+
确认删除会话?
+
该操作不可撤销。将删除会话及其全部消息:
{pendingDelete.title}
@@ -1306,7 +1305,7 @@ export function App() {
onClick={() => setPendingDelete(null)}
variant="secondary"
style={{
- fontSize: 14,
+ fontSize: "var(--ui-font-size-md)",
}}
>
取消
@@ -1315,7 +1314,7 @@ export function App() {
onClick={confirmDeleteConversation}
variant="danger"
style={{
- fontSize: 14,
+ fontSize: "var(--ui-font-size-md)",
}}
>
确认删除
diff --git a/oneapi-gateway/chat-ui/tsconfig.json b/oneapi-gateway/chat-ui/tsconfig.json
index 8acb0ae..88fea78 100644
--- a/oneapi-gateway/chat-ui/tsconfig.json
+++ b/oneapi-gateway/chat-ui/tsconfig.json
@@ -8,7 +8,6 @@
"strict": true,
"skipLibCheck": true,
"noEmit": true,
- "baseUrl": ".",
"paths": {
"@easyai/ui": ["../shared-ui/src/index"],
"@easyai/ui/*": ["../shared-ui/src/*"]
diff --git a/oneapi-gateway/package-lock.json b/oneapi-gateway/package-lock.json
index 2d7648c..03fddb9 100644
--- a/oneapi-gateway/package-lock.json
+++ b/oneapi-gateway/package-lock.json
@@ -8,22 +8,18 @@
"name": "oneapi-gateway",
"version": "0.1.0",
"dependencies": {
- "@fastify/cors": "^11.2.0",
- "@fastify/static": "^9.1.3",
- "fastify": "^5.8.5",
- "jose": "^6.2.3",
- "js-yaml": "^4.1.1",
- "pg": "^8.21.0",
- "prom-client": "^15.1.3",
- "redis": "^5.12.1",
- "swagger-ui-dist": "^5.32.6"
+ "@fastify/cors": "^11.4.3",
+ "@fastify/static": "^10.1.12",
+ "fastify": "^5.12.8",
+ "js-yaml": "^5.5.0",
+ "pg": "^8.23.1",
+ "redis": "^6.3.1"
},
"devDependencies": {
- "@types/js-yaml": "^4.0.9",
- "@types/node": "^25.9.1",
- "@types/pg": "^8.20.0",
- "tsx": "^4.22.3",
- "typescript": "^6.0.3"
+ "@types/node": "^26.6.6",
+ "@types/pg": "^8.23.1",
+ "tsx": "^4.23.15",
+ "typescript": "^7.0.2"
}
},
"node_modules/@esbuild/aix-ppc64": {
@@ -506,9 +502,9 @@
}
},
"node_modules/@fastify/cors": {
- "version": "11.2.0",
- "resolved": "https://registry.npmjs.org/@fastify/cors/-/cors-11.2.0.tgz",
- "integrity": "sha512-LbLHBuSAdGdSFZYTLVA3+Ch2t+sA6nq3Ejc6XLAKiQ6ViS2qFnvicpj0htsx03FyYeLs04HfRNBsz/a8SvbcUw==",
+ "version": "11.4.3",
+ "resolved": "https://registry.npmjs.org/@fastify/cors/-/cors-11.4.3.tgz",
+ "integrity": "sha512-6NNFNR1i9t1oG1WlQftwc2ugElFm4cG75ylYyGNiKKiyxlVGueneup9MQ9Nd3eI4lT6kVOJaxV1Jqa727/E4jg==",
"funding": [
{
"type": "github",
@@ -521,7 +517,7 @@
],
"license": "MIT",
"dependencies": {
- "fastify-plugin": "^5.0.0",
+ "fastify-plugin": "^6.0.0",
"toad-cache": "^3.7.0"
}
},
@@ -616,9 +612,9 @@
}
},
"node_modules/@fastify/send": {
- "version": "4.1.0",
- "resolved": "https://registry.npmjs.org/@fastify/send/-/send-4.1.0.tgz",
- "integrity": "sha512-TMYeQLCBSy2TOFmV95hQWkiTYgC/SEx7vMdV+wnZVX4tt8VBLKzmH8vV9OzJehV0+XBfg+WxPMt5wp+JBUKsVw==",
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/@fastify/send/-/send-4.2.1.tgz",
+ "integrity": "sha512-zOB8L9z444PnGbd1Nd7gNXPz/7bnDR8Z4KNTNSwLVQuE3cTGsU9qUj1N4SjXKK0Tq4cauZYTwB+tqvlqosuKsw==",
"funding": [
{
"type": "github",
@@ -639,9 +635,9 @@
}
},
"node_modules/@fastify/static": {
- "version": "9.1.3",
- "resolved": "https://registry.npmjs.org/@fastify/static/-/static-9.1.3.tgz",
- "integrity": "sha512-aXrYtsiryLhRxRNaxNqsn7FUISeb7rB9q4eHUPIot5aeQBLNahnz1m6thzm7JWC1poSGXS9XrX8DvuMivp2hkQ==",
+ "version": "10.1.12",
+ "resolved": "https://registry.npmjs.org/@fastify/static/-/static-10.1.12.tgz",
+ "integrity": "sha512-D0pmf8OgurIsKiIjxC8ZJP/bCYnUSAiU6PS/se/6Me63UoliAu8FqrzDRX8FdgJMqFMXy45ISlfUZ1Gi6AJnqA==",
"funding": [
{
"type": "github",
@@ -655,13 +651,20 @@
"license": "MIT",
"dependencies": {
"@fastify/accept-negotiator": "^2.0.0",
- "@fastify/send": "^4.0.0",
- "content-disposition": "^1.0.1",
- "fastify-plugin": "^5.0.0",
+ "@fastify/error": "^4.0.0",
+ "@fastify/send": "^4.2.0",
+ "content-disposition": "^3.0.0",
+ "fastify-plugin": "^6.0.0",
"fastq": "^1.17.1",
- "glob": "^13.0.0"
+ "glob": "^14.0.0"
}
},
+ "node_modules/@isaacs/nonrecursive-glob-match": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz",
+ "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==",
+ "license": "BlueOak-1.0.0"
+ },
"node_modules/@lukeed/ms": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/@lukeed/ms/-/ms-2.0.2.tgz",
@@ -671,15 +674,6 @@
"node": ">=8"
}
},
- "node_modules/@opentelemetry/api": {
- "version": "1.9.1",
- "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz",
- "integrity": "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==",
- "license": "Apache-2.0",
- "engines": {
- "node": ">=8.0.0"
- }
- },
"node_modules/@pinojs/redact": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
@@ -687,27 +681,24 @@
"license": "MIT"
},
"node_modules/@redis/bloom": {
- "version": "5.12.1",
- "resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-5.12.1.tgz",
- "integrity": "sha512-PUUfv+ms7jgPSBVoo/DN4AkPHj4D5TZSd6SbJX7egzBplkYUcKmHRE8RKia7UtZ8bSQbLguLvxVO+asKtQfZWA==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-6.3.1.tgz",
+ "integrity": "sha512-dpF9j2yJDoPzSCaZn0MSB3xzmnXQVJeTSAWJcQVcgbmluwhpFeemmII0cF1t+WYfoVS+shEFq79+MmUItgzJLg==",
"license": "MIT",
"engines": {
- "node": ">= 18.19.0"
+ "node": ">= 20.0.0"
},
"peerDependencies": {
- "@redis/client": "^5.12.1"
+ "@redis/client": "^6.3.1"
}
},
"node_modules/@redis/client": {
- "version": "5.12.1",
- "resolved": "https://registry.npmjs.org/@redis/client/-/client-5.12.1.tgz",
- "integrity": "sha512-7aPGWeqA3uFm43o19umzdl16CEjK/JQGtSXVPevplTaOU3VJA/rseBC1QvYUz9lLDIMBimc4SW/zrW4S89BaCA==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/@redis/client/-/client-6.3.1.tgz",
+ "integrity": "sha512-masbfVKULdoAofwddepZxRhWa4w6zvBHn6TRn90TRPrRkVIlGCur3pFqwWaCbMxtYI9twepkz63e/T/tEH8GjA==",
"license": "MIT",
- "dependencies": {
- "cluster-key-slot": "1.1.2"
- },
"engines": {
- "node": ">= 18.19.0"
+ "node": ">= 20.0.0"
},
"peerDependencies": {
"@node-rs/xxhash": "^1.1.0",
@@ -723,69 +714,55 @@
}
},
"node_modules/@redis/json": {
- "version": "5.12.1",
- "resolved": "https://registry.npmjs.org/@redis/json/-/json-5.12.1.tgz",
- "integrity": "sha512-eOze75esLve4vfqDel7aMX08CNaiLLQS2fV8mpRN9NxPe1rVR4vQyYiW/OgtGUysF6QOr9ANhfxABKNOJfXdKg==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/@redis/json/-/json-6.3.1.tgz",
+ "integrity": "sha512-fMz4kUwJzEftcU9EMaqsjZcUwzpTQLOYRqhQsAD6uKvZWeamblK13ZhgO5SzVSZVk31jmwLeTRpU5GAl5egfUw==",
"license": "MIT",
"engines": {
- "node": ">= 18.19.0"
+ "node": ">= 20.0.0"
},
"peerDependencies": {
- "@redis/client": "^5.12.1"
+ "@redis/client": "^6.3.1"
}
},
"node_modules/@redis/search": {
- "version": "5.12.1",
- "resolved": "https://registry.npmjs.org/@redis/search/-/search-5.12.1.tgz",
- "integrity": "sha512-ItlxbxC9cKI6IU1TLWoczwJCRb6TdmkEpWv05UrPawqaAnWGRu3rcIqsc5vN483T2fSociuyV1UkWIL5I4//2w==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/@redis/search/-/search-6.3.1.tgz",
+ "integrity": "sha512-T67pvPUpW82VrZLvihO8O2DFMC7eY2oMAzMzapCbiPZn7mdWqHMEIlohYim12gIawT5kn6qT/Cvmm4WulKB+kQ==",
"license": "MIT",
"engines": {
- "node": ">= 18.19.0"
+ "node": ">= 20.0.0"
},
"peerDependencies": {
- "@redis/client": "^5.12.1"
+ "@redis/client": "^6.3.1"
}
},
"node_modules/@redis/time-series": {
- "version": "5.12.1",
- "resolved": "https://registry.npmjs.org/@redis/time-series/-/time-series-5.12.1.tgz",
- "integrity": "sha512-c6JL6E3EcZJuNqKFz+KM+l9l5mpcQiKvTwgA3blt5glWJ8hjDk0yeHN3beE/MpqYIQ8UEX44ItQzgkE/gCBELQ==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/@redis/time-series/-/time-series-6.3.1.tgz",
+ "integrity": "sha512-MNDgrm+i63M/1a+XA+HcDsScwt4uBh/fGGJ84swTQZTFK5K5wMmxdlTRa4ZgmNJzjxMaszW/ipPScMUGV3aAMg==",
"license": "MIT",
"engines": {
- "node": ">= 18.19.0"
+ "node": ">= 20.0.0"
},
"peerDependencies": {
- "@redis/client": "^5.12.1"
+ "@redis/client": "^6.3.1"
}
},
- "node_modules/@scarf/scarf": {
- "version": "1.4.0",
- "resolved": "https://registry.npmjs.org/@scarf/scarf/-/scarf-1.4.0.tgz",
- "integrity": "sha512-xxeapPiUXdZAE3che6f3xogoJPeZgig6omHEy1rIY5WVsB3H2BHNnZH+gHG6x91SCWyQCzWGsuL2Hh3ClO5/qQ==",
- "hasInstallScript": true,
- "license": "Apache-2.0"
- },
- "node_modules/@types/js-yaml": {
- "version": "4.0.9",
- "resolved": "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-4.0.9.tgz",
- "integrity": "sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/@types/node": {
- "version": "25.9.1",
- "resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.1.tgz",
- "integrity": "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg==",
+ "version": "26.6.6",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
+ "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
"dev": true,
"license": "MIT",
"dependencies": {
- "undici-types": ">=7.24.0 <7.24.7"
+ "undici-types": "~8.9.0"
}
},
"node_modules/@types/pg": {
- "version": "8.20.0",
- "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.20.0.tgz",
- "integrity": "sha512-bEPFOaMAHTEP1EzpvHTbmwR8UsFyHSKsRisLIHVMXnpNefSbGA1bD6CVy+qKjGSqmZqNqBDV2azOBo8TgkcVow==",
+ "version": "8.23.1",
+ "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.23.1.tgz",
+ "integrity": "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -794,6 +771,346 @@
"pg-types": "^2.2.0"
}
},
+ "node_modules/@typescript/typescript-aix-ppc64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
+ "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-darwin-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
+ "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-darwin-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
+ "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-freebsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-freebsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
+ "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-arm": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
+ "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
+ "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-loong64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
+ "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-mips64el": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
+ "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-ppc64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
+ "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-riscv64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
+ "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-s390x": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
+ "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
+ "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-netbsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-netbsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
+ "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-openbsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-openbsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
+ "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-sunos-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
+ "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-win32-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
+ "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-win32-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
+ "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
"node_modules/abstract-logging": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz",
@@ -834,10 +1151,20 @@
}
},
"node_modules/argparse": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
- "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
- "license": "Python-2.0"
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-3.0.4.tgz",
+ "integrity": "sha512-fwWK3Zq22l4XJJjx5mcBHGikIk+hJqO+32dPm0Jur7+rtG5x1scOjSfdT9ZKeWHPpsya/l0HHK4tDImBkTrtvA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/puzrin"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/nodeca"
+ }
+ ],
+ "license": "PSF-2.0"
},
"node_modules/atomic-sleep": {
"version": "1.0.0",
@@ -877,40 +1204,25 @@
"node": "18 || 20 || >=22"
}
},
- "node_modules/bintrees": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/bintrees/-/bintrees-1.0.2.tgz",
- "integrity": "sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==",
- "license": "MIT"
- },
"node_modules/brace-expansion": {
- "version": "5.0.6",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz",
- "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==",
+ "version": "5.0.13",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz",
+ "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==",
"license": "MIT",
"dependencies": {
"balanced-match": "^4.0.2"
},
"engines": {
- "node": "18 || 20 || >=22"
- }
- },
- "node_modules/cluster-key-slot": {
- "version": "1.1.2",
- "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz",
- "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==",
- "license": "Apache-2.0",
- "engines": {
- "node": ">=0.10.0"
+ "node": "20 || >=22"
}
},
"node_modules/content-disposition": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
- "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-3.1.0.tgz",
+ "integrity": "sha512-6lwVDK9bsenmMu7hxcLuUiu+FzFBDAdfQR1LKbE+SCo7/Qfpm2NG8X9f8AJgumfoVID/4r1stSxcmCeiT7pfkQ==",
"license": "MIT",
"engines": {
- "node": ">=18"
+ "node": ">=22"
},
"funding": {
"type": "opencollective",
@@ -1058,9 +1370,9 @@
"license": "BSD-3-Clause"
},
"node_modules/fastify": {
- "version": "5.8.5",
- "resolved": "https://registry.npmjs.org/fastify/-/fastify-5.8.5.tgz",
- "integrity": "sha512-Yqptv59pQzPgQUSIm87hMqHJmdkb1+GPxdE6vW6FRyVE9G86mt7rOghitiU4JHRaTyDUk9pfeKmDeu70lAwM4Q==",
+ "version": "5.12.8",
+ "resolved": "https://registry.npmjs.org/fastify/-/fastify-5.12.8.tgz",
+ "integrity": "sha512-moP8exb2sCHLUbJkwp+I6C0padhy4D8lp0SdmzY7HhSdZuqm7O/u3o2aq7u8okaQ//33QDzj3G/u+FsSdB8Qzw==",
"funding": [
{
"type": "github",
@@ -1079,11 +1391,11 @@
"@fastify/proxy-addr": "^5.0.0",
"abstract-logging": "^2.0.1",
"avvio": "^9.0.0",
- "fast-json-stringify": "^6.0.0",
- "find-my-way": "^9.0.0",
+ "fast-json-stringify": "^7.0.0",
+ "find-my-way": "^9.10.0",
"light-my-request": "^6.0.0",
"pino": "^9.14.0 || ^10.1.0",
- "process-warning": "^5.0.0",
+ "process-warning": "^5.1.0",
"rfdc": "^1.3.1",
"secure-json-parse": "^4.0.0",
"semver": "^7.6.0",
@@ -1091,9 +1403,9 @@
}
},
"node_modules/fastify-plugin": {
- "version": "5.1.0",
- "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-5.1.0.tgz",
- "integrity": "sha512-FAIDA8eovSt5qcDgcBvDuX/v0Cjz0ohGhENZ/wpc3y+oZCY2afZ9Baqql3g/lC+OHRnciQol4ww7tuthOb9idw==",
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-6.0.1.tgz",
+ "integrity": "sha512-4wW4RxSmvPXLrh5mgQEiu43qU3bw44N2ss4FTkTkQIbprUhE+/s43QX0j/ttcztdWK7PEkHqVthdc5GdEGDvjA==",
"funding": [
{
"type": "github",
@@ -1106,6 +1418,46 @@
],
"license": "MIT"
},
+ "node_modules/fastify/node_modules/fast-json-stringify": {
+ "version": "7.3.9",
+ "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-7.3.9.tgz",
+ "integrity": "sha512-5wxgeniisjX/pgaAeCN9tTizOhMEl5sZepJ+8N0YfFCRjc4X3BcDlswqgbBMFghbsRPVhnmFovdmdo0vpfIZ+g==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@fastify/merge-json-schemas": "^0.2.0",
+ "ajv": "^8.12.0",
+ "ajv-formats": "^3.0.1",
+ "fast-uri": "^4.0.0",
+ "json-schema-ref-resolver": "^3.0.0",
+ "rfdc": "^1.2.0"
+ }
+ },
+ "node_modules/fastify/node_modules/fast-uri": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-4.2.3.tgz",
+ "integrity": "sha512-I1PXwP5eAhlNlcdpjt9CgB59op2ZvZfxw+BkqGFVIUOgNpCVTcTqp3HhTX7brxj5vsip+nSY4nTvff+eIA76hg==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
"node_modules/fastq": {
"version": "1.20.1",
"resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz",
@@ -1116,9 +1468,9 @@
}
},
"node_modules/find-my-way": {
- "version": "9.6.0",
- "resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.6.0.tgz",
- "integrity": "sha512-Zf4Xve4RymLl7NgaavNebZ01joJ8MfVerOG43wy7SHLO+r+K0C6d/SE0BiR7AV5V1VOCFlOP7ecdo+I4qmiHrQ==",
+ "version": "9.10.2",
+ "resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.10.2.tgz",
+ "integrity": "sha512-gbLMuTm2FV5QiRh/eM0uhL4nyOvbSqqa2K3mASAtkIqxvY8ZmoLOCLMd2syLWT/SyhrvOR7GPxOKj/kcV6o8bg==",
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.3",
@@ -1145,14 +1497,14 @@
}
},
"node_modules/glob": {
- "version": "13.0.6",
- "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz",
- "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==",
+ "version": "14.0.6",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-14.0.6.tgz",
+ "integrity": "sha512-OwXjVP2svY5EyLY75Vek96C8qK43gqrt4xsZ+qSILdnaEiJPXkd62mcfUSNx/TQErQRdu5uM5kF67sfONragKw==",
"license": "BlueOak-1.0.0",
"dependencies": {
- "minimatch": "^10.2.2",
+ "minimatch": "^11.0.5",
"minipass": "^7.1.3",
- "path-scurry": "^2.0.2"
+ "path-scurry": "^3.0.0"
},
"engines": {
"node": "18 || 20 || >=22"
@@ -1196,25 +1548,26 @@
"node": ">= 10"
}
},
- "node_modules/jose": {
- "version": "6.2.3",
- "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.3.tgz",
- "integrity": "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==",
- "license": "MIT",
- "funding": {
- "url": "https://github.com/sponsors/panva"
- }
- },
"node_modules/js-yaml": {
- "version": "4.1.1",
- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
- "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
+ "version": "5.5.0",
+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.5.0.tgz",
+ "integrity": "sha512-paNr4LFIFPjeeSmwNYdrb8FafLLG/Cr2Af3GjbsHJ5CxIjH4r0c2emlmRdAtpPAieP1gRVzk6buBbVP5gBMGAg==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/puzrin"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/nodeca"
+ }
+ ],
"license": "MIT",
"dependencies": {
- "argparse": "^2.0.1"
+ "argparse": "^3.0.3"
},
"bin": {
- "js-yaml": "bin/js-yaml.js"
+ "js-yaml": "bin/js-yaml.mjs"
}
},
"node_modules/json-schema-ref-resolver": {
@@ -1280,9 +1633,9 @@
"license": "MIT"
},
"node_modules/lru-cache": {
- "version": "11.4.0",
- "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.4.0.tgz",
- "integrity": "sha512-W+R+kFL4HgVxONq2bhXPi3bGpzGe/yEhVOp233qw9wCRtgncJ15P3bC+e4zZMu4Cq7d+WAJjXGW0uUkifhcatA==",
+ "version": "11.5.3",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
+ "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
"license": "BlueOak-1.0.0",
"engines": {
"node": "20 || >=22"
@@ -1301,15 +1654,16 @@
}
},
"node_modules/minimatch": {
- "version": "10.2.5",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
- "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",
+ "version": "11.0.9",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz",
+ "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==",
"license": "BlueOak-1.0.0",
"dependencies": {
- "brace-expansion": "^5.0.5"
+ "@isaacs/nonrecursive-glob-match": "^1.1.0",
+ "brace-expansion": "^5.0.12"
},
"engines": {
- "node": "18 || 20 || >=22"
+ "node": "20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
@@ -1334,9 +1688,9 @@
}
},
"node_modules/path-scurry": {
- "version": "2.0.2",
- "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz",
- "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==",
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz",
+ "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==",
"license": "BlueOak-1.0.0",
"dependencies": {
"lru-cache": "^11.0.0",
@@ -1350,14 +1704,14 @@
}
},
"node_modules/pg": {
- "version": "8.21.0",
- "resolved": "https://registry.npmjs.org/pg/-/pg-8.21.0.tgz",
- "integrity": "sha512-AUP1EYJuHraQGsVoCQVIcM7TEJVGtDzxWtGFZd8rds9d+CCXlU5Js1rYgfLNvxy9iJrpHjGrRjoi/3BT9fRyiA==",
+ "version": "8.23.1",
+ "resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz",
+ "integrity": "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==",
"license": "MIT",
"dependencies": {
- "pg-connection-string": "^2.13.0",
+ "pg-connection-string": "^2.14.1",
"pg-pool": "^3.14.0",
- "pg-protocol": "^1.14.0",
+ "pg-protocol": "^1.16.1",
"pg-types": "2.2.0",
"pgpass": "1.0.5"
},
@@ -1365,7 +1719,7 @@
"node": ">= 16.0.0"
},
"optionalDependencies": {
- "pg-cloudflare": "^1.4.0"
+ "pg-cloudflare": "^1.4.1"
},
"peerDependencies": {
"pg-native": ">=3.0.1"
@@ -1377,16 +1731,16 @@
}
},
"node_modules/pg-cloudflare": {
- "version": "1.4.0",
- "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.0.tgz",
- "integrity": "sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A==",
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz",
+ "integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==",
"license": "MIT",
"optional": true
},
"node_modules/pg-connection-string": {
- "version": "2.13.0",
- "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.13.0.tgz",
- "integrity": "sha512-EMnU9E2fSULdsbErBbMaXJvFeD9B4+nPcM3f+4lsiCR0BHLPrLVjv3DbyM2hgQQviKJaTWIRRTjKjWlHg3p2ig==",
+ "version": "2.14.1",
+ "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz",
+ "integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==",
"license": "MIT"
},
"node_modules/pg-int8": {
@@ -1408,9 +1762,9 @@
}
},
"node_modules/pg-protocol": {
- "version": "1.14.0",
- "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.14.0.tgz",
- "integrity": "sha512-n5taZ1kO3s9ngDTVxsEznOqCyToTgz0FLuPq0B33COy5pPpuWJpY3/2oRBVETuOgzdqRXfWpM9HIhp2LBBT1BA==",
+ "version": "1.16.1",
+ "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz",
+ "integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==",
"license": "MIT"
},
"node_modules/pg-types": {
@@ -1515,9 +1869,9 @@
}
},
"node_modules/process-warning": {
- "version": "5.0.0",
- "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz",
- "integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==",
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.1.tgz",
+ "integrity": "sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==",
"funding": [
{
"type": "github",
@@ -1530,19 +1884,6 @@
],
"license": "MIT"
},
- "node_modules/prom-client": {
- "version": "15.1.3",
- "resolved": "https://registry.npmjs.org/prom-client/-/prom-client-15.1.3.tgz",
- "integrity": "sha512-6ZiOBfCywsD4k1BN9IX0uZhF+tJkV8q8llP64G5Hajs4JOeVLPCwpPVcpXy3BwYiUGgyJzsJJQeOIv7+hDSq8g==",
- "license": "Apache-2.0",
- "dependencies": {
- "@opentelemetry/api": "^1.4.0",
- "tdigest": "^0.1.1"
- },
- "engines": {
- "node": "^16 || ^18 || >=20"
- }
- },
"node_modules/quick-format-unescaped": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz",
@@ -1559,19 +1900,19 @@
}
},
"node_modules/redis": {
- "version": "5.12.1",
- "resolved": "https://registry.npmjs.org/redis/-/redis-5.12.1.tgz",
- "integrity": "sha512-LDsoVvb/CpoV9EN3FXvgvSHNJWuCIzl9MiO3ppOevuGLpSGJhwfQjpEwfFJcQvNSddHADDdZaWx0HnmMxRXG7g==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/redis/-/redis-6.3.1.tgz",
+ "integrity": "sha512-mV96ZKxQ4CGn3SyEGaY0Lb9YA443mdVey3c+mdr0NAUaBxiOZGoYCWX8PoM55kictSOmxlJRtZJxIsmZm3jL+w==",
"license": "MIT",
"dependencies": {
- "@redis/bloom": "5.12.1",
- "@redis/client": "5.12.1",
- "@redis/json": "5.12.1",
- "@redis/search": "5.12.1",
- "@redis/time-series": "5.12.1"
+ "@redis/bloom": "6.3.1",
+ "@redis/client": "6.3.1",
+ "@redis/json": "6.3.1",
+ "@redis/search": "6.3.1",
+ "@redis/time-series": "6.3.1"
},
"engines": {
- "node": ">= 18.19.0"
+ "node": ">= 20.0.0"
}
},
"node_modules/require-from-string": {
@@ -1584,9 +1925,9 @@
}
},
"node_modules/ret": {
- "version": "0.5.0",
- "resolved": "https://registry.npmjs.org/ret/-/ret-0.5.0.tgz",
- "integrity": "sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==",
+ "version": "0.5.1",
+ "resolved": "https://registry.npmjs.org/ret/-/ret-0.5.1.tgz",
+ "integrity": "sha512-Z/nyvABwcRnRD2mMP7Kz6G1dFZZqX1mNErOnxF42OCQKE07b9k9hK9SQxHL3LFEZUdzQaLM4dId1E/E6Vm4WhA==",
"license": "MIT",
"engines": {
"node": ">=10"
@@ -1609,9 +1950,9 @@
"license": "MIT"
},
"node_modules/safe-regex2": {
- "version": "5.1.1",
- "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.1.1.tgz",
- "integrity": "sha512-mOSBvHGDZMuIEZMdOz/aCEYDCv0E7nfcNsIhUF+/P+xC7Hyf3FkvymqgPbg9D1EdSGu+uKbJgy09K/RKKc7kJA==",
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.1.2.tgz",
+ "integrity": "sha512-tAtCGFPPP02VroDVzp4daGi6bC7jWG+41D47GKf18FeH/ubvKQHT9VmhAkvtjNOmJwqtApzWeUpEhkyEYULvmw==",
"funding": [
{
"type": "github",
@@ -1706,24 +2047,6 @@
"node": ">= 0.8"
}
},
- "node_modules/swagger-ui-dist": {
- "version": "5.32.6",
- "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.32.6.tgz",
- "integrity": "sha512-75ttZNaYCLoFPnozPZcTUU6mS3wKT8l7WLjU5zJSHFeJa23i5vtnze6IiCl4jDMPeQTXVXIgovq4M11NNfQvSA==",
- "license": "Apache-2.0",
- "dependencies": {
- "@scarf/scarf": "=1.4.0"
- }
- },
- "node_modules/tdigest": {
- "version": "0.1.2",
- "resolved": "https://registry.npmjs.org/tdigest/-/tdigest-0.1.2.tgz",
- "integrity": "sha512-+G0LLgjjo9BZX2MfdvPfH+MKLCrxlXSYec5DaPYP1fe6Iyhf0/fSmJ0bFiZ1F8BT6cGXl2LpltQptzjXKWEkKA==",
- "license": "MIT",
- "dependencies": {
- "bintrees": "1.0.2"
- }
- },
"node_modules/thread-stream": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz",
@@ -1761,9 +2084,9 @@
}
},
"node_modules/tsx": {
- "version": "4.22.3",
- "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.22.3.tgz",
- "integrity": "sha512-mdoNxBC/cSQObGGVQ5Bpn5i+yv7j68gk3Nfm3wFjcJg3Z0Mix9jzAFfP12prmm5eVGmDKtp0yyArrs0Q+8gZHg==",
+ "version": "4.23.15",
+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz",
+ "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -1780,23 +2103,44 @@
}
},
"node_modules/typescript": {
- "version": "6.0.3",
- "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
- "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
+ "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
"dev": true,
"license": "Apache-2.0",
"bin": {
- "tsc": "bin/tsc",
- "tsserver": "bin/tsserver"
+ "tsc": "bin/tsc"
},
"engines": {
- "node": ">=14.17"
+ "node": ">=16.20.0"
+ },
+ "optionalDependencies": {
+ "@typescript/typescript-aix-ppc64": "7.0.2",
+ "@typescript/typescript-darwin-arm64": "7.0.2",
+ "@typescript/typescript-darwin-x64": "7.0.2",
+ "@typescript/typescript-freebsd-arm64": "7.0.2",
+ "@typescript/typescript-freebsd-x64": "7.0.2",
+ "@typescript/typescript-linux-arm": "7.0.2",
+ "@typescript/typescript-linux-arm64": "7.0.2",
+ "@typescript/typescript-linux-loong64": "7.0.2",
+ "@typescript/typescript-linux-mips64el": "7.0.2",
+ "@typescript/typescript-linux-ppc64": "7.0.2",
+ "@typescript/typescript-linux-riscv64": "7.0.2",
+ "@typescript/typescript-linux-s390x": "7.0.2",
+ "@typescript/typescript-linux-x64": "7.0.2",
+ "@typescript/typescript-netbsd-arm64": "7.0.2",
+ "@typescript/typescript-netbsd-x64": "7.0.2",
+ "@typescript/typescript-openbsd-arm64": "7.0.2",
+ "@typescript/typescript-openbsd-x64": "7.0.2",
+ "@typescript/typescript-sunos-x64": "7.0.2",
+ "@typescript/typescript-win32-arm64": "7.0.2",
+ "@typescript/typescript-win32-x64": "7.0.2"
}
},
"node_modules/undici-types": {
- "version": "7.24.6",
- "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
- "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
+ "version": "8.9.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
+ "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"dev": true,
"license": "MIT"
},
diff --git a/oneapi-gateway/package.json b/oneapi-gateway/package.json
index 4dcd331..c973e09 100644
--- a/oneapi-gateway/package.json
+++ b/oneapi-gateway/package.json
@@ -11,21 +11,17 @@
"doc-audit": "node --import tsx ../tools/doc-audit/check-docs.ts"
},
"dependencies": {
- "@fastify/cors": "^11.2.0",
- "@fastify/static": "^9.1.3",
- "fastify": "^5.8.5",
- "jose": "^6.2.3",
- "js-yaml": "^4.1.1",
- "pg": "^8.21.0",
- "prom-client": "^15.1.3",
- "redis": "^5.12.1",
- "swagger-ui-dist": "^5.32.6"
+ "@fastify/cors": "^11.4.3",
+ "@fastify/static": "^10.1.12",
+ "fastify": "^5.12.8",
+ "js-yaml": "^5.5.0",
+ "pg": "^8.23.1",
+ "redis": "^6.3.1"
},
"devDependencies": {
- "@types/js-yaml": "^4.0.9",
- "@types/node": "^25.9.1",
- "@types/pg": "^8.20.0",
- "tsx": "^4.22.3",
- "typescript": "^6.0.3"
+ "@types/node": "^26.6.6",
+ "@types/pg": "^8.23.1",
+ "tsx": "^4.23.15",
+ "typescript": "^7.0.2"
}
}
diff --git a/oneapi-gateway/shared-ui/package-lock.json b/oneapi-gateway/shared-ui/package-lock.json
index 9dd13aa..fc59c7e 100644
--- a/oneapi-gateway/shared-ui/package-lock.json
+++ b/oneapi-gateway/shared-ui/package-lock.json
@@ -8,8 +8,9 @@
"name": "@easyai/ui",
"version": "0.1.0",
"devDependencies": {
- "@types/react": "^19.1.12",
- "@types/react-dom": "^19.1.8"
+ "@types/react": "^19.3.0",
+ "@types/react-dom": "^19.3.0",
+ "typescript": "^7.0.2"
},
"peerDependencies": {
"react": "^19.1.1",
@@ -17,9 +18,9 @@
}
},
"node_modules/@types/react": {
- "version": "19.2.16",
- "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.16.tgz",
- "integrity": "sha512-esJiCAnl0kfpNdE69f3So4WJUXy95dLZydX0KwK46riIHDzHM7O9Vtf9xCHW0PXIqvgqNrswl522kA/5yx+F4w==",
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
+ "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -27,13 +28,353 @@
}
},
"node_modules/@types/react-dom": {
- "version": "19.2.3",
- "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
- "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz",
+ "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==",
"dev": true,
"license": "MIT",
"peerDependencies": {
- "@types/react": "^19.2.0"
+ "@types/react": "^19.3.0"
+ }
+ },
+ "node_modules/@typescript/typescript-aix-ppc64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
+ "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-darwin-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
+ "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-darwin-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
+ "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-freebsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-freebsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
+ "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-arm": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
+ "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
+ "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-loong64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
+ "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-mips64el": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
+ "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-ppc64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
+ "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-riscv64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
+ "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-s390x": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
+ "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
+ "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-netbsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-netbsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
+ "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-openbsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-openbsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
+ "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-sunos-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
+ "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-win32-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
+ "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-win32-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
+ "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
}
},
"node_modules/csstype": {
@@ -72,6 +413,41 @@
"integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
"license": "MIT",
"peer": true
+ },
+ "node_modules/typescript": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
+ "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc"
+ },
+ "engines": {
+ "node": ">=16.20.0"
+ },
+ "optionalDependencies": {
+ "@typescript/typescript-aix-ppc64": "7.0.2",
+ "@typescript/typescript-darwin-arm64": "7.0.2",
+ "@typescript/typescript-darwin-x64": "7.0.2",
+ "@typescript/typescript-freebsd-arm64": "7.0.2",
+ "@typescript/typescript-freebsd-x64": "7.0.2",
+ "@typescript/typescript-linux-arm": "7.0.2",
+ "@typescript/typescript-linux-arm64": "7.0.2",
+ "@typescript/typescript-linux-loong64": "7.0.2",
+ "@typescript/typescript-linux-mips64el": "7.0.2",
+ "@typescript/typescript-linux-ppc64": "7.0.2",
+ "@typescript/typescript-linux-riscv64": "7.0.2",
+ "@typescript/typescript-linux-s390x": "7.0.2",
+ "@typescript/typescript-linux-x64": "7.0.2",
+ "@typescript/typescript-netbsd-arm64": "7.0.2",
+ "@typescript/typescript-netbsd-x64": "7.0.2",
+ "@typescript/typescript-openbsd-arm64": "7.0.2",
+ "@typescript/typescript-openbsd-x64": "7.0.2",
+ "@typescript/typescript-sunos-x64": "7.0.2",
+ "@typescript/typescript-win32-arm64": "7.0.2",
+ "@typescript/typescript-win32-x64": "7.0.2"
+ }
}
}
}
diff --git a/oneapi-gateway/shared-ui/package.json b/oneapi-gateway/shared-ui/package.json
index 3139db8..b573575 100644
--- a/oneapi-gateway/shared-ui/package.json
+++ b/oneapi-gateway/shared-ui/package.json
@@ -4,11 +4,12 @@
"version": "0.1.0",
"type": "module",
"peerDependencies": {
- "react": "^19.1.1",
- "react-dom": "^19.1.1"
+ "react": "^19.3.1",
+ "react-dom": "^19.3.1"
},
"devDependencies": {
- "@types/react": "^19.1.12",
- "@types/react-dom": "^19.1.8"
+ "@types/react": "^19.3.0",
+ "@types/react-dom": "^19.3.0",
+ "typescript": "^7.0.2"
}
}
diff --git a/oneapi-gateway/shared-ui/src/styles.css b/oneapi-gateway/shared-ui/src/styles.css
index 18d3d22..dc1c255 100644
--- a/oneapi-gateway/shared-ui/src/styles.css
+++ b/oneapi-gateway/shared-ui/src/styles.css
@@ -7,6 +7,18 @@
--ui-control-height: 40px;
--ui-control-height-compact: 36px;
--ui-control-gap: 10px;
+ --ui-control-padding-x: 14px;
+ --ui-control-font-size: var(--ui-font-size-md);
+ --ui-control-line-height: 1.35;
+ --ui-card-padding: 16px;
+ --ui-text-line-height: 1.62;
+ --ui-font-size-xs: 12px;
+ --ui-font-size-sm: 13px;
+ --ui-font-size-md: 14px;
+ --ui-font-size-lg: 16px;
+ --ui-font-size-xl: 18px;
+ --ui-font-size-2xl: 24px;
+ --ui-font-size-3xl: 32px;
--ui-space-1: 4px;
--ui-space-2: 8px;
--ui-space-3: 12px;
@@ -62,11 +74,43 @@ body {
radial-gradient(circle at right top, rgba(14, 165, 233, 0.1), transparent 24%),
var(--ui-bg);
font-family: var(--ui-font-sans);
+ font-size: var(--ui-font-size-md);
+ line-height: var(--ui-text-line-height);
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
+h1,
+h2,
+h3,
+p {
+ margin-top: 0;
+}
+
+h1,
+.ui-page-title {
+ margin-bottom: 0;
+ font-size: clamp(var(--ui-font-size-2xl), 2.4vw, var(--ui-font-size-3xl));
+ font-weight: 750;
+ letter-spacing: -0.03em;
+ line-height: 1.12;
+}
+
+h2,
+.ui-page-subtitle {
+ margin-bottom: 0;
+ font-size: var(--ui-font-size-2xl);
+ font-weight: 720;
+ letter-spacing: -0.025em;
+ line-height: 1.18;
+}
+
+h3 {
+ font-size: var(--ui-font-size-xl);
+ line-height: 1.28;
+}
+
* {
box-sizing: border-box;
}
@@ -85,7 +129,7 @@ input[type="submit"],
input[type="reset"],
select {
min-height: var(--ui-control-height) !important;
- padding: 0 14px !important;
+ padding: 0 var(--ui-control-padding-x) !important;
border-radius: var(--ui-radius-md) !important;
border: 1px solid var(--ui-border) !important;
background: var(--ui-bg-elevated);
@@ -97,7 +141,7 @@ button {
align-items: center;
justify-content: center;
cursor: pointer;
- line-height: 1;
+ line-height: var(--ui-control-line-height);
transition:
transform 120ms ease,
border-color 120ms ease,
@@ -108,13 +152,15 @@ button {
.ui-button {
gap: 8px;
white-space: nowrap;
+ min-width: max-content;
+ letter-spacing: 0.01em;
}
.ui-button[data-size="sm"] {
min-height: 34px !important;
padding: 0 12px !important;
border-radius: 12px !important;
- font-size: 12px;
+ font-size: var(--ui-font-size-xs);
}
.ui-button[data-variant="primary"] {
@@ -167,6 +213,12 @@ textarea {
border: 1px solid var(--ui-border) !important;
background: var(--ui-input-bg) !important;
outline: none;
+ font-size: var(--ui-control-font-size);
+ line-height: var(--ui-control-line-height);
+ transition:
+ border-color 120ms ease,
+ box-shadow 120ms ease,
+ background 120ms ease;
}
.ui-input,
@@ -175,7 +227,12 @@ textarea {
box-shadow: none;
}
-input,
+input:not([type="checkbox"]):not([type="radio"]),
+select {
+ padding-inline: var(--ui-control-padding-x) !important;
+}
+
+input:not([type="checkbox"]):not([type="radio"]),
select {
height: var(--ui-control-height) !important;
}
@@ -192,10 +249,10 @@ select {
}
textarea {
- padding: 12px 14px !important;
+ padding: 13px 15px !important;
resize: vertical;
min-height: 120px;
- line-height: 1.55;
+ line-height: var(--ui-text-line-height);
}
input:focus,
@@ -263,33 +320,37 @@ a {
border: 1px solid var(--ui-border);
border-radius: var(--ui-radius-lg);
box-shadow: var(--ui-shadow-soft);
+ padding: var(--ui-card-padding);
}
.ui-section {
display: grid;
gap: var(--ui-space-4);
+ min-width: 0;
}
.ui-section-header {
display: grid;
- gap: 4px;
+ gap: 5px;
+ min-width: 0;
}
.ui-section-title {
margin: 0;
- font-size: 18px;
- line-height: 1.35;
+ font-size: var(--ui-font-size-xl);
+ line-height: 1.32;
+ letter-spacing: -0.01em;
}
.ui-section-description {
color: var(--ui-text-muted);
- font-size: 13px;
- line-height: 1.55;
+ font-size: var(--ui-font-size-sm);
+ line-height: var(--ui-text-line-height);
}
.ui-field {
display: grid;
- gap: 6px;
+ gap: 7px;
min-width: 0;
}
@@ -305,14 +366,16 @@ a {
.ui-field-label {
color: var(--ui-text-muted);
- font-size: 12px;
- line-height: 1.45;
+ font-size: var(--ui-font-size-xs);
+ font-weight: 650;
+ letter-spacing: 0.01em;
+ line-height: 1.35;
}
.ui-field-hint {
color: var(--ui-text-muted);
- font-size: 12px;
- line-height: 1.45;
+ font-size: var(--ui-font-size-xs);
+ line-height: 1.5;
}
.ui-action-bar {
@@ -352,11 +415,16 @@ a {
height: var(--ui-control-height) !important;
}
+.ui-action-bar > .ui-button,
+.ui-action-bar > button {
+ align-self: flex-end;
+}
+
.ui-action-bar .ui-button[data-size="sm"] {
min-height: var(--ui-control-height) !important;
height: var(--ui-control-height) !important;
padding: 0 14px !important;
- font-size: 13px;
+ font-size: var(--ui-font-size-sm);
}
.ui-popover {
@@ -387,11 +455,13 @@ a {
.ui-stack {
display: grid;
gap: var(--ui-space-4);
+ min-width: 0;
}
.ui-grid {
display: grid;
gap: var(--ui-space-3);
+ min-width: 0;
}
.ui-inline {
@@ -423,6 +493,7 @@ a {
color: var(--ui-text);
box-shadow: var(--ui-shadow-soft);
white-space: nowrap;
+ line-height: 1;
}
.ui-badge-dot {
@@ -470,10 +541,11 @@ a {
.ui-table th,
.ui-table td {
- padding: 12px 12px;
+ padding: 13px 14px;
text-align: left;
border-bottom: 1px solid var(--ui-border);
vertical-align: top;
+ line-height: 1.52;
}
.ui-table thead th {
@@ -481,11 +553,16 @@ a {
top: 0;
background: var(--ui-bg-elevated);
z-index: 1;
+ color: var(--ui-text-muted);
+ font-size: var(--ui-font-size-xs);
+ font-weight: 700;
+ letter-spacing: 0.02em;
+ white-space: nowrap;
}
.ui-table--compact th,
.ui-table--compact td {
- padding: 10px 10px;
+ padding: 10px 12px;
}
.ui-dialog-overlay {
@@ -500,7 +577,7 @@ a {
.ui-dialog {
width: min(520px, 100%);
- padding: 22px;
+ padding: 24px;
border-radius: 22px;
background: var(--ui-bg-strong);
border: 1px solid var(--ui-border);
@@ -515,7 +592,10 @@ a {
}
.ui-layout-chat {
+ --ui-chat-bottom-height: 89px;
display: flex;
+ height: 100%;
+ max-height: 100%;
min-height: 100%;
min-width: 0;
overflow: hidden;
@@ -555,12 +635,19 @@ a {
}
.ui-chat-conversation-item {
- padding: 10px 12px;
+ padding: 11px 12px;
border-radius: var(--ui-radius-sm);
margin-bottom: 4px;
display: flex;
gap: 8px;
align-items: flex-start;
+ transition:
+ background 120ms ease,
+ transform 120ms ease;
+}
+
+.ui-chat-conversation-item:hover {
+ background: color-mix(in srgb, var(--ui-primary) 8%, transparent);
}
.ui-chat-conversation-active {
@@ -568,26 +655,45 @@ a {
}
.ui-chat-conversation-name {
- font-size: 14px;
+ font-size: var(--ui-font-size-md);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ui-chat-conversation-meta {
- font-size: 12px;
+ font-size: var(--ui-font-size-xs);
color: var(--ui-text-muted);
margin-top: 2px;
}
.ui-chat-footer {
- padding: 12px 16px calc(12px + env(safe-area-inset-bottom, 0px));
+ flex: 0 0 var(--ui-chat-bottom-height);
+ height: var(--ui-chat-bottom-height);
+ min-height: var(--ui-chat-bottom-height);
+ padding: 16px 16px calc(16px + env(safe-area-inset-bottom, 0px));
border-top: 1px solid var(--ui-border);
- font-size: 12px;
+ font-size: var(--ui-font-size-xs);
color: var(--ui-text-muted);
display: flex;
justify-content: space-between;
align-items: center;
+ gap: 12px;
+ background:
+ linear-gradient(180deg, color-mix(in srgb, var(--ui-bg-strong) 72%, transparent), transparent 140%),
+ var(--ui-bg);
+ box-shadow: inset 0 1px 0 color-mix(in srgb, white 34%, transparent);
+}
+
+html[data-theme="dark"] .ui-chat-footer {
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04);
+}
+
+.ui-chat-footer > span {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
.ui-chat-main {
@@ -613,7 +719,7 @@ a {
.ui-chat-settings {
padding: 12px 24px;
border-bottom: 1px solid var(--ui-border);
- font-size: 13px;
+ font-size: var(--ui-font-size-sm);
background: var(--ui-bg);
align-items: flex-end;
}
@@ -642,12 +748,13 @@ a {
.ui-chat-message-bubble {
max-width: 75%;
- padding: 12px 16px;
- border-radius: 12px;
- font-size: 14px;
- line-height: 1.6;
+ padding: 14px 17px;
+ border-radius: 16px;
+ font-size: var(--ui-font-size-md);
+ line-height: var(--ui-text-line-height);
white-space: pre-wrap;
overflow-wrap: break-word;
+ box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
}
.ui-chat-message-bubble--user {
@@ -658,6 +765,7 @@ a {
.ui-chat-message-bubble--assistant {
background: color-mix(in srgb, var(--ui-bg-strong) 72%, var(--ui-bg-elevated));
color: var(--ui-text);
+ border: 1px solid var(--ui-border);
}
.ui-chat-message-caret {
@@ -671,9 +779,19 @@ a {
}
.ui-chat-input-panel {
+ flex: 0 0 var(--ui-chat-bottom-height);
+ height: var(--ui-chat-bottom-height);
+ min-height: var(--ui-chat-bottom-height);
padding: 16px 24px calc(16px + env(safe-area-inset-bottom, 0px));
border-top: 1px solid var(--ui-border);
- background: var(--ui-bg);
+ background:
+ linear-gradient(180deg, color-mix(in srgb, var(--ui-bg-strong) 72%, transparent), transparent 140%),
+ var(--ui-bg);
+ box-shadow: inset 0 1px 0 color-mix(in srgb, white 34%, transparent);
+}
+
+html[data-theme="dark"] .ui-chat-input-panel {
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04);
}
.ui-chat-input-panel .ui-inline {
@@ -683,6 +801,8 @@ a {
.ui-chat-input-panel .ui-textarea {
min-height: 56px;
max-height: 180px;
+ padding-top: 12px !important;
+ padding-bottom: 12px !important;
}
.ui-chat-input-panel .ui-button {
@@ -693,7 +813,12 @@ a {
.ui-chat-test-panel {
flex: 1;
+ min-height: 0;
+ max-height: 100%;
overflow: auto;
+ -webkit-overflow-scrolling: touch;
+ overscroll-behavior: contain;
+ align-content: start;
padding: 24px;
}
@@ -705,13 +830,13 @@ a {
.ui-chat-empty {
height: 100%;
color: #cbd5e1;
- font-size: 16px;
+ font-size: var(--ui-font-size-lg);
display: grid;
place-items: center;
}
.ui-chat-empty-icon {
- font-size: 48px;
+ font-size: clamp(40px, 6vw, 48px);
margin-bottom: 16px;
opacity: 0.3;
}
@@ -781,7 +906,10 @@ a {
.ui-chat-settings,
.ui-chat-messages,
.ui-chat-test-panel,
+ .ui-chat-footer,
.ui-chat-input-panel {
+ flex-basis: auto;
+ height: auto;
padding-left: 14px;
padding-right: 14px;
}
diff --git a/oneapi-gateway/src/admin-auth.ts b/oneapi-gateway/src/admin-auth.ts
deleted file mode 100644
index 655dd76..0000000
--- a/oneapi-gateway/src/admin-auth.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { createHmac, timingSafeEqual } from "node:crypto";
-import type { Config } from "./config.js";
-import { ipAllowed } from "./net.js";
-
-export const ADMIN_SESSION_COOKIE = "easyai_admin_session";
-const SESSION_TTL_SECONDS = 8 * 60 * 60;
-
-export function basicAuthOk(authHeader: string | undefined, user: string, pass: string): boolean {
- if (!authHeader) return false;
- const m = authHeader.match(/^Basic\s+(.+)$/i);
- if (!m) return false;
- const decoded = Buffer.from(m[1]!, "base64").toString("utf8");
- const idx = decoded.indexOf(":");
- if (idx < 0) return false;
- const u = decoded.slice(0, idx);
- const p = decoded.slice(idx + 1);
- return u === user && p === pass;
-}
-
-function sessionSecret(cfg: Config): string {
- return `${cfg.adminUser}:${cfg.adminPass}:${cfg.internalToken ?? ""}:${cfg.databaseUrl}`;
-}
-
-function sign(value: string, cfg: Config): string {
- return createHmac("sha256", sessionSecret(cfg)).update(value).digest("base64url");
-}
-
-function safeEqual(a: string, b: string): boolean {
- const ab = Buffer.from(a);
- const bb = Buffer.from(b);
- if (ab.length !== bb.length) return false;
- return timingSafeEqual(ab, bb);
-}
-
-function parseCookies(cookieHeader: string | undefined): Record
{
- if (!cookieHeader) return {};
- const out: Record = {};
- for (const part of cookieHeader.split(";")) {
- const idx = part.indexOf("=");
- if (idx < 0) continue;
- const k = part.slice(0, idx).trim();
- const v = part.slice(idx + 1).trim();
- if (k) out[k] = decodeURIComponent(v);
- }
- return out;
-}
-
-export function createAdminSessionCookie(cfg: Config): string {
- const payload = Buffer.from(JSON.stringify({
- u: cfg.adminUser,
- exp: Math.floor(Date.now() / 1000) + SESSION_TTL_SECONDS,
- }), "utf8").toString("base64url");
- const token = `${payload}.${sign(payload, cfg)}`;
- const attrs = [
- `${ADMIN_SESSION_COOKIE}=${encodeURIComponent(token)}`,
- "HttpOnly",
- "SameSite=Lax",
- "Path=/",
- `Max-Age=${SESSION_TTL_SECONDS}`,
- ];
- if (cfg.tls) attrs.push("Secure");
- return attrs.join("; ");
-}
-
-export function clearAdminSessionCookie(): string {
- return `${ADMIN_SESSION_COOKIE}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0`;
-}
-
-export function adminSessionOk(cookieHeader: string | undefined, cfg: Config): boolean {
- const token = parseCookies(cookieHeader)[ADMIN_SESSION_COOKIE];
- if (!token) return false;
- const [payload, sig] = token.split(".");
- if (!payload || !sig || !safeEqual(sig, sign(payload, cfg))) return false;
- try {
- const raw = Buffer.from(payload, "base64url").toString("utf8");
- const data = JSON.parse(raw);
- return data?.u === cfg.adminUser && typeof data?.exp === "number" && data.exp > Math.floor(Date.now() / 1000);
- } catch {
- return false;
- }
-}
-
-export function isAdminRequest(req: any, cfg: Config): boolean {
- return ipAllowed(req.ip, cfg.adminAllowedCidrs)
- && (adminSessionOk(req.headers.cookie, cfg) || basicAuthOk(req.headers.authorization, cfg.adminUser, cfg.adminPass));
-}
diff --git a/oneapi-gateway/src/admin.ts b/oneapi-gateway/src/admin.ts
deleted file mode 100644
index a6ae71d..0000000
--- a/oneapi-gateway/src/admin.ts
+++ /dev/null
@@ -1,308 +0,0 @@
-import type { FastifyInstance } from "fastify";
-import { randomBytes } from "node:crypto";
-import { sha256Hex } from "./crypto.js";
-import type { Config } from "./config.js";
-import type { Db } from "./db.js";
-import {
- findTenant,
- deleteApiKey,
- deleteTenant,
- getApiKeyUsage,
- insertApiKey,
- listApiKeys,
- listTenants,
- revokeApiKey,
- scheduleApiKeyRevocation,
- unbindTenantKeys,
- updateApiKeyAutoRevoke,
- updateApiKeyMetadata,
- updateApiKeyRpm,
- updateApiKeyTenant,
- upsertTenant,
-} from "./db.js";
-import type { RedisClient } from "./redis.js";
-import { isAdminRequest } from "./admin-auth.js";
-
-function requireAdmin(req: any, cfg: Config): boolean {
- return isAdminRequest(req, cfg);
-}
-
-function requireAdminAction(req: any): boolean {
- const h = req.headers["x-oneapi-admin-action"];
- const v = Array.isArray(h) ? h[0] : h;
- return String(v ?? "") === "1";
-}
-
-function requireAdminWrite(req: any, cfg: Config): boolean {
- return requireAdmin(req, cfg) && requireAdminAction(req);
-}
-
-function apiKeyPrefix(rawKey: string): string {
- return rawKey.slice(0, 8);
-}
-
-function apiKeySuffix(rawKey: string): string {
- return rawKey.slice(-6);
-}
-
-function generateApiKey(): string {
- const b = randomBytes(24).toString("base64url");
- return `sk-${b}`;
-}
-
-function runtimeKeyEnvironment(cfg: Config): "development" | "production" {
- return cfg.appEnv === "production" ? "production" : "development";
-}
-
-function parseStringList(value: unknown): string[] | null {
- if (value === null || value === undefined || value === "") return null;
- if (Array.isArray(value)) return value.map((v) => String(v).trim()).filter(Boolean);
- return String(value)
- .split(",")
- .map((v) => v.trim())
- .filter(Boolean);
-}
-
-function parseNullableDate(value: unknown): string | null {
- if (value === null || value === undefined || value === "") return null;
- const d = new Date(String(value));
- if (Number.isNaN(d.getTime())) throw new Error("invalid date");
- return d.toISOString();
-}
-
-function keyStatus(k: { revoked_at: string | null; expires_at?: string | null; revocation_scheduled_at?: string | null }): string {
- if (k.revoked_at) return "revoked";
- if (k.expires_at && new Date(k.expires_at).getTime() <= Date.now()) return "expired";
- if (k.revocation_scheduled_at) return "revoking";
- return "active";
-}
-
-export async function registerAdminApi(app: FastifyInstance, cfg: Config, db: Db, redis: RedisClient): Promise {
- app.get("/admin/api/keys", async (req, reply) => {
- if (!requireAdmin(req, cfg)) {
- reply.header("WWW-Authenticate", 'Basic realm="oneapi-dashboard"');
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
- const keys = await listApiKeys(db);
- return {
- keys: keys.map((k) => ({
- id: k.id,
- name: k.name,
- key_prefix: k.key_prefix,
- key_suffix: k.key_suffix,
- masked_key: `${k.key_prefix}...${k.key_suffix ?? ""}`,
- environment: k.environment,
- scopes: k.scopes,
- created_at: k.created_at,
- revoked_at: k.revoked_at,
- expires_at: k.expires_at,
- last_used_at: k.last_used_at,
- last_used_ip: k.last_used_ip,
- revocation_scheduled_at: k.revocation_scheduled_at,
- auto_revoke_after_unused_days: k.auto_revoke_after_unused_days,
- ip_allow_cidrs: k.ip_allow_cidrs,
- status: keyStatus(k),
- rpm_limit: k.rpm_limit,
- tenant_id: k.tenant_id,
- })),
- };
- });
-
- app.post("/admin/api/keys", async (req, reply) => {
- if (!requireAdminWrite(req, cfg)) {
- reply.header("WWW-Authenticate", 'Basic realm="oneapi-dashboard"');
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
- const body = (req.body ?? {}) as any;
- let expiresAt: string | null;
- try {
- expiresAt = parseNullableDate(body.expires_at);
- } catch {
- return reply.status(400).send({ error: { message: "invalid expires_at", type: "invalid_request_error" } });
- }
- const raw = generateApiKey();
- const hash = sha256Hex(raw);
- const prefix = apiKeyPrefix(raw);
- const suffix = apiKeySuffix(raw);
- const out = await insertApiKey(db, {
- keyHash: hash,
- keyPrefix: prefix,
- keySuffix: suffix,
- name: typeof body.name === "string" && body.name.trim() ? body.name.trim() : null,
- environment: runtimeKeyEnvironment(cfg),
- scopes: parseStringList(body.scopes),
- expiresAt,
- ipAllowCidrs: null,
- });
- return { id: out.id, api_key: raw, key_prefix: prefix, key_suffix: suffix, masked_key: `${prefix}...${suffix}` };
- });
-
- app.post("/admin/api/keys/:id/revoke", async (req, reply) => {
- if (!requireAdminWrite(req, cfg)) {
- reply.header("WWW-Authenticate", 'Basic realm="oneapi-dashboard"');
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
- const id = Number((req.params as any).id);
- if (!Number.isFinite(id) || id <= 0) return reply.status(400).send({ error: { message: "invalid id", type: "invalid_request_error" } });
- const body = (req.body ?? {}) as any;
- if (body.mode === "scheduled") {
- const hours = Number(body.delay_hours);
- if (!Number.isFinite(hours) || hours <= 0) return reply.status(400).send({ error: { message: "invalid delay_hours", type: "invalid_request_error" } });
- await scheduleApiKeyRevocation(db, id, new Date(Date.now() + hours * 60 * 60 * 1000).toISOString());
- } else if (body.mode === "unused") {
- const days = Number(body.unused_days);
- if (!Number.isFinite(days) || days <= 0) return reply.status(400).send({ error: { message: "invalid unused_days", type: "invalid_request_error" } });
- await updateApiKeyAutoRevoke(db, id, Math.floor(days));
- } else {
- await revokeApiKey(db, id);
- }
- return { ok: true };
- });
-
- app.patch("/admin/api/keys/:id", async (req, reply) => {
- if (!requireAdminWrite(req, cfg)) {
- reply.header("WWW-Authenticate", 'Basic realm="oneapi-dashboard"');
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
- const id = Number((req.params as any).id);
- if (!Number.isFinite(id) || id <= 0) return reply.status(400).send({ error: { message: "invalid id", type: "invalid_request_error" } });
- const body = (req.body ?? {}) as any;
- let expiresAt: string | null;
- try {
- expiresAt = parseNullableDate(body.expires_at);
- } catch {
- return reply.status(400).send({ error: { message: "invalid expires_at", type: "invalid_request_error" } });
- }
- await updateApiKeyMetadata(db, id, {
- name: typeof body.name === "string" && body.name.trim() ? body.name.trim() : null,
- environment: runtimeKeyEnvironment(cfg),
- scopes: parseStringList(body.scopes),
- expiresAt,
- ipAllowCidrs: null,
- });
- return { ok: true };
- });
-
- app.get("/admin/api/keys/:id/usage", async (req, reply) => {
- if (!requireAdmin(req, cfg)) {
- reply.header("WWW-Authenticate", 'Basic realm="oneapi-dashboard"');
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
- const id = Number((req.params as any).id);
- if (!Number.isFinite(id) || id <= 0) return reply.status(400).send({ error: { message: "invalid id", type: "invalid_request_error" } });
- const q = req.query as any;
- const sinceMinutes = Math.min(Math.max(Number(q.sinceMinutes ?? 1440), 1), 60 * 24 * 30);
- const rows = await getApiKeyUsage(db, id, sinceMinutes);
- return { rows };
- });
-
- app.delete("/admin/api/keys/:id", async (req, reply) => {
- if (!requireAdminWrite(req, cfg)) {
- reply.header("WWW-Authenticate", 'Basic realm="oneapi-dashboard"');
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
- const id = Number((req.params as any).id);
- if (!Number.isFinite(id) || id <= 0) return reply.status(400).send({ error: { message: "invalid id", type: "invalid_request_error" } });
- const body = (req.body ?? {}) as any;
- const force = Boolean(body.force);
- const r = await deleteApiKey(db, id, force);
- if (r === "deleted") return { ok: true };
- if (r === "not_found") return reply.status(404).send({ error: { message: "not found", type: "not_found" } });
- return reply.status(409).send({ error: { message: "key must be revoked before delete", type: "invalid_request_error" } });
- });
-
- app.put("/admin/api/keys/:id/rpm", async (req, reply) => {
- if (!requireAdminWrite(req, cfg)) {
- reply.header("WWW-Authenticate", 'Basic realm="oneapi-dashboard"');
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
- const id = Number((req.params as any).id);
- if (!Number.isFinite(id) || id <= 0) return reply.status(400).send({ error: { message: "invalid id", type: "invalid_request_error" } });
- const body = (req.body ?? {}) as any;
- const rpm = body.rpm_limit === null || body.rpm_limit === undefined ? null : Number(body.rpm_limit);
- if (rpm !== null && (!Number.isFinite(rpm) || rpm <= 0)) return reply.status(400).send({ error: { message: "invalid rpm_limit", type: "invalid_request_error" } });
- await updateApiKeyRpm(db, id, rpm);
- return { ok: true };
- });
-
- app.put("/admin/api/keys/:id/tenant", async (req, reply) => {
- if (!requireAdminWrite(req, cfg)) {
- reply.header("WWW-Authenticate", 'Basic realm="oneapi-dashboard"');
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
- const id = Number((req.params as any).id);
- if (!Number.isFinite(id) || id <= 0) return reply.status(400).send({ error: { message: "invalid id", type: "invalid_request_error" } });
- const body = (req.body ?? {}) as any;
- const tenantIdRaw = body.tenant_id === null || body.tenant_id === undefined ? null : String(body.tenant_id).trim();
- const tenantId = tenantIdRaw ? tenantIdRaw : null;
- if (tenantId) {
- const t = await findTenant(db, tenantId);
- if (!t) return reply.status(400).send({ error: { message: "tenant not found", type: "not_found" } });
- }
- await updateApiKeyTenant(db, id, tenantId);
- return { ok: true };
- });
-
- app.get("/admin/api/tenants", async (req, reply) => {
- if (!requireAdmin(req, cfg)) {
- reply.header("WWW-Authenticate", 'Basic realm="oneapi-dashboard"');
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
- const tenants = await listTenants(db);
- return { tenants };
- });
-
- app.put("/admin/api/tenants/:tenantId", async (req, reply) => {
- if (!requireAdminWrite(req, cfg)) {
- reply.header("WWW-Authenticate", 'Basic realm="oneapi-dashboard"');
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
- const tenantId = String((req.params as any).tenantId ?? "").trim();
- if (!tenantId) return reply.status(400).send({ error: { message: "invalid tenantId", type: "invalid_request_error" } });
- const body = (req.body ?? {}) as any;
- const rpm = body.rpm_limit === null || body.rpm_limit === undefined ? null : Number(body.rpm_limit);
- const tpm = body.tpm_limit === null || body.tpm_limit === undefined ? null : Number(body.tpm_limit);
- const disabled = Boolean(body.disabled);
- if (rpm !== null && (!Number.isFinite(rpm) || rpm <= 0)) return reply.status(400).send({ error: { message: "invalid rpm_limit", type: "invalid_request_error" } });
- if (tpm !== null && (!Number.isFinite(tpm) || tpm <= 0)) return reply.status(400).send({ error: { message: "invalid tpm_limit", type: "invalid_request_error" } });
- await upsertTenant(db, tenantId, rpm, tpm, disabled);
- await redis.set(
- `tenantcfg:v1:${tenantId}`,
- JSON.stringify({ rpm_limit: rpm, tpm_limit: tpm, disabled }),
- { EX: 300 },
- );
- return { ok: true };
- });
-
- app.delete("/admin/api/tenants/:tenantId", async (req, reply) => {
- if (!requireAdminWrite(req, cfg)) {
- reply.header("WWW-Authenticate", 'Basic realm="oneapi-dashboard"');
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
- const tenantId = String((req.params as any).tenantId ?? "").trim();
- if (!tenantId) return reply.status(400).send({ error: { message: "invalid tenantId", type: "invalid_request_error" } });
- const body = (req.body ?? {}) as any;
- const force = Boolean(body.force);
- const r = await deleteTenant(db, tenantId, force);
- if (r === "deleted") {
- await redis.del(`tenantcfg:v1:${tenantId}`);
- return { ok: true };
- }
- if (r === "not_found") return reply.status(404).send({ error: { message: "not found", type: "not_found" } });
- return reply.status(409).send({ error: { message: "tenant still has keys bound", type: "invalid_request_error" } });
- });
-
- app.post("/admin/api/tenants/:tenantId/unbind_keys", async (req, reply) => {
- if (!requireAdminWrite(req, cfg)) {
- reply.header("WWW-Authenticate", 'Basic realm="oneapi-dashboard"');
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
- const tenantId = String((req.params as any).tenantId ?? "").trim();
- if (!tenantId) return reply.status(400).send({ error: { message: "invalid tenantId", type: "invalid_request_error" } });
- const t = await findTenant(db, tenantId);
- if (!t) return reply.status(404).send({ error: { message: "not found", type: "not_found" } });
- const n = await unbindTenantKeys(db, tenantId);
- await redis.del(`tenantcfg:v1:${tenantId}`);
- return { ok: true, unbound: n };
- });
-}
diff --git a/oneapi-gateway/src/auth.ts b/oneapi-gateway/src/auth.ts
index 93ef143..a5e5fcd 100644
--- a/oneapi-gateway/src/auth.ts
+++ b/oneapi-gateway/src/auth.ts
@@ -1,176 +1,53 @@
-import { createRemoteJWKSet, jwtVerify } from "jose";
import { sha256Hex } from "./crypto.js";
import type { Config } from "./config.js";
-import type { Db } from "./db.js";
-import { findActiveApiKeyByHash, findTenant, markApiKeyUsed } from "./db.js";
-import type { RedisClient } from "./redis.js";
-import { ipAllowed, normalizeIp } from "./net.js";
export type AuthContext = {
+ /** Stable identity used to scope conversations and batches. */
principal: string;
- authMode: "apikey" | "oauth";
- apiKeyHash?: string;
- apiKeyId?: number;
- rpmLimit?: number | null;
- scopes?: string[] | null;
- environment?: string;
- tenantId?: string | null;
- tenantRpmLimit?: number | null;
- tenantTpmLimit?: number | null;
- tenantDisabled?: boolean;
+ /**
+ * true -> the gateway authenticates the key itself and talks to LiteLLM with the master key
+ * false -> the client presented a LiteLLM virtual key; forward it and let LiteLLM validate
+ */
+ useMasterKey: boolean;
+ token?: string;
};
-function bearerTokenFromHeaders(headers: Record): string | undefined {
- const h = headers["authorization"];
- const v = Array.isArray(h) ? h[0] : h;
- if (!v) return;
- const m = v.match(/^Bearer\s+(.+)$/i);
- return m?.[1]?.trim();
+function headerValue(headers: Record, name: string): string | undefined {
+ const raw = headers[name];
+ const value = Array.isArray(raw) ? raw[0] : raw;
+ return value && value.trim() ? value.trim() : undefined;
}
-function apiKeyFromHeaders(headers: Record): string | undefined {
- const headerKey = headers["x-api-key"];
- const hk = Array.isArray(headerKey) ? headerKey[0] : headerKey;
- if (hk && hk.trim().length) return hk.trim();
- return bearerTokenFromHeaders(headers);
+export function apiKeyFromHeaders(headers: Record): string | undefined {
+ const direct = headerValue(headers, "x-api-key");
+ if (direct) return direct;
+ const auth = headerValue(headers, "authorization");
+ if (!auth) return;
+ const match = auth.match(/^Bearer\s+(.+)$/i);
+ return match?.[1]?.trim();
}
-export type OAuthVerifier = {
- verify: (token: string) => Promise<{ subject: string }>;
-};
-
-export function hasScope(auth: AuthContext, required: string): boolean {
- if (!auth.scopes || auth.scopes.length === 0) return true;
- return auth.scopes.includes(required) || auth.scopes.includes("*");
-}
-
-export function createOAuthVerifier(cfg: Config): OAuthVerifier | undefined {
- if (!cfg.authModes.has("oauth")) return;
- if (!cfg.oauth.jwksUrl) return;
-
- const jwks = createRemoteJWKSet(new URL(cfg.oauth.jwksUrl));
- return {
- verify: async (token: string) => {
- const out = await jwtVerify(token, jwks, {
- issuer: cfg.oauth.issuer,
- audience: cfg.oauth.audience,
- });
- const sub = out.payload.sub;
- if (!sub || typeof sub !== "string") throw new Error("missing sub");
- return { subject: sub };
- },
- };
-}
-
-export async function authenticate(
- cfg: Config,
- oauth: OAuthVerifier | undefined,
- headers: Record,
- db?: Db,
- redis?: RedisClient,
- reqIp?: string,
-): Promise {
- const internalHeader = headers["x-oneapi-internal-token"];
- const internalToken = Array.isArray(internalHeader) ? internalHeader[0] : internalHeader;
- if (cfg.internalToken && internalToken && internalToken === cfg.internalToken) {
- if (!ipAllowed(reqIp, cfg.internalTokenAllowCidrs)) throw new Error("unauthorized");
- const pHeader = headers["x-oneapi-principal"];
- const principal = (Array.isArray(pHeader) ? pHeader[0] : pHeader)?.trim();
- if (!principal) throw new Error("missing principal");
- const tenantHeader = headers["x-oneapi-tenant-id"];
- const tenantId = (Array.isArray(tenantHeader) ? tenantHeader[0] : tenantHeader)?.trim();
- let tenantRpmLimit: number | null | undefined;
- let tenantTpmLimit: number | null | undefined;
- let tenantDisabled: boolean | undefined;
- if (tenantId && db) {
- if (redis) {
- const cached = await redis.get(`tenantcfg:v1:${tenantId}`);
- if (cached) {
- try {
- const j = JSON.parse(cached);
- tenantRpmLimit = typeof j.rpm_limit === "number" ? j.rpm_limit : null;
- tenantTpmLimit = typeof j.tpm_limit === "number" ? j.tpm_limit : null;
- tenantDisabled = Boolean(j.disabled);
- } catch {}
- }
- }
- if (tenantRpmLimit === undefined && tenantTpmLimit === undefined && tenantDisabled === undefined) {
- const t = await findTenant(db, tenantId);
- if (t) {
- tenantRpmLimit = t.rpm_limit ?? null;
- tenantTpmLimit = t.tpm_limit ?? null;
- tenantDisabled = Boolean(t.disabled);
- }
- }
- }
- return { principal, authMode: "apikey", tenantId: tenantId || null, tenantRpmLimit, tenantTpmLimit, tenantDisabled };
- }
-
- const tokenOrKey = apiKeyFromHeaders(headers);
- if (!tokenOrKey) throw new Error("missing credentials");
-
- if (cfg.authModes.has("apikey") && cfg.apiKeys.size > 0 && cfg.apiKeys.has(tokenOrKey)) {
- const apiKeyHash = sha256Hex(tokenOrKey);
- return { principal: `apikey:${apiKeyHash.slice(0, 12)}`, authMode: "apikey", apiKeyHash };
+/**
+ * Single auth entrypoint.
+ *
+ * - internal token: used by the batch worker (trusted, no client key involved)
+ * - `secrets.api_keys`: simple keys for individuals / small teams, defined in YAML
+ * - anything else: treated as a LiteLLM virtual key and forwarded untouched, so the
+ * LiteLLM console owns key lifecycle, budgets and rate limits
+ */
+export function authenticate(cfg: Config, headers: Record): AuthContext {
+ const internal = headerValue(headers, "x-oneapi-internal-token");
+ if (cfg.internalToken && internal && internal === cfg.internalToken) {
+ const principal = headerValue(headers, "x-oneapi-principal") ?? "internal";
+ return { principal, useMasterKey: true };
}
- if (cfg.authModes.has("apikey") && db) {
- const apiKeyHash = sha256Hex(tokenOrKey);
- const row = await findActiveApiKeyByHash(db, apiKeyHash);
- if (row) {
- if (!ipAllowed(reqIp, row.ip_allow_cidrs)) throw new Error("unauthorized");
- let tenantRpmLimit: number | null | undefined;
- let tenantTpmLimit: number | null | undefined;
- let tenantDisabled: boolean | undefined;
- if (row.tenant_id) {
- if (redis) {
- const cached = await redis.get(`tenantcfg:v1:${row.tenant_id}`);
- if (cached) {
- try {
- const j = JSON.parse(cached);
- tenantRpmLimit = typeof j.rpm_limit === "number" ? j.rpm_limit : null;
- tenantTpmLimit = typeof j.tpm_limit === "number" ? j.tpm_limit : null;
- tenantDisabled = Boolean(j.disabled);
- } catch {}
- }
- }
- if (tenantRpmLimit === undefined && tenantTpmLimit === undefined && tenantDisabled === undefined) {
- const t = await findTenant(db, row.tenant_id);
- if (t) {
- tenantRpmLimit = t.rpm_limit ?? null;
- tenantTpmLimit = t.tpm_limit ?? null;
- tenantDisabled = Boolean(t.disabled);
- if (redis) {
- await redis.set(
- `tenantcfg:v1:${row.tenant_id}`,
- JSON.stringify({ rpm_limit: tenantRpmLimit, tpm_limit: tenantTpmLimit, disabled: tenantDisabled }),
- { EX: 300 },
- );
- }
- }
- }
- }
- await markApiKeyUsed(db, row.id, normalizeIp(reqIp));
- return {
- principal: `apikey:${apiKeyHash.slice(0, 12)}`,
- authMode: "apikey",
- apiKeyHash,
- apiKeyId: row.id,
- rpmLimit: row.rpm_limit,
- scopes: row.scopes,
- environment: row.environment,
- tenantId: row.tenant_id,
- tenantRpmLimit,
- tenantTpmLimit,
- tenantDisabled,
- };
- }
- }
+ const token = apiKeyFromHeaders(headers);
+ if (!token) throw new Error("missing credentials");
- if (cfg.authModes.has("oauth") && oauth) {
- const out = await oauth.verify(tokenOrKey);
- return { principal: `oauth:${out.subject}`, authMode: "oauth" };
+ const hash = sha256Hex(token);
+ if (cfg.apiKeys.has(token)) {
+ return { principal: `key:${hash.slice(0, 12)}`, useMasterKey: true, token };
}
-
- throw new Error("invalid credentials");
+ return { principal: `litellm:${hash.slice(0, 12)}`, useMasterKey: false, token };
}
diff --git a/oneapi-gateway/src/batch.ts b/oneapi-gateway/src/batch.ts
index 1c1d40e..736fee9 100644
--- a/oneapi-gateway/src/batch.ts
+++ b/oneapi-gateway/src/batch.ts
@@ -4,7 +4,7 @@ import type { Config } from "./config.js";
import type { Db } from "./db.js";
import { createBatch, getBatch, insertBatchItem, listBatchItems } from "./db.js";
import type { RedisClient } from "./redis.js";
-import { hasScope, type AuthContext } from "./auth.js";
+import { authenticate, type AuthContext } from "./auth.js";
type BatchRequestItem = {
endpoint?: string;
@@ -22,7 +22,6 @@ export async function registerBatchRoutes(
cfg: Config,
db: Db,
redis: RedisClient,
- authenticateRequest: (headers: Record) => Promise,
): Promise {
app.post("/v1/batches", async (req, reply) => {
if (!cfg.internalToken) {
@@ -30,11 +29,10 @@ export async function registerBatchRoutes(
}
let auth: AuthContext;
try {
- auth = await authenticateRequest(req.headers as any);
+ auth = authenticate(cfg, req.headers as any);
} catch {
return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
}
- if (!hasScope(auth, "batch:write")) return reply.status(403).send({ error: { message: "insufficient scope", type: "auth_error" } });
const body = (req.body ?? {}) as any;
const items = (body.requests ?? body.items) as BatchRequestItem[] | undefined;
@@ -43,7 +41,7 @@ export async function registerBatchRoutes(
}
const batchId = randomUUID();
- await createBatch(db, batchId, auth.principal, auth.tenantId ?? null, items.length);
+ await createBatch(db, batchId, auth.principal, items.length);
for (let i = 0; i < items.length; i++) {
const it = items[i] as any;
@@ -63,11 +61,10 @@ export async function registerBatchRoutes(
app.get("/v1/batches/:batchId", async (req, reply) => {
let auth: AuthContext;
try {
- auth = await authenticateRequest(req.headers as any);
+ auth = authenticate(cfg, req.headers as any);
} catch {
return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
}
- if (!hasScope(auth, "batch:read")) return reply.status(403).send({ error: { message: "insufficient scope", type: "auth_error" } });
const batchId = String((req.params as any).batchId ?? "").trim();
const row = await getBatch(db, batchId);
@@ -79,11 +76,10 @@ export async function registerBatchRoutes(
app.get("/v1/batches/:batchId/output", async (req, reply) => {
let auth: AuthContext;
try {
- auth = await authenticateRequest(req.headers as any);
+ auth = authenticate(cfg, req.headers as any);
} catch {
return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
}
- if (!hasScope(auth, "batch:read")) return reply.status(403).send({ error: { message: "insufficient scope", type: "auth_error" } });
const batchId = String((req.params as any).batchId ?? "").trim();
const row = await getBatch(db, batchId);
diff --git a/oneapi-gateway/src/cache.ts b/oneapi-gateway/src/cache.ts
deleted file mode 100644
index f45d775..0000000
--- a/oneapi-gateway/src/cache.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import type { RedisClient } from "./redis.js";
-import { sha256Hex } from "./crypto.js";
-
-export type CacheDecision = { shouldCache: false } | { shouldCache: true; cacheKey: string };
-
-export function decideCache(path: string, body: unknown): CacheDecision {
- if (path !== "/v1/chat/completions" && path !== "/v1/embeddings") return { shouldCache: false };
- if (!body || typeof body !== "object") return { shouldCache: false };
- const b = body as Record;
- const temperature = b["temperature"];
- if (typeof temperature === "number" && temperature > 0) return { shouldCache: false };
- const model = b["model"];
- if (typeof model !== "string" || !model.length) return { shouldCache: false };
- const stream = b["stream"] === true;
-
- const keyPayload =
- path === "/v1/embeddings"
- ? { path, model, input: b["input"], encoding_format: b["encoding_format"] }
- : {
- path,
- model,
- messages: b["messages"],
- temperature: b["temperature"] ?? 0,
- top_p: b["top_p"],
- max_tokens: b["max_tokens"],
- response_format: b["response_format"],
- seed: b["seed"],
- stream,
- };
-
- const cacheKey = `cache:v1:${sha256Hex(JSON.stringify(keyPayload))}`;
- return { shouldCache: true, cacheKey };
-}
-
-export async function cacheGet(redis: RedisClient, key: string): Promise {
- const v = await redis.get(key);
- return v ?? undefined;
-}
-
-export async function cacheSet(redis: RedisClient, key: string, value: string, ttlSeconds: number): Promise {
- await redis.set(key, value, { EX: ttlSeconds });
-}
diff --git a/oneapi-gateway/src/chat.ts b/oneapi-gateway/src/chat.ts
index e364d6e..d4532f3 100644
--- a/oneapi-gateway/src/chat.ts
+++ b/oneapi-gateway/src/chat.ts
@@ -4,13 +4,7 @@ import { Readable } from "node:stream";
import type { Config } from "./config.js";
import type { Db, ConversationRow } from "./db.js";
import { createConversation, listConversations, getConversation, updateConversationTitle, touchConversation, deleteConversation, insertMessage, listMessages } from "./db.js";
-import type { RedisClient } from "./redis.js";
-import type { AuthContext, OAuthVerifier } from "./auth.js";
-import { authenticate, hasScope } from "./auth.js";
-
-async function authenticateRequest(cfg: Config, oauth: OAuthVerifier | undefined, headers: Record, db: Db, redis: RedisClient, reqIp?: string): Promise {
- return authenticate(cfg, oauth, headers, db, redis, reqIp);
-}
+import { authenticate, type AuthContext } from "./auth.js";
function authHeaderFromRequest(req: any): string {
const h = req.headers["authorization"] ?? req.headers["x-api-key"];
@@ -53,18 +47,12 @@ function extractAssistantContent(sseText: string): { content: string; promptToke
return { content, promptTokens, completionTokens };
}
-export async function registerChatRoutes(app: FastifyInstance, cfg: Config, oauth: OAuthVerifier | undefined, db: Db, redis: RedisClient): Promise {
+export async function registerChatRoutes(app: FastifyInstance, cfg: Config, db: Db): Promise {
app.addHook("onRequest", async (req, reply) => {
const p = (req.url.split("?")[0] ?? req.url) as string;
if (!p.startsWith("/chat-api/")) return;
try {
- const auth = await authenticateRequest(cfg, oauth, req.headers as any, db, redis, (req as any).ip);
- const method = req.method.toUpperCase();
- const required = p === "/chat-api/models" ? "model:invoke" : method === "GET" ? "chat:read" : "chat:write";
- if (!hasScope(auth, required)) {
- return reply.status(403).send({ error: { message: "insufficient scope", type: "auth_error" } });
- }
- (req as any).authContext = auth;
+ (req as any).authContext = authenticate(cfg, req.headers as any);
} catch {
return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
}
@@ -100,7 +88,7 @@ export async function registerChatRoutes(app: FastifyInstance, cfg: Config, oaut
app.post("/chat-api/conversations", async (req, reply) => {
const auth = (req as any).authContext as AuthContext;
const id = randomUUID();
- await createConversation(db, id, auth.principal, auth.tenantId ?? null);
+ await createConversation(db, id, auth.principal);
return { id };
});
diff --git a/oneapi-gateway/src/config.ts b/oneapi-gateway/src/config.ts
index 01e090e..5f413cb 100644
--- a/oneapi-gateway/src/config.ts
+++ b/oneapi-gateway/src/config.ts
@@ -1,56 +1,29 @@
import fs from "node:fs";
-import yaml from "js-yaml";
-import { parseCidrAllowList } from "./net.js";
-
-export type AuthMode = "apikey" | "oauth";
+import { load as loadYaml } from "js-yaml";
export type Config = {
appEnv: "development" | "staging" | "production" | "test";
port: number;
bodyLimitBytes?: number;
logLevel: "fatal" | "error" | "warn" | "info" | "debug" | "trace";
- trustProxy: boolean | number;
- adminUser: string;
- adminPass: string;
- adminAllowedCidrs?: string[] | null;
- metricsAllowedCidrs?: string[] | null;
+ trustProxy: boolean | string;
securityHeadersEnabled?: boolean;
- authModes: Set;
+ /** Keys defined in YAML. LiteLLM virtual keys are also accepted and validated by LiteLLM. */
apiKeys: Set;
- oauth: {
- jwksUrl?: string;
- audience?: string;
- issuer?: string;
- };
- upstreams: string[];
+ /** LiteLLM proxy base URL (model access plane). */
+ litellmBaseUrl: string;
+ /** Master key used by the gateway when it talks to LiteLLM on behalf of YAML keys. */
+ litellmMasterKey: string;
+ /** Public URL of the LiteLLM console (`/ui`). */
+ consoleUrl?: string;
upstreamTimeoutMs: number;
rateLimitRpm: number;
- cacheEnabled: boolean;
- cacheTtlSeconds: number;
- cacheReplayChunkDelayMs: number;
- cacheReplayMaxTotalMs: number;
- cacheReplayMode: "fixed" | "original";
- guardrails: {
- enabled: boolean;
- blockInternalIp: boolean;
- injectionKeywords: string[];
- piiMaskEnabled: boolean;
- };
corsOrigin: string | string[];
- tls?: {
- certPath: string;
- keyPath: string;
- };
internalToken?: string;
- internalTokenAllowCidrs?: string[] | null;
redisUrl: string;
databaseUrl: string;
- modelMap: Record;
- fallbackMap: Record;
};
-const PRIVATE_CIDRS = ["127.0.0.1/32", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10"];
-
function parseBytes(value: unknown, defaultBytes: number): number {
if (value === undefined || value === null || value === "") return defaultBytes;
if (typeof value === "number") return value;
@@ -63,15 +36,11 @@ function parseBytes(value: unknown, defaultBytes: number): number {
return Math.floor(n * multiplier);
}
-function arr(value: unknown, fallback: string[] = []): string[] {
- return Array.isArray(value) ? value.map((v) => String(v).trim()).filter(Boolean) : fallback;
-}
-
-function buildPostgresUrl(password: string): string {
- const host = "postgres";
- const port = 5432;
- const user = "oneapi";
- const name = "oneapi";
+function buildPostgresUrl(password: string, app: any): string {
+ const host = String(app.postgres_host ?? "postgres");
+ const port = Number(app.postgres_port ?? 5432);
+ const user = String(app.postgres_user ?? "oneapi");
+ const name = String(app.postgres_db ?? "oneapi");
return `postgres://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${host}:${port}/${encodeURIComponent(name)}`;
}
@@ -84,19 +53,16 @@ function isPlaceholderSecret(value: unknown): boolean {
);
}
-function assertNoPlaceholderSecrets(opts: {
- adminPass: string;
- apiKeys: Set;
- internalToken?: string;
- databaseUrl: string;
-}): void {
- if (isPlaceholderSecret(opts.adminPass)) throw new Error(`Refusing to start with placeholder admin password in production`);
+function assertNoPlaceholderSecrets(opts: { apiKeys: Set; internalToken?: string; masterKey: string; databaseUrl: string }): void {
for (const key of opts.apiKeys) {
if (isPlaceholderSecret(key)) throw new Error(`Refusing to start with placeholder api key in production`);
}
if (opts.internalToken && isPlaceholderSecret(opts.internalToken)) {
throw new Error(`Refusing to start with placeholder internal token in production`);
}
+ if (isPlaceholderSecret(opts.masterKey)) {
+ throw new Error(`Refusing to start with placeholder master key in production`);
+ }
if (opts.databaseUrl.includes("oneapi:oneapi@")) {
throw new Error(`Refusing to start with default database password in production`);
}
@@ -115,9 +81,7 @@ export function loadConfig(configPath = "/app/config/easyai.yaml"): Config {
throw new Error(`Configuration file not found: ${configPath}`);
}
- const fileContents = fs.readFileSync(configPath, "utf8");
- const parsed = yaml.load(fileContents) as any;
-
+ const parsed = loadYaml(fs.readFileSync(configPath, "utf8")) as any;
if (!parsed || typeof parsed !== "object") {
throw new Error("Invalid YAML configuration");
}
@@ -129,53 +93,29 @@ export function loadConfig(configPath = "/app/config/easyai.yaml"): Config {
const port = Number(app.port ?? 3003);
const bodyLimitBytes = parseBytes(app.body_limit, 10 * 1024 * 1024);
const logLevel = app.log_level ?? "info";
- const trustProxy = app.trust_proxy ?? false;
-
- const adminUser = "admin";
- const adminPass = String(secrets.admin_password ?? "").trim();
- const adminAllowedCidrs = parseCidrAllowList(undefined, appEnv === "production" ? PRIVATE_CIDRS : undefined);
- const metricsAllowedCidrs = parseCidrAllowList(undefined, appEnv === "production" ? PRIVATE_CIDRS : undefined);
+ const trustProxy = typeof app.trust_proxy === "number" ? String(app.trust_proxy) : (app.trust_proxy ?? false);
const securityHeadersEnabled = appEnv !== "development";
- const authModes = new Set(["apikey"]);
-
const apiKeysArr = Array.isArray(secrets.api_keys) ? secrets.api_keys : [];
- const apiKeys = new Set(apiKeysArr.map((s: string) => s.trim()).filter(Boolean));
-
- const oauth = {};
-
- const upstreams = ["http://litellm:4000"];
- const upstreamTimeoutMs = 60000;
-
- const rateLimitRpm = 120;
-
- const cacheEnabled = true;
- const cacheTtlSeconds = 60;
- const cacheReplayChunkDelayMs = 35;
- const cacheReplayMaxTotalMs = 10000;
- const cacheReplayMode = "original";
-
- const guardEnabled = true;
- const guardBlockInternalIp = true;
- const guardPiiMaskEnabled = false;
- const injectionKeywords = ["ignore all previous instructions", "system prompt", "developer message", "jailbreak"];
+ const apiKeys = new Set(apiKeysArr.map((s: string) => String(s).trim()).filter(Boolean));
- const corsOrigin = "*";
-
- const tls = undefined;
+ const litellmBaseUrl = String(app.litellm_base_url ?? "http://litellm:4000").replace(/\/+$/, "");
+ const litellmMasterKey = String(secrets.master_key ?? "").trim();
+ if (!litellmMasterKey) {
+ throw new Error("Missing secrets.master_key in configuration");
+ }
- const internalToken = secrets.internal_token;
- let internalTokenAllowCidrs: string[] | null | undefined = undefined;
- if (internalToken) internalTokenAllowCidrs = parseCidrAllowList(undefined, PRIVATE_CIDRS);
+ const consoleUrl = app.console_url ? String(app.console_url) : undefined;
+ const upstreamTimeoutMs = Number(app.upstream_timeout_ms ?? 60000);
+ const rateLimitRpm = Number(app.rate_limit_rpm ?? 120);
+ const corsOrigin = "*";
+ const internalToken = secrets.internal_token ? String(secrets.internal_token) : undefined;
const redisUrl = "redis://redis:6379";
- const databaseUrl = buildPostgresUrl(String(secrets.postgres_password ?? "oneapi"));
-
- const modelMap = {};
- const fallbackMap = {};
+ const databaseUrl = buildPostgresUrl(String(secrets.postgres_password ?? "oneapi"), app);
if (appEnv === "production") {
- assertNoPlaceholderSecrets({ adminPass, apiKeys, internalToken, databaseUrl });
+ assertNoPlaceholderSecrets({ apiKeys, internalToken, masterKey: litellmMasterKey, databaseUrl });
}
return {
@@ -184,39 +124,16 @@ export function loadConfig(configPath = "/app/config/easyai.yaml"): Config {
bodyLimitBytes,
logLevel,
trustProxy,
- adminUser,
- adminPass,
- adminAllowedCidrs,
- metricsAllowedCidrs,
securityHeadersEnabled,
- authModes,
apiKeys,
- oauth: {
- jwksUrl: undefined,
- audience: undefined,
- issuer: undefined,
- },
- upstreams,
+ litellmBaseUrl,
+ litellmMasterKey,
+ consoleUrl,
upstreamTimeoutMs,
rateLimitRpm,
- cacheEnabled,
- cacheTtlSeconds,
- cacheReplayChunkDelayMs,
- cacheReplayMaxTotalMs,
- cacheReplayMode,
- guardrails: {
- enabled: guardEnabled,
- blockInternalIp: guardBlockInternalIp,
- injectionKeywords,
- piiMaskEnabled: guardPiiMaskEnabled,
- },
corsOrigin,
- tls,
internalToken,
- internalTokenAllowCidrs,
redisUrl,
databaseUrl,
- modelMap,
- fallbackMap,
};
}
diff --git a/oneapi-gateway/src/dashboard.ts b/oneapi-gateway/src/dashboard.ts
deleted file mode 100644
index 421f37e..0000000
--- a/oneapi-gateway/src/dashboard.ts
+++ /dev/null
@@ -1,469 +0,0 @@
-import type { FastifyInstance } from "fastify";
-import fastifyStatic from "@fastify/static";
-import path from "node:path";
-import { Readable } from "node:stream";
-import { fileURLToPath } from "node:url";
-import fs from "node:fs";
-import type { Config } from "./config.js";
-import type { Db } from "./db.js";
-import { getUsageSummary } from "./db.js";
-import { ipAllowed } from "./net.js";
-import { clearAdminSessionCookie, createAdminSessionCookie, isAdminRequest } from "./admin-auth.js";
-import { buildGlobalNav, buildThemeInitScript, injectGlobalNav } from "./ui-shell.js";
-
-function requireAdminAction(req: any): boolean {
- const h = req.headers["x-oneapi-admin-action"];
- const v = Array.isArray(h) ? h[0] : h;
- return String(v ?? "") === "1";
-}
-
-function buildPlaygroundAuthHeaders(cfg: Config): Record | undefined {
- if (cfg.internalToken) {
- return {
- "x-oneapi-internal-token": cfg.internalToken,
- "x-oneapi-principal": "admin:playground",
- };
- }
- const firstApiKey = Array.from(cfg.apiKeys.values())[0];
- if (firstApiKey) {
- return { authorization: `Bearer ${firstApiKey}` };
- }
- return;
-}
-
-function buildHomeHtml(cfg: Config, isAdmin: boolean, loginState?: string): string {
- const capabilityItems = [
- "统一 OpenAI-compatible 入口,屏蔽上游模型服务差异",
- "支持 API Key 调用,按租户做配额和限流治理",
- "内置聊天界面,支持会话历史、流式输出和模型测试",
- "提供 Batch API,用于离线批量请求和异步处理",
- "提供缓存、回放、指标和用量统计,便于控制成本和排障",
- "提供注入拦截、内网 IP 拦截和可选 PII 脱敏能力",
- ];
- const usageSteps = [
- {
- title: "1. 启动服务",
- body: "使用 Docker Compose 启动完整栈,网关会自动连接 LiteLLM、Redis、Postgres、Ollama 和 Batch Worker。",
- hint: "docker compose up -d --build",
- },
- {
- title: "2. 选择入口",
- body: "普通用户进入会话页并输入 API Key;管理员先在首页登录后进入 Dashboard;开发者可直接打开 API 文档。",
- hint: "Chat / Dashboard / Docs",
- },
- {
- title: "3. 开始使用",
- body: "管理员在 Dashboard 创建 API Key 并绑定租户;用户使用分配到的 Key 调用接口或进入会话页。",
- hint: "API Key / Tenant / Usage",
- },
- ];
- return `
-
-
- ${buildThemeInitScript()}
-
-
- EasyAI Console
-
-
-
- ${buildGlobalNav({ active: "home", isAdmin, loginState })}
-
-
-
-
EasyAI Platform
-
统一入口:会话、管理和 API 文档
-
EasyAI 提供 OpenAI-compatible 网关、本地模型接入、会话页、API Key 管理、租户治理、批处理和用量统计。
-
顶部导航集中提供会话页、API 文档和管理员登录入口;正文只保留平台能力与使用顺序。
-
-
-
-
- 项目能做什么
- 这套服务不是单纯的聊天页,而是一个可直接用于本地开发、团队试用和生产接入的 LLM 服务平台。
-
- ${capabilityItems.map((item) => `- ${escapeHtml(item)}
`).join("")}
-
-
-
-
- 用户怎么用
- 推荐的使用顺序很简单:先启动服务,再选择入口,最后按角色完成自己的操作。
-
- ${usageSteps.map((step) => `
${step.title}${step.body}
${step.hint} `).join("")}
-
-
-
-
- ${isAdmin ? "" : ``}
-
-`;
-}
-
-function escapeHtml(value: string): string {
- return value
- .replaceAll("&", "&")
- .replaceAll("<", "<")
- .replaceAll(">", ">")
- .replaceAll('"', """)
- .replaceAll("'", "'");
-}
-
-export async function registerDashboard(app: FastifyInstance, cfg: Config, db: Db): Promise {
- app.addContentTypeParser("application/x-www-form-urlencoded", { parseAs: "string" }, (_req, body, done) => {
- done(null, body);
- });
-
- app.addHook("onRequest", async (req, reply) => {
- const p = (req.url.split("?")[0] ?? req.url) as string;
- if (p.startsWith("/dashboard/assets/")) return;
- const needsAuth = p === "/dashboard" || p.startsWith("/dashboard/") || p.startsWith("/admin/api/");
- if (!needsAuth) return;
- if (!ipAllowed((req as any).ip, cfg.adminAllowedCidrs)) {
- return reply.status(403).send({ error: { message: "forbidden", type: "auth_error" } });
- }
- const ok = isAdminRequest(req, cfg);
- if (ok) return;
- if (p.startsWith("/admin/api/")) return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- return reply.redirect("/?adminLogin=required");
- });
-
- const __filename = fileURLToPath(import.meta.url);
- const __dirname = path.dirname(__filename);
-
- app.get("/", async (req, reply) => {
- reply.type("text/html; charset=utf-8");
- const loginState = String((req.query as any)?.adminLogin ?? "");
- return reply.send(buildHomeHtml(cfg, isAdminRequest(req, cfg), loginState));
- });
-
- app.get("/admin/session.js", async (_req, reply) => {
- reply.type("application/javascript; charset=utf-8");
- return reply.send(`
-const form = document.getElementById("admin-login-form");
-if (form) {
- form.addEventListener("submit", async (event) => {
- event.preventDefault();
- const data = new FormData(form);
- const res = await fetch("/admin/session", {
- method: "POST",
- headers: { "content-type": "application/json", "accept": "application/json" },
- body: JSON.stringify({
- username: String(data.get("username") || ""),
- password: String(data.get("password") || "")
- })
- });
- window.location.href = res.ok ? "/" : "/?adminLogin=failed";
- });
-}
-`);
- });
-
- app.post("/admin/session", async (req, reply) => {
- if (!ipAllowed((req as any).ip, cfg.adminAllowedCidrs)) {
- return reply.status(403).send({ error: { message: "forbidden", type: "auth_error" } });
- }
- const body = (req.body ?? {}) as any;
- const username = String(body.username ?? "").trim();
- const password = String(body.password ?? "");
- if (username !== cfg.adminUser || password !== cfg.adminPass) {
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
- reply.header("set-cookie", createAdminSessionCookie(cfg));
- return { ok: true };
- });
-
- app.post("/admin/session/logout", async (_req, reply) => {
- reply.header("set-cookie", clearAdminSessionCookie());
- return reply.redirect("/", 303);
- });
-
- const dashboardRoot = path.resolve(__dirname, "../admin-ui/dist");
-
- if (fs.existsSync(dashboardRoot)) {
- const assetsRoot = path.join(dashboardRoot, "assets");
- if (fs.existsSync(assetsRoot)) {
- await app.register(fastifyStatic, { root: assetsRoot, prefix: "/dashboard/assets/" });
- }
-
- app.get("/dashboard", async (_req, reply) => {
- const html = fs.readFileSync(path.join(dashboardRoot, "index.html"), "utf8");
- reply.type("text/html; charset=utf-8");
- return reply.send(injectGlobalNav(html, { active: "dashboard" }));
- });
-
- app.get("/dashboard/*", async (_req, reply) => {
- const html = fs.readFileSync(path.join(dashboardRoot, "index.html"), "utf8");
- reply.type("text/html; charset=utf-8");
- return reply.send(injectGlobalNav(html, { active: "dashboard" }));
- });
- } else {
- app.get("/dashboard", async (_req, reply) => {
- return reply.status(503).send("Dashboard not built");
- });
- }
-
- const chatRoot = path.resolve(__dirname, "../chat-ui/dist");
- if (fs.existsSync(chatRoot)) {
- const chatAssetsRoot = path.join(chatRoot, "assets");
- if (fs.existsSync(chatAssetsRoot)) {
- await app.register(fastifyStatic, { root: chatAssetsRoot, prefix: "/chat/assets/", decorateReply: false });
- }
-
- app.get("/chat", async (_req, reply) => {
- const html = fs.readFileSync(path.join(chatRoot, "index.html"), "utf8");
- reply.type("text/html; charset=utf-8");
- return reply.send(injectGlobalNav(html, { active: "chat" }));
- });
-
- app.get("/chat/*", async (_req, reply) => {
- const html = fs.readFileSync(path.join(chatRoot, "index.html"), "utf8");
- reply.type("text/html; charset=utf-8");
- return reply.send(injectGlobalNav(html, { active: "chat" }));
- });
- } else {
- app.get("/chat", async (_req, reply) => {
- return reply.status(503).send("Chat UI not built");
- });
- }
-
- app.get("/admin/api/usage", async (req, reply) => {
- const ok = isAdminRequest(req, cfg);
- if (!ok) {
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
-
- const sinceMinutes = Math.max(1, Math.min(24 * 60, Number((req.query as any)?.sinceMinutes ?? "60")));
- const rows = await getUsageSummary(db, sinceMinutes);
- return { rows };
- });
-
- app.get("/admin/api/playground/models", async (req, reply) => {
- const ok = isAdminRequest(req, cfg);
- if (!ok) {
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
- const authHeaders = buildPlaygroundAuthHeaders(cfg);
- if (!authHeaders) return reply.status(503).send({ error: { message: "no playground auth configured", type: "gateway_error" } });
-
- const upstream = await app.inject({
- method: "GET",
- url: "/v1/models",
- headers: authHeaders,
- });
-
- reply.status(upstream.statusCode);
- const contentType = upstream.headers["content-type"];
- if (contentType) reply.header("content-type", String(contentType));
- const payload = upstream.body;
- if (!payload) return reply.send({});
- try {
- return reply.send(JSON.parse(payload));
- } catch {
- return reply.send(payload);
- }
- });
-
- app.post("/admin/api/playground/chat", async (req, reply) => {
- const ok = isAdminRequest(req, cfg);
- if (!ok || !requireAdminAction(req)) {
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
- const authHeaders = buildPlaygroundAuthHeaders(cfg);
- if (!authHeaders) return reply.status(503).send({ error: { message: "no playground auth configured", type: "gateway_error" } });
-
- const body = (req.body ?? {}) as any;
- if (!body || typeof body !== "object") return reply.status(400).send({ error: { message: "invalid body", type: "invalid_request_error" } });
- if (typeof body.model !== "string" || !body.model.trim()) return reply.status(400).send({ error: { message: "model is required", type: "invalid_request_error" } });
- if (!Array.isArray(body.messages) || body.messages.length === 0) {
- return reply.status(400).send({ error: { message: "messages is required", type: "invalid_request_error" } });
- }
-
- const payload = {
- ...body,
- stream: body.stream === true,
- };
-
- if (payload.stream) {
- if (cfg.port > 0) {
- const upstream = await fetch(`http://127.0.0.1:${cfg.port}/v1/chat/completions`, {
- method: "POST",
- headers: {
- ...authHeaders,
- accept: "text/event-stream",
- "content-type": "application/json",
- },
- body: JSON.stringify(payload),
- });
-
- reply.status(upstream.status);
- const contentType = upstream.headers.get("content-type");
- if (contentType) reply.header("content-type", contentType);
- reply.header("cache-control", "no-store");
- reply.header("x-accel-buffering", "no");
-
- if (!upstream.body) {
- return reply.send(await upstream.text());
- }
- return reply.send(Readable.fromWeb(upstream.body as any));
- }
-
- const injected = await app.inject({
- method: "POST",
- url: "/v1/chat/completions",
- headers: {
- ...authHeaders,
- accept: "text/event-stream",
- "content-type": "application/json",
- },
- payload,
- });
- reply.status(injected.statusCode);
- const contentType = injected.headers["content-type"];
- if (contentType) reply.header("content-type", String(contentType));
- reply.header("cache-control", "no-store");
- return reply.send(injected.body);
- }
-
- const upstream = await app.inject({
- method: "POST",
- url: "/v1/chat/completions",
- headers: {
- ...authHeaders,
- "content-type": "application/json",
- },
- payload,
- });
-
- reply.status(upstream.statusCode);
- const contentType = upstream.headers["content-type"];
- if (contentType) reply.header("content-type", String(contentType));
- const payloadText = upstream.body;
- if (!payloadText) return reply.send({});
- try {
- return reply.send(JSON.parse(payloadText));
- } catch {
- return reply.send(payloadText);
- }
- });
-}
diff --git a/oneapi-gateway/src/db.ts b/oneapi-gateway/src/db.ts
index dd18794..afd77db 100644
--- a/oneapi-gateway/src/db.ts
+++ b/oneapi-gateway/src/db.ts
@@ -16,136 +16,15 @@ export async function createDb(databaseUrl: string): Promise {
};
}
+/**
+ * EasyAI only owns chat history + batch bookkeeping.
+ * API keys, tenants, spend and request logs live in LiteLLM.
+ */
async function migrate(pool: pg.Pool): Promise {
- await pool.query(`
- create table if not exists usage_events (
- id bigserial primary key,
- ts timestamptz not null default now(),
- principal text not null,
- api_key_id bigint,
- api_key_hash text,
- tenant_id text,
- auth_mode text not null,
- model text,
- endpoint text not null,
- method text not null,
- status int not null,
- latency_ms int not null,
- cached boolean not null default false,
- upstream text,
- request_bytes int,
- response_bytes int,
- prompt_tokens int,
- completion_tokens int,
- total_tokens int,
- error text,
- ttft_ms int,
- tps double precision
- );
- `);
- await pool.query(`
- do $$
- begin
- if not exists (select 1 from information_schema.columns where table_name='usage_events' and column_name='ttft_ms') then
- alter table usage_events add column ttft_ms int;
- end if;
- if not exists (select 1 from information_schema.columns where table_name='usage_events' and column_name='tps') then
- alter table usage_events add column tps double precision;
- end if;
- if not exists (select 1 from information_schema.columns where table_name='usage_events' and column_name='api_key_id') then
- alter table usage_events add column api_key_id bigint;
- end if;
- if not exists (select 1 from information_schema.columns where table_name='usage_events' and column_name='tenant_id') then
- alter table usage_events add column tenant_id text;
- end if;
- end $$;
- `);
- await pool.query(`create index if not exists usage_events_ts_idx on usage_events(ts desc);`);
- await pool.query(`create index if not exists usage_events_principal_ts_idx on usage_events(principal, ts desc);`);
- await pool.query(`create index if not exists usage_events_api_key_id_ts_idx on usage_events(api_key_id, ts desc);`);
- await pool.query(`create index if not exists usage_events_tenant_id_ts_idx on usage_events(tenant_id, ts desc);`);
-
- // api_keys must be created before the backfill UPDATE that references it
- await pool.query(`
- create table if not exists api_keys (
- id bigserial primary key,
- key_hash text not null unique,
- key_prefix text not null,
- created_at timestamptz not null default now(),
- revoked_at timestamptz,
- rpm_limit int,
- tenant_id text
- );
- `);
- await pool.query(`
- do $$
- begin
- if not exists (select 1 from information_schema.columns where table_name='api_keys' and column_name='tenant_id') then
- alter table api_keys add column tenant_id text;
- end if;
- if not exists (select 1 from information_schema.columns where table_name='api_keys' and column_name='name') then
- alter table api_keys add column name text;
- end if;
- if not exists (select 1 from information_schema.columns where table_name='api_keys' and column_name='key_suffix') then
- alter table api_keys add column key_suffix text;
- end if;
- if not exists (select 1 from information_schema.columns where table_name='api_keys' and column_name='environment') then
- alter table api_keys add column environment text not null default 'production';
- end if;
- if not exists (select 1 from information_schema.columns where table_name='api_keys' and column_name='scopes') then
- alter table api_keys add column scopes text[];
- end if;
- if not exists (select 1 from information_schema.columns where table_name='api_keys' and column_name='expires_at') then
- alter table api_keys add column expires_at timestamptz;
- end if;
- if not exists (select 1 from information_schema.columns where table_name='api_keys' and column_name='last_used_at') then
- alter table api_keys add column last_used_at timestamptz;
- end if;
- if not exists (select 1 from information_schema.columns where table_name='api_keys' and column_name='last_used_ip') then
- alter table api_keys add column last_used_ip text;
- end if;
- if not exists (select 1 from information_schema.columns where table_name='api_keys' and column_name='revocation_scheduled_at') then
- alter table api_keys add column revocation_scheduled_at timestamptz;
- end if;
- if not exists (select 1 from information_schema.columns where table_name='api_keys' and column_name='auto_revoke_after_unused_days') then
- alter table api_keys add column auto_revoke_after_unused_days int;
- end if;
- if not exists (select 1 from information_schema.columns where table_name='api_keys' and column_name='ip_allow_cidrs') then
- alter table api_keys add column ip_allow_cidrs text[];
- end if;
- end $$;
- `);
- await pool.query(`create index if not exists api_keys_revoked_idx on api_keys(revoked_at);`);
- await pool.query(`create index if not exists api_keys_tenant_idx on api_keys(tenant_id);`);
- await pool.query(`create index if not exists api_keys_prefix_idx on api_keys(key_prefix);`);
- await pool.query(`create index if not exists api_keys_last_used_idx on api_keys(last_used_at desc);`);
-
- await pool.query(`
- update usage_events ue
- set
- api_key_id = ak.id,
- tenant_id = coalesce(ue.tenant_id, ak.tenant_id)
- from api_keys ak
- where ue.api_key_id is null
- and ue.api_key_hash = ak.key_hash
- `);
-
- await pool.query(`
- create table if not exists tenants (
- tenant_id text primary key,
- created_at timestamptz not null default now(),
- rpm_limit int,
- tpm_limit int,
- disabled boolean not null default false
- );
- `);
- await pool.query(`create index if not exists tenants_disabled_idx on tenants(disabled);`);
-
await pool.query(`
create table if not exists batches (
batch_id text primary key,
principal text not null,
- tenant_id text,
status text not null,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
@@ -175,7 +54,6 @@ async function migrate(pool: pg.Pool): Promise {
id uuid primary key,
title text not null default '',
principal text not null,
- tenant_id text,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
@@ -197,375 +75,11 @@ async function migrate(pool: pg.Pool): Promise {
await pool.query(`create index if not exists messages_conversation_idx on messages(conversation_id, created_at asc);`);
}
-export type UsageEvent = {
- principal: string;
- apiKeyId?: number;
- apiKeyHash?: string;
- tenantId?: string | null;
- authMode: string;
- model?: string;
- endpoint: string;
- method: string;
- status: number;
- latencyMs: number;
- cached: boolean;
- upstream?: string;
- requestBytes?: number;
- responseBytes?: number;
- promptTokens?: number;
- completionTokens?: number;
- totalTokens?: number;
- error?: string;
- ttftMs?: number;
- tps?: number;
-};
-
-export async function insertUsageEvent(db: Db, e: UsageEvent): Promise {
- await db.pool.query(
- `
- insert into usage_events (
- principal, api_key_id, api_key_hash, tenant_id, auth_mode, model, endpoint, method, status, latency_ms, cached, upstream,
- request_bytes, response_bytes, prompt_tokens, completion_tokens, total_tokens, error, ttft_ms, tps
- ) values (
- $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,
- $11,$12,$13,$14,$15,$16,$17,$18,$19,$20
- )
- `,
- [
- e.principal,
- e.apiKeyId ?? null,
- e.apiKeyHash ?? null,
- e.tenantId ?? null,
- e.authMode,
- e.model ?? null,
- e.endpoint,
- e.method,
- e.status,
- e.latencyMs,
- e.cached,
- e.upstream ?? null,
- e.requestBytes ?? null,
- e.responseBytes ?? null,
- e.promptTokens ?? null,
- e.completionTokens ?? null,
- e.totalTokens ?? null,
- e.error ?? null,
- e.ttftMs ?? null,
- e.tps ?? null,
- ],
- );
-}
-
-export type UsageSummaryRow = {
- principal: string;
- auth_mode: string;
- tenant_id: string | null;
- api_key_id: number | null;
- api_key_prefix: string | null;
- requests: number;
- errors: number;
- cached: number;
- p95_latency_ms: number | null;
- total_tokens: number | null;
-};
-
-async function processDueApiKeyRevocations(db: Db): Promise {
- await db.pool.query(`
- update api_keys
- set revoked_at = now()
- where revoked_at is null
- and revocation_scheduled_at is not null
- and revocation_scheduled_at <= now()
- `);
- await db.pool.query(`
- update api_keys
- set revoked_at = now()
- where revoked_at is null
- and auto_revoke_after_unused_days is not null
- and auto_revoke_after_unused_days > 0
- and coalesce(last_used_at, created_at) <= now() - (auto_revoke_after_unused_days::text || ' days')::interval
- `);
-}
-
-export async function getUsageSummary(db: Db, sinceMinutes: number): Promise {
- const res = await db.pool.query(
- `
- select
- ue.principal,
- ue.auth_mode,
- ue.tenant_id,
- ue.api_key_id::bigint,
- ak.key_prefix as api_key_prefix,
- count(*)::int as requests,
- sum(case when ue.status >= 400 then 1 else 0 end)::int as errors,
- sum(case when ue.cached then 1 else 0 end)::int as cached,
- percentile_cont(0.95) within group (order by ue.latency_ms)::float as p95_latency_ms,
- sum(ue.total_tokens)::bigint as total_tokens
- from usage_events ue
- left join api_keys ak on ak.id = ue.api_key_id
- where ue.ts >= now() - ($1::text || ' minutes')::interval
- group by ue.principal, ue.auth_mode, ue.tenant_id, ue.api_key_id, ak.key_prefix
- order by requests desc
- limit 200
- `,
- [String(sinceMinutes)],
- );
- return res.rows;
-}
-
-export type ApiKeyRow = {
- id: number;
- key_hash: string;
- key_prefix: string;
- key_suffix: string | null;
- name: string | null;
- environment: string;
- scopes: string[] | null;
- created_at: string;
- revoked_at: string | null;
- expires_at: string | null;
- last_used_at: string | null;
- last_used_ip: string | null;
- revocation_scheduled_at: string | null;
- auto_revoke_after_unused_days: number | null;
- ip_allow_cidrs: string[] | null;
- rpm_limit: number | null;
- tenant_id: string | null;
-};
-
-export async function listApiKeys(db: Db): Promise {
- await processDueApiKeyRevocations(db);
- const res = await db.pool.query(
- `
- select
- id, key_hash, key_prefix, key_suffix, name, environment, scopes,
- created_at::text, revoked_at::text, expires_at::text, last_used_at::text, last_used_ip,
- revocation_scheduled_at::text, auto_revoke_after_unused_days, ip_allow_cidrs,
- rpm_limit, tenant_id
- from api_keys
- order by id desc
- limit 500
- `,
- );
- return res.rows;
-}
-
-export type NewApiKeyInput = {
- keyHash: string;
- keyPrefix: string;
- keySuffix: string;
- name?: string | null;
- environment?: string | null;
- scopes?: string[] | null;
- expiresAt?: string | null;
- ipAllowCidrs?: string[] | null;
-};
-
-export async function insertApiKey(db: Db, input: NewApiKeyInput): Promise<{ id: number }> {
- const res = await db.pool.query(
- `
- insert into api_keys (key_hash, key_prefix, key_suffix, name, environment, scopes, expires_at, ip_allow_cidrs)
- values ($1, $2, $3, $4, $5, $6, $7, $8)
- returning id
- `,
- [
- input.keyHash,
- input.keyPrefix,
- input.keySuffix,
- input.name ?? null,
- input.environment || "production",
- input.scopes && input.scopes.length ? input.scopes : null,
- input.expiresAt ?? null,
- input.ipAllowCidrs && input.ipAllowCidrs.length ? input.ipAllowCidrs : null,
- ],
- );
- return { id: Number(res.rows[0]?.id) };
-}
-
-export async function revokeApiKey(db: Db, id: number): Promise {
- await db.pool.query(`update api_keys set revoked_at = now(), revocation_scheduled_at = null where id = $1 and revoked_at is null`, [id]);
-}
-
-export async function scheduleApiKeyRevocation(db: Db, id: number, scheduledAt: string): Promise {
- await db.pool.query(`update api_keys set revocation_scheduled_at = $2 where id = $1 and revoked_at is null`, [id, scheduledAt]);
-}
-
-export async function updateApiKeyAutoRevoke(db: Db, id: number, unusedDays: number | null): Promise {
- await db.pool.query(`update api_keys set auto_revoke_after_unused_days = $2 where id = $1 and revoked_at is null`, [id, unusedDays]);
-}
-
-export async function updateApiKeyRpm(db: Db, id: number, rpmLimit: number | null): Promise {
- await db.pool.query(`update api_keys set rpm_limit = $2 where id = $1`, [id, rpmLimit]);
-}
-
-export async function updateApiKeyTenant(db: Db, id: number, tenantId: string | null): Promise {
- await db.pool.query(`update api_keys set tenant_id = $2 where id = $1`, [id, tenantId]);
-}
-
-export type ApiKeyPatch = {
- name?: string | null;
- environment?: string;
- scopes?: string[] | null;
- expiresAt?: string | null;
- ipAllowCidrs?: string[] | null;
-};
-
-export async function updateApiKeyMetadata(db: Db, id: number, patch: ApiKeyPatch): Promise {
- await db.pool.query(
- `
- update api_keys
- set
- name = $2,
- environment = $3,
- scopes = $4,
- expires_at = $5,
- ip_allow_cidrs = $6
- where id = $1
- `,
- [
- id,
- patch.name ?? null,
- patch.environment || "production",
- patch.scopes && patch.scopes.length ? patch.scopes : null,
- patch.expiresAt ?? null,
- patch.ipAllowCidrs && patch.ipAllowCidrs.length ? patch.ipAllowCidrs : null,
- ],
- );
-}
-
-export async function findActiveApiKeyByHash(
- db: Db,
- keyHash: string,
-): Promise<{
- id: number;
- rpm_limit: number | null;
- tenant_id: string | null;
- scopes: string[] | null;
- environment: string;
- ip_allow_cidrs: string[] | null;
-} | undefined> {
- await processDueApiKeyRevocations(db);
- const res = await db.pool.query(
- `
- select id, rpm_limit, tenant_id, scopes, environment, ip_allow_cidrs
- from api_keys
- where key_hash = $1
- and revoked_at is null
- and (expires_at is null or expires_at > now())
- and (revocation_scheduled_at is null or revocation_scheduled_at > now())
- limit 1
- `,
- [keyHash],
- );
- if (!res.rows?.length) return;
- return {
- id: Number(res.rows[0].id),
- rpm_limit: res.rows[0].rpm_limit ?? null,
- tenant_id: res.rows[0].tenant_id ?? null,
- scopes: res.rows[0].scopes ?? null,
- environment: res.rows[0].environment ?? "production",
- ip_allow_cidrs: res.rows[0].ip_allow_cidrs ?? null,
- };
-}
-
-export async function markApiKeyUsed(db: Db, id: number, ip?: string): Promise {
- await db.pool.query(`update api_keys set last_used_at = now(), last_used_ip = $2 where id = $1`, [id, ip ?? null]);
-}
-
-export type ApiKeyUsageRow = {
- day: string;
- requests: number;
- errors: number;
- total_tokens: number | null;
-};
-
-export async function getApiKeyUsage(db: Db, id: number, sinceMinutes: number): Promise {
- const res = await db.pool.query(
- `
- select
- date_trunc('hour', ts)::text as day,
- count(*)::int as requests,
- sum(case when status >= 400 then 1 else 0 end)::int as errors,
- sum(total_tokens)::bigint as total_tokens
- from usage_events
- where api_key_id = $1
- and ts >= now() - ($2::text || ' minutes')::interval
- group by 1
- order by 1 desc
- limit 200
- `,
- [id, String(sinceMinutes)],
- );
- return res.rows;
-}
-
-export type TenantRow = {
- tenant_id: string;
- created_at: string;
- rpm_limit: number | null;
- tpm_limit: number | null;
- disabled: boolean;
-};
-
-export async function deleteApiKey(db: Db, id: number, force: boolean): Promise<"deleted" | "not_found" | "must_revoke"> {
- const existsRes = await db.pool.query(`select id, key_hash, revoked_at, tenant_id from api_keys where id=$1 limit 1`, [id]);
- if (!existsRes.rows?.length) return "not_found";
- const row = existsRes.rows[0];
-
- if (!force && !row.revoked_at) return "must_revoke";
-
- await db.pool.query(`delete from usage_events where api_key_id=$1`, [row.id]);
-
- const res = await db.pool.query(`delete from api_keys where id=$1`, [id]);
- return res.rowCount === 1 ? "deleted" : "not_found";
-}
-
-export async function deleteTenant(
- db: Db,
- tenantId: string,
- force: boolean,
-): Promise<"deleted" | "not_found" | "has_keys"> {
- if (!force) {
- const res = await db.pool.query(
- `
- delete from tenants
- where tenant_id = $1
- and not exists (select 1 from api_keys where tenant_id = $1)
- `,
- [tenantId],
- );
- if (res.rowCount === 1) return "deleted";
-
- const existsRes = await db.pool.query(`select tenant_id from tenants where tenant_id=$1 limit 1`, [tenantId]);
- if (!existsRes.rows?.length) return "not_found";
-
- const keysRes = await db.pool.query(`select 1 from api_keys where tenant_id=$1 limit 1`, [tenantId]);
- if (keysRes.rows?.length) return "has_keys";
- await db.pool.query(`delete from usage_events where tenant_id=$1`, [tenantId]);
- const res2 = await db.pool.query(`delete from tenants where tenant_id=$1`, [tenantId]);
- return res2.rowCount === 1 ? "deleted" : "not_found";
- }
-
- const existsRes = await db.pool.query(`select tenant_id from tenants where tenant_id=$1 limit 1`, [tenantId]);
- if (!existsRes.rows?.length) return "not_found";
-
- await db.pool.query(`delete from usage_events where tenant_id=$1`, [tenantId]);
- await db.pool.query(`update api_keys set tenant_id=null where tenant_id=$1`, [tenantId]);
- await db.pool.query(`delete from tenants where tenant_id=$1`, [tenantId]);
- return "deleted";
-}
-
-export async function unbindTenantKeys(db: Db, tenantId: string): Promise {
- const res = await db.pool.query(`update api_keys set tenant_id=null where tenant_id=$1`, [tenantId]);
- return res.rowCount ?? 0;
-}
-
export type BatchStatus = "queued" | "running" | "completed" | "failed";
export type BatchRow = {
batch_id: string;
principal: string;
- tenant_id: string | null;
status: BatchStatus;
created_at: string;
updated_at: string;
@@ -574,19 +88,13 @@ export type BatchRow = {
failed: number;
};
-export async function createBatch(
- db: Db,
- batchId: string,
- principal: string,
- tenantId: string | null,
- total: number,
-): Promise {
+export async function createBatch(db: Db, batchId: string, principal: string, total: number): Promise {
await db.pool.query(
`
- insert into batches (batch_id, principal, tenant_id, status, total)
- values ($1, $2, $3, 'queued', $4)
+ insert into batches (batch_id, principal, status, total)
+ values ($1, $2, 'queued', $3)
`,
- [batchId, principal, tenantId, total],
+ [batchId, principal, total],
);
}
@@ -609,7 +117,7 @@ export async function insertBatchItem(
export async function getBatch(db: Db, batchId: string): Promise {
const res = await db.pool.query(
`
- select batch_id, principal, tenant_id, status, created_at::text, updated_at::text, total, completed, failed
+ select batch_id, principal, status, created_at::text, updated_at::text, total, completed, failed
from batches
where batch_id = $1
limit 1
@@ -636,122 +144,24 @@ export async function listBatchItems(
return res.rows;
}
-export async function claimBatch(db: Db, batchId: string): Promise {
- const res = await db.pool.query(
- `update batches set status='running', updated_at=now() where batch_id=$1 and status='queued'`,
- [batchId],
- );
- return res.rowCount === 1;
-}
-
-export async function markBatchItemResult(
- db: Db,
- batchId: string,
- idx: number,
- status: "completed" | "failed",
- responseJson: string | null,
- error: string | null,
-): Promise {
- await db.pool.query(
- `
- update batch_items
- set status=$3, response_json=$4, error=$5
- where batch_id=$1 and idx=$2
- `,
- [batchId, idx, status, responseJson, error],
- );
-}
-
-export async function finishBatch(db: Db, batchId: string): Promise {
- await db.pool.query(
- `
- with s as (
- select
- sum(case when status='completed' then 1 else 0 end)::int as completed,
- sum(case when status='failed' then 1 else 0 end)::int as failed
- from batch_items
- where batch_id = $1
- )
- update batches
- set
- status = case when (select failed from s) > 0 then 'failed' else 'completed' end,
- completed = (select completed from s),
- failed = (select failed from s),
- updated_at = now()
- where batch_id = $1
- `,
- [batchId],
- );
-}
-
-export async function listTenants(db: Db): Promise {
- const res = await db.pool.query(
- `
- select tenant_id, created_at::text, rpm_limit, tpm_limit, disabled
- from tenants
- order by tenant_id asc
- limit 500
- `,
- );
- return res.rows;
-}
-
-export async function upsertTenant(
- db: Db,
- tenantId: string,
- rpmLimit: number | null,
- tpmLimit: number | null,
- disabled: boolean,
-): Promise {
- await db.pool.query(
- `
- insert into tenants (tenant_id, rpm_limit, tpm_limit, disabled)
- values ($1, $2, $3, $4)
- on conflict (tenant_id) do update set
- rpm_limit = excluded.rpm_limit,
- tpm_limit = excluded.tpm_limit,
- disabled = excluded.disabled
- `,
- [tenantId, rpmLimit, tpmLimit, disabled],
- );
-}
-
-export async function findTenant(db: Db, tenantId: string): Promise {
- const res = await db.pool.query(
- `select tenant_id, created_at::text, rpm_limit, tpm_limit, disabled from tenants where tenant_id = $1 limit 1`,
- [tenantId],
- );
- if (!res.rows?.length) return;
- return res.rows[0];
-}
-
export type ConversationRow = {
id: string;
title: string;
principal: string;
- tenant_id: string | null;
created_at: string;
updated_at: string;
message_count: number;
};
-export async function createConversation(
- db: Db,
- id: string,
- principal: string,
- tenantId: string | null,
-): Promise {
- await db.pool.query(
- `insert into conversations (id, title, principal, tenant_id) values ($1, $2, $3, $4)`,
- [id, "", principal, tenantId],
- );
+export async function createConversation(db: Db, id: string, principal: string): Promise {
+ await db.pool.query(`insert into conversations (id, title, principal) values ($1, $2, $3)`, [id, "", principal]);
}
export async function listConversations(db: Db, principal: string): Promise {
const res = await db.pool.query(
`
select
- c.id, c.title, c.principal, c.tenant_id, c.created_at::text, c.updated_at::text,
+ c.id, c.title, c.principal, c.created_at::text, c.updated_at::text,
coalesce(msg_counts.cnt, 0)::int as message_count
from conversations c
left join (
@@ -770,7 +180,7 @@ export async function getConversation(db: Db, id: string, principal: string): Pr
const res = await db.pool.query(
`
select
- c.id, c.title, c.principal, c.tenant_id, c.created_at::text, c.updated_at::text,
+ c.id, c.title, c.principal, c.created_at::text, c.updated_at::text,
coalesce(msg_counts.cnt, 0)::int as message_count
from conversations c
left join (
@@ -786,10 +196,7 @@ export async function getConversation(db: Db, id: string, principal: string): Pr
}
export async function updateConversationTitle(db: Db, id: string, title: string): Promise {
- await db.pool.query(
- `update conversations set title = $2, updated_at = now() where id = $1`,
- [id, title],
- );
+ await db.pool.query(`update conversations set title = $2, updated_at = now() where id = $1`, [id, title]);
}
export async function touchConversation(db: Db, id: string): Promise {
@@ -797,10 +204,7 @@ export async function touchConversation(db: Db, id: string): Promise {
}
export async function deleteConversation(db: Db, id: string, principal: string): Promise<"deleted" | "not_found"> {
- const res = await db.pool.query(
- `delete from conversations where id = $1 and principal = $2`,
- [id, principal],
- );
+ const res = await db.pool.query(`delete from conversations where id = $1 and principal = $2`, [id, principal]);
return res.rowCount === 1 ? "deleted" : "not_found";
}
diff --git a/oneapi-gateway/src/guardrails.ts b/oneapi-gateway/src/guardrails.ts
deleted file mode 100644
index 51d9ce6..0000000
--- a/oneapi-gateway/src/guardrails.ts
+++ /dev/null
@@ -1,160 +0,0 @@
-export type GuardrailsConfig = {
- enabled: boolean;
- blockInternalIp: boolean;
- injectionKeywords: string[];
- piiMaskEnabled: boolean;
-};
-
-function normalize(s: string): string {
- return s.toLowerCase();
-}
-
-function uniqueNonEmpty(arr: string[]): string[] {
- const out: string[] = [];
- const seen = new Set();
- for (const v of arr) {
- const t = v.trim();
- if (!t) continue;
- const k = normalize(t);
- if (seen.has(k)) continue;
- seen.add(k);
- out.push(t);
- }
- return out;
-}
-
-export function buildDefaultGuardrails(): GuardrailsConfig {
- return {
- enabled: false,
- blockInternalIp: true,
- injectionKeywords: [
- "ignore all previous instructions",
- "system prompt",
- "developer message",
- "jailbreak",
- "do anything now",
- "reveal your instructions",
- "prompt injection",
- ],
- piiMaskEnabled: true,
- };
-}
-
-function extractTextFromBody(body: unknown): string {
- if (!body || typeof body !== "object") return "";
- const b: any = body;
- const parts: string[] = [];
-
- if (typeof b.prompt === "string") parts.push(b.prompt);
- if (Array.isArray(b.messages)) {
- for (const m of b.messages) {
- if (!m || typeof m !== "object") continue;
- const c = (m as any).content;
- if (typeof c === "string") parts.push(c);
- if (Array.isArray(c)) {
- for (const item of c) {
- if (item && typeof item === "object" && typeof (item as any).text === "string") parts.push((item as any).text);
- }
- }
- }
- }
-
- return parts.join("\n");
-}
-
-function parseIpv4(s: string): number[] | undefined {
- const parts = s.split(".");
- if (parts.length !== 4) return;
- const nums = parts.map((p) => Number(p));
- if (nums.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return;
- return nums;
-}
-
-function isPrivateIpv4(o: number[]): boolean {
- const [a, b] = o;
- if (a === 10) return true;
- if (a === 127) return true;
- if (a === 0) return true;
- if (a === 169 && b === 254) return true;
- if (a === 192 && b === 168) return true;
- if (a === 172 && b >= 16 && b <= 31) return true;
- return false;
-}
-
-export function containsInternalIp(text: string): boolean {
- const t = text;
- if (!t) return false;
- const lower = normalize(t);
- if (lower.includes("localhost")) return true;
- if (lower.includes("0.0.0.0")) return true;
- if (lower.includes("::1")) return true;
- if (lower.includes("fe80:")) return true;
- if (lower.includes("fc00:") || lower.includes("fd00:")) return true;
-
- const ipv4Re = /\b(?:\d{1,3}\.){3}\d{1,3}\b/g;
- const matches = t.match(ipv4Re);
- if (!matches) return false;
- for (const m of matches) {
- const o = parseIpv4(m);
- if (o && isPrivateIpv4(o)) return true;
- }
- return false;
-}
-
-export function containsInjection(text: string, keywords: string[]): boolean {
- const k = uniqueNonEmpty(keywords);
- if (!text || !k.length) return false;
- const lower = normalize(text);
- for (const kw of k) {
- if (lower.includes(normalize(kw))) return true;
- }
- return false;
-}
-
-export type GuardrailsResult = { ok: true } | { ok: false; reason: "internal_ip" | "prompt_injection" };
-
-export function checkInputGuardrails(cfg: GuardrailsConfig, body: unknown): GuardrailsResult {
- if (!cfg.enabled) return { ok: true };
- const text = extractTextFromBody(body);
- if (cfg.blockInternalIp && containsInternalIp(text)) return { ok: false, reason: "internal_ip" };
- if (containsInjection(text, cfg.injectionKeywords)) return { ok: false, reason: "prompt_injection" };
- return { ok: true };
-}
-
-function maskKeepStartEnd(s: string, start: number, end: number, maskChar: string): string {
- if (s.length <= start + end) return s;
- return s.slice(0, start) + maskChar.repeat(Math.max(1, s.length - start - end)) + s.slice(s.length - end);
-}
-
-export function maskPiiText(text: string): string {
- if (!text) return text;
- let out = text;
- out = out.replace(/\b1[3-9]\d{9}\b/g, (m) => maskKeepStartEnd(m, 3, 4, "*"));
- out = out.replace(/\b\d{17}[\dXx]\b/g, (m) => maskKeepStartEnd(m, 4, 4, "*"));
- out = out.replace(/\b\d{3}[- ]?\d{3}[- ]?\d{4}\b/g, (m) => maskKeepStartEnd(m.replace(/[- ]/g, ""), 3, 4, "*"));
- out = out.replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, (m) => {
- const idx = m.indexOf("@");
- if (idx <= 1) return "***" + m.slice(idx);
- return m[0] + "***" + m.slice(idx - 1);
- });
- return out;
-}
-
-export function maskPiiJson(value: any): any {
- if (value === null || value === undefined) return value;
- if (typeof value === "string") return maskPiiText(value);
- if (Array.isArray(value)) return value.map(maskPiiJson);
- if (typeof value === "object") {
- const out: any = {};
- for (const [k, v] of Object.entries(value)) {
- if (k === "usage") {
- out[k] = v;
- continue;
- }
- out[k] = maskPiiJson(v);
- }
- return out;
- }
- return value;
-}
-
diff --git a/oneapi-gateway/src/index.ts b/oneapi-gateway/src/index.ts
index 9b92ed7..be62c83 100644
--- a/oneapi-gateway/src/index.ts
+++ b/oneapi-gateway/src/index.ts
@@ -1,19 +1,12 @@
import Fastify from "fastify";
import cors from "@fastify/cors";
-import fs from "node:fs";
import { loadConfig } from "./config.js";
import { createRedis } from "./redis.js";
import { createDb } from "./db.js";
-import { registry } from "./metrics.js";
-import { createOAuthVerifier, authenticate } from "./auth.js";
-import { UpstreamPool } from "./upstreams.js";
import { registerProxyRoutes } from "./proxy.js";
-import { registerDashboard } from "./dashboard.js";
-import { registerAdminApi } from "./admin.js";
+import { registerUi } from "./ui.js";
import { registerBatchRoutes } from "./batch.js";
-import { registerOpenApi } from "./openapi.js";
import { registerChatRoutes } from "./chat.js";
-import { ipAllowed } from "./net.js";
const cfg = loadConfig();
@@ -24,18 +17,10 @@ const app = Fastify({
},
bodyLimit: cfg.bodyLimitBytes ?? 10 * 1024 * 1024,
trustProxy: cfg.trustProxy,
- ...(cfg.tls ? {
- https: {
- cert: fs.readFileSync(cfg.tls.certPath),
- key: fs.readFileSync(cfg.tls.keyPath),
- },
- } : {}),
});
const redis = await createRedis(cfg.redisUrl);
const db = await createDb(cfg.databaseUrl);
-const oauth = createOAuthVerifier(cfg);
-const pool = new UpstreamPool(cfg.upstreams);
await app.register(cors, { origin: cfg.corsOrigin });
@@ -52,37 +37,41 @@ if (cfg.securityHeadersEnabled === true) {
app.get("/healthz", async () => {
return {
ok: true,
- service: "oneapi-gateway",
+ service: "easyai-gateway",
appEnv: cfg.appEnv,
- upstreams: pool.list().map((u) => u.baseUrl),
- authModes: Array.from(cfg.authModes.values()),
- cacheEnabled: cfg.cacheEnabled,
+ modelPlane: cfg.litellmBaseUrl,
+ consoleUrl: cfg.consoleUrl ?? null,
};
});
-app.get("/metrics", async (_req, reply) => {
- if (!ipAllowed((_req as any).ip, cfg.metricsAllowedCidrs)) {
- return reply.status(403).send({ error: { message: "forbidden", type: "auth_error" } });
+/**
+ * Docs and metrics are produced by LiteLLM; the gateway only forwards them so
+ * there is a single source of truth for the API surface and observability.
+ */
+async function fetchModelPlane(path: string, reply: any) {
+ try {
+ const res = await fetch(`${cfg.litellmBaseUrl}${path}`, {
+ headers: { authorization: `Bearer ${cfg.litellmMasterKey}` },
+ });
+ const contentType = res.headers.get("content-type") ?? "application/json";
+ reply.status(res.status).header("content-type", contentType);
+ return reply.send(Buffer.from(await res.arrayBuffer()));
+ } catch {
+ return reply.status(503).send({ error: { message: "model service unavailable", type: "upstream_error" } });
}
- reply.header("content-type", registry.contentType);
- return registry.metrics();
-});
+}
-await registerOpenApi(app, cfg);
-await registerDashboard(app, cfg, db);
-await registerAdminApi(app, cfg, db, redis);
+app.get("/openapi.json", async (_req, reply) => fetchModelPlane("/openapi.json", reply));
+app.get("/docs", async (_req, reply) => fetchModelPlane("/docs", reply));
+app.get("/docs/*", async (req, reply) => fetchModelPlane(req.url, reply));
+app.get("/metrics", async (_req, reply) => fetchModelPlane("/metrics", reply));
-await registerProxyRoutes(app, {
- cfg,
- redis,
- db,
- pool,
- authenticateRequest: async (headers, reqIp) => authenticate(cfg, oauth, headers, db, redis, reqIp),
-});
+await registerUi(app, cfg);
-await registerBatchRoutes(app, cfg, db, redis, async (headers) => authenticate(cfg, oauth, headers, db, redis));
+await registerProxyRoutes(app, { cfg, redis });
-await registerChatRoutes(app, cfg, oauth, db, redis);
+await registerBatchRoutes(app, cfg, db, redis);
+await registerChatRoutes(app, cfg, db);
await app.listen({ host: "0.0.0.0", port: cfg.port });
diff --git a/oneapi-gateway/src/metrics.ts b/oneapi-gateway/src/metrics.ts
deleted file mode 100644
index 801359e..0000000
--- a/oneapi-gateway/src/metrics.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import client from "prom-client";
-
-export const registry = new client.Registry();
-client.collectDefaultMetrics({ register: registry });
-
-export const httpRequestsTotal = new client.Counter({
- name: "oneapi_http_requests_total",
- help: "Total HTTP requests",
- labelNames: ["route", "method", "status"] as const,
- registers: [registry],
-});
-
-export const httpRequestDurationSeconds = new client.Histogram({
- name: "oneapi_http_request_duration_seconds",
- help: "HTTP request duration in seconds",
- labelNames: ["route", "method"] as const,
- buckets: [0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 20],
- registers: [registry],
-});
-
-export const upstreamRequestsTotal = new client.Counter({
- name: "oneapi_upstream_requests_total",
- help: "Upstream requests",
- labelNames: ["upstream", "status"] as const,
- registers: [registry],
-});
-
-export const cacheHitsTotal = new client.Counter({
- name: "oneapi_cache_hits_total",
- help: "Cache hits",
- labelNames: ["route"] as const,
- registers: [registry],
-});
-
-export const ttftDurationSeconds = new client.Histogram({
- name: "easyai_ttft_seconds",
- help: "Time to first token in seconds",
- labelNames: ["route", "model", "cached"] as const,
- buckets: [0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10],
- registers: [registry],
-});
-
-export const tpsTokensPerSecond = new client.Histogram({
- name: "easyai_tps",
- help: "Tokens per second (total_tokens / (latency - ttft))",
- labelNames: ["route", "model", "cached"] as const,
- buckets: [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000],
- registers: [registry],
-});
diff --git a/oneapi-gateway/src/net.ts b/oneapi-gateway/src/net.ts
deleted file mode 100644
index 38b057a..0000000
--- a/oneapi-gateway/src/net.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-export function normalizeIp(raw?: string): string | undefined {
- if (!raw) return;
- const ip = raw.trim();
- if (!ip) return;
- if (ip === "::1") return "127.0.0.1";
- if (ip.startsWith("::ffff:")) return ip.slice("::ffff:".length);
- return ip;
-}
-
-function ipv4ToInt(ip: string): number | undefined {
- const parts = ip.split(".");
- if (parts.length !== 4) return;
- let n = 0;
- for (const p of parts) {
- const v = Number(p);
- if (!Number.isInteger(v) || v < 0 || v > 255) return;
- n = (n << 8) | v;
- }
- return n >>> 0;
-}
-
-function ipInCidr(ip: string, cidr: string): boolean {
- const [base, maskRaw] = cidr.split("/");
- const mask = Number(maskRaw);
- if (!base || !Number.isInteger(mask) || mask < 0 || mask > 32) return false;
- const ipInt = ipv4ToInt(ip);
- const baseInt = ipv4ToInt(base);
- if (ipInt === undefined || baseInt === undefined) return false;
- const m = mask === 0 ? 0 : (0xffffffff << (32 - mask)) >>> 0;
- return (ipInt & m) === (baseInt & m);
-}
-
-export function ipAllowed(ipRaw: string | undefined, allowCidrs: string[] | null | undefined): boolean {
- if (allowCidrs === undefined || allowCidrs === null) return true;
- const ip = normalizeIp(ipRaw);
- if (!ip) return false;
- return allowCidrs.some((c) => ipInCidr(ip, c));
-}
-
-export function parseCidrAllowList(value: unknown, defaultCidrs: string[] | null | undefined): string[] | null | undefined {
- if (value === undefined) return defaultCidrs;
- if (value === "any" || value === null) return null;
- if (Array.isArray(value)) return value.map((v) => String(v).trim()).filter(Boolean);
- return defaultCidrs;
-}
diff --git a/oneapi-gateway/src/openapi.ts b/oneapi-gateway/src/openapi.ts
deleted file mode 100644
index bb2cfb4..0000000
--- a/oneapi-gateway/src/openapi.ts
+++ /dev/null
@@ -1,291 +0,0 @@
-import type { FastifyInstance } from "fastify";
-import fastifyStatic from "@fastify/static";
-import { createRequire } from "node:module";
-import path from "node:path";
-import type { Config } from "./config.js";
-import { buildGlobalNav, buildThemeInitScript } from "./ui-shell.js";
-
-const require = createRequire(import.meta.url);
-const swaggerUiAssetRoot = path.dirname(require.resolve("swagger-ui-dist/swagger-ui-bundle.js"));
-
-function buildSpec(cfg: Config) {
- const securitySchemes = {
- bearerAuth: { type: "http", scheme: "bearer", bearerFormat: "JWT or API Key" },
- apiKeyAuth: { type: "apiKey", in: "header", name: "x-api-key" },
- } as const;
-
- const security = [{ bearerAuth: [] }, { apiKeyAuth: [] }];
-
- return {
- openapi: "3.0.3",
- info: {
- title: "OneAPI Gateway",
- version: "0.1.0",
- description:
- "Public API reference for calling OpenAI-compatible model endpoints through EasyAI Gateway. It covers model listing, chat completions and asynchronous Batch API workflows. Admin, dashboard and metrics endpoints are intentionally excluded.",
- },
- servers: [{ url: "/" }],
- components: { securitySchemes },
- tags: [{ name: "OpenAI" }, { name: "Batch" }],
- paths: {
- "/v1/models": {
- get: {
- tags: ["OpenAI"],
- summary: "List models (proxied)",
- security,
- responses: {
- "200": {
- description: "OK",
- content: { "application/json": { schema: { type: "object" } } },
- },
- "401": { description: "Unauthorized" },
- },
- },
- },
- "/v1/chat/completions": {
- post: {
- tags: ["OpenAI"],
- summary: "Create chat completion (proxied)",
- description:
- "This endpoint is forwarded to upstream OpenAI-compatible services. Streaming responses use server-sent events when stream=true.",
- security,
- requestBody: {
- required: true,
- content: {
- "application/json": {
- schema: {
- type: "object",
- required: ["model", "messages"],
- properties: {
- model: { type: "string" },
- messages: {
- type: "array",
- items: {
- type: "object",
- required: ["role", "content"],
- properties: {
- role: { type: "string", enum: ["system", "user", "assistant", "tool"] },
- content: { type: "string" },
- name: { type: "string" },
- },
- },
- },
- stream: { type: "boolean", default: false },
- temperature: { type: "number" },
- top_p: { type: "number" },
- max_tokens: { type: "integer" },
- },
- },
- },
- },
- },
- responses: {
- "200": {
- description: "OK",
- content: {
- "application/json": { schema: { type: "object" } },
- "text/event-stream": { schema: { type: "string" } },
- },
- },
- "401": { description: "Unauthorized" },
- },
- },
- },
- "/v1/embeddings": {
- post: {
- tags: ["OpenAI"],
- summary: "Create embeddings (proxied)",
- security,
- requestBody: {
- required: true,
- content: {
- "application/json": {
- schema: {
- type: "object",
- required: ["model", "input"],
- properties: {
- model: { type: "string" },
- input: {
- oneOf: [
- { type: "string" },
- { type: "array", items: { type: "string" } },
- { type: "array", items: { type: "integer" } },
- { type: "array", items: { type: "array", items: { type: "integer" } } },
- ],
- },
- encoding_format: { type: "string", enum: ["float", "base64"] },
- },
- },
- },
- },
- },
- responses: {
- "200": { description: "OK", content: { "application/json": { schema: { type: "object" } } } },
- "401": { description: "Unauthorized" },
- },
- },
- },
- "/v1/batches": {
- post: {
- tags: ["Batch"],
- summary: "Create a batch job",
- security,
- requestBody: {
- required: true,
- content: {
- "application/json": {
- schema: {
- type: "object",
- required: ["requests"],
- properties: {
- requests: {
- type: "array",
- items: {
- type: "object",
- required: ["endpoint", "body"],
- properties: {
- endpoint: { type: "string", description: "Target endpoint under /v1, e.g. /v1/chat/completions" },
- body: { type: "object" },
- },
- },
- },
- },
- },
- },
- },
- },
- responses: {
- "200": { description: "OK", content: { "application/json": { schema: { type: "object" } } } },
- "401": { description: "Unauthorized" },
- "503": { description: "Batch not enabled" },
- },
- },
- },
- "/v1/batches/{batchId}": {
- get: {
- tags: ["Batch"],
- summary: "Get batch status",
- security,
- parameters: [{ name: "batchId", in: "path", required: true, schema: { type: "string" } }],
- responses: {
- "200": { description: "OK", content: { "application/json": { schema: { type: "object" } } } },
- "401": { description: "Unauthorized" },
- "403": { description: "Forbidden" },
- "404": { description: "Not found" },
- },
- },
- },
- "/v1/batches/{batchId}/output": {
- get: {
- tags: ["Batch"],
- summary: "Download batch output (JSONL)",
- security,
- parameters: [{ name: "batchId", in: "path", required: true, schema: { type: "string" } }],
- responses: {
- "200": {
- description: "OK",
- content: {
- "application/jsonl": { schema: { type: "string" } },
- "text/plain": { schema: { type: "string" } },
- },
- },
- "401": { description: "Unauthorized" },
- "403": { description: "Forbidden" },
- "404": { description: "Not found" },
- },
- },
- },
- },
- "x-oneapi": {
- authModes: Array.from(cfg.authModes.values()),
- notes: ["The gateway proxies any other /v1/* paths supported by upstreams, but only a common subset is described here."],
- },
- };
-}
-
-export async function registerOpenApi(app: FastifyInstance, cfg: Config): Promise {
- const spec = buildSpec(cfg);
-
- await app.register(fastifyStatic, {
- root: swaggerUiAssetRoot,
- prefix: "/docs/assets/",
- decorateReply: false,
- });
-
- app.get("/openapi.json", async (_req, reply) => {
- reply.header("content-type", "application/json; charset=utf-8");
- reply.header("cache-control", "no-store");
- return spec;
- });
-
- app.get("/docs/init.js", async (_req, reply) => {
- reply.header("content-type", "application/javascript; charset=utf-8");
- reply.header("cache-control", "no-store");
- return `
-window.ui = SwaggerUIBundle({
- url: "/openapi.json",
- dom_id: "#swagger-ui",
- deepLinking: true
-});
-`;
- });
-
- app.get("/docs", async (_req, reply) => {
- reply.header("content-type", "text/html; charset=utf-8");
- reply.header("cache-control", "no-store");
- return `
-
-
- ${buildThemeInitScript()}
-
-
- OneAPI Gateway API Docs
-
-
-
-
- ${buildGlobalNav({ active: "docs" })}
-
-
-
-
-`;
- });
-}
diff --git a/oneapi-gateway/src/proxy.ts b/oneapi-gateway/src/proxy.ts
index 2b61bca..6d87277 100644
--- a/oneapi-gateway/src/proxy.ts
+++ b/oneapi-gateway/src/proxy.ts
@@ -1,89 +1,15 @@
import type { FastifyInstance } from "fastify";
import { Readable } from "node:stream";
-import { cacheGet, cacheSet, decideCache } from "./cache.js";
import type { Config } from "./config.js";
-import type { Db } from "./db.js";
-import { insertUsageEvent } from "./db.js";
import type { RedisClient } from "./redis.js";
-import { checkTpm, enforceRpm, recordTpm } from "./rate_limit.js";
-import {
- httpRequestDurationSeconds,
- httpRequestsTotal,
- upstreamRequestsTotal,
- cacheHitsTotal,
- ttftDurationSeconds,
- tpsTokensPerSecond,
-} from "./metrics.js";
-import { hasScope, type AuthContext } from "./auth.js";
-import { UpstreamPool } from "./upstreams.js";
-import { checkInputGuardrails, maskPiiJson, maskPiiText } from "./guardrails.js";
+import { enforceRpm } from "./rate_limit.js";
+import { authenticate } from "./auth.js";
-function jsonBytes(v: unknown): number {
- try {
- return Buffer.byteLength(JSON.stringify(v));
- } catch {
- return 0;
- }
-}
-
-function parseModelFromBody(body: unknown): string | undefined {
- if (!body || typeof body !== "object") return;
- const m = (body as any).model;
- return typeof m === "string" ? m : undefined;
-}
-
-function updateModelInBody(body: any, newModel: string): any {
- if (body && typeof body === "object") {
- return { ...body, model: newModel };
- }
- return body;
-}
-
-function parseTokensFromResponse(body: any): { prompt?: number; completion?: number; total?: number } {
- const usage = body?.usage;
- if (!usage || typeof usage !== "object") return {};
- const p = typeof usage.prompt_tokens === "number" ? usage.prompt_tokens : undefined;
- const c = typeof usage.completion_tokens === "number" ? usage.completion_tokens : undefined;
- const t = typeof usage.total_tokens === "number" ? usage.total_tokens : undefined;
- return { prompt: p, completion: c, total: t };
-}
-
-function shouldFailover(status: number): boolean {
- return status === 429 || status === 502 || status === 503 || status === 504;
-}
-
-async function sleep(ms: number): Promise {
- if (!Number.isFinite(ms) || ms <= 0) return;
- await new Promise((resolve) => setTimeout(resolve, ms));
-}
-
-function computeTps(totalTokens: number | undefined, startMs: number, firstTokenMs: number | undefined, endMs: number): number | undefined {
- if (typeof totalTokens !== "number" || !Number.isFinite(totalTokens) || totalTokens <= 0) return;
- const baseMs = typeof firstTokenMs === "number" && Number.isFinite(firstTokenMs) ? firstTokenMs : startMs;
- const seconds = Math.max(0.001, (endMs - baseMs) / 1000);
- return totalTokens / seconds;
-}
-
-type CachedSseV1 = {
- kind: "sse_v1";
- delays_ms: number[];
- chunks: string[];
+export type ProxyDeps = {
+ cfg: Config;
+ redis: RedisClient;
};
-function parseCachedSseV1(hit: string): CachedSseV1 | undefined {
- if (!hit || hit[0] !== "{") return;
- try {
- const j = JSON.parse(hit);
- if (!j || typeof j !== "object") return;
- if (j.kind !== "sse_v1") return;
- if (!Array.isArray(j.delays_ms) || !Array.isArray(j.chunks)) return;
- if (j.delays_ms.length !== j.chunks.length) return;
- return j as CachedSseV1;
- } catch {
- return;
- }
-}
-
async function fetchWithTimeout(url: string, init: RequestInit, timeoutMs: number): Promise {
const controller = new AbortController();
const t = setTimeout(() => controller.abort(), timeoutMs);
@@ -94,642 +20,104 @@ async function fetchWithTimeout(url: string, init: RequestInit, timeoutMs: numbe
}
}
-export type ProxyDeps = {
- cfg: Config;
- redis: RedisClient;
- db: Db;
- pool: UpstreamPool;
- authenticateRequest: (headers: Record, reqIp?: string) => Promise;
-};
-
+/**
+ * Thin `/v1/*` passthrough.
+ *
+ * Model routing, retries, fallbacks, caching, guardrails, spend tracking and
+ * request logs are all handled by LiteLLM. This layer only adds EasyAI's
+ * rate limit and key delegation.
+ */
export async function registerProxyRoutes(app: FastifyInstance, deps: ProxyDeps): Promise {
app.route({
method: ["GET", "POST", "PUT", "PATCH", "DELETE"],
url: "/v1/*",
handler: async (req, reply) => {
- const route = req.url.split("?")[0] ?? req.url;
- const timer = httpRequestDurationSeconds.labels(route, req.method).startTimer();
- const startMs = Date.now();
reply.header("X-Request-Id", String((req as any).id ?? ""));
- let auth: AuthContext | undefined;
- let cached = false;
- let upstreamUsed: string | undefined;
- let status = 500;
- let error: string | undefined;
-
+ let auth;
try {
- auth = await deps.authenticateRequest(req.headers as any, (req as any).ip);
- if (!hasScope(auth, "model:invoke")) {
- status = 403;
- httpRequestsTotal.labels(route, req.method, String(status)).inc();
- timer();
- await insertUsageEvent(deps.db, {
- principal: auth.principal,
- apiKeyId: auth.apiKeyId,
- apiKeyHash: auth.apiKeyHash,
- tenantId: auth.tenantId,
- authMode: auth.authMode,
- endpoint: route,
- method: req.method,
- status,
- latencyMs: Date.now() - startMs,
- cached: false,
- error: "scope_denied",
- });
- return reply.status(403).send({ error: { message: "insufficient scope", type: "auth_error" } });
- }
- let body: unknown = req.body;
- if (body && typeof body === "object") {
- const m = (body as any).model;
- if (typeof m === "string" && deps.cfg.modelMap[m]) {
- body = { ...(body as any), model: deps.cfg.modelMap[m] };
- }
- }
-
- const gr = checkInputGuardrails(deps.cfg.guardrails, body);
- if (!gr.ok) {
- status = 400;
- httpRequestsTotal.labels(route, req.method, String(status)).inc();
- timer();
- await insertUsageEvent(deps.db, {
- principal: auth.principal,
- apiKeyId: auth.apiKeyId,
- apiKeyHash: auth.apiKeyHash,
- tenantId: auth.tenantId,
- authMode: auth.authMode,
- model: parseModelFromBody(body),
- endpoint: route,
- method: req.method,
- status,
- latencyMs: Date.now() - startMs,
- cached: false,
- error: gr.reason,
- });
- return reply.status(400).send({ error: { message: "bad request", type: "guardrails_error" } });
- }
-
- if (auth.tenantDisabled) {
- status = 403;
- httpRequestsTotal.labels(route, req.method, String(status)).inc();
- timer();
- await insertUsageEvent(deps.db, {
- principal: auth.principal,
- apiKeyId: auth.apiKeyId,
- apiKeyHash: auth.apiKeyHash,
- tenantId: auth.tenantId,
- authMode: auth.authMode,
- model: parseModelFromBody(body),
- endpoint: route,
- method: req.method,
- status,
- latencyMs: Date.now() - startMs,
- cached: false,
- error: "tenant_disabled",
- });
- return reply.status(403).send({ error: { message: "tenant disabled", type: "auth_error" } });
- }
-
- const tenantKey = auth.tenantId ? `tenant:${auth.tenantId}` : auth.principal;
- const rpm =
- typeof auth.tenantRpmLimit === "number"
- ? auth.tenantRpmLimit
- : typeof auth.rpmLimit === "number"
- ? auth.rpmLimit
- : deps.cfg.rateLimitRpm;
-
- const rl = await enforceRpm(deps.redis, tenantKey, rpm, Date.now());
- reply.header("X-RateLimit-Limit", rl.limit);
- reply.header("X-RateLimit-Remaining", rl.remaining);
- reply.header("X-RateLimit-Reset", rl.resetSeconds);
- if (!rl.ok) {
- status = 429;
- httpRequestsTotal.labels(route, req.method, String(status)).inc();
- timer();
- await insertUsageEvent(deps.db, {
- principal: auth.principal,
- apiKeyId: auth.apiKeyId,
- apiKeyHash: auth.apiKeyHash,
- tenantId: auth.tenantId,
- authMode: auth.authMode,
- model: parseModelFromBody(body),
- endpoint: route,
- method: req.method,
- status,
- latencyMs: Date.now() - startMs,
- cached: false,
- error: "rate_limited",
- });
- return reply.status(429).send({ error: { message: "rate limited", type: "rate_limit_error" } });
- }
-
- if (typeof auth.tenantTpmLimit === "number") {
- const tr = await checkTpm(deps.redis, tenantKey, auth.tenantTpmLimit, Date.now());
- if (!tr.ok) {
- status = 429;
- reply.header("X-TokenLimit-Limit", tr.limit);
- reply.header("X-TokenLimit-Used", tr.used);
- reply.header("X-TokenLimit-Reset", tr.resetSeconds);
- httpRequestsTotal.labels(route, req.method, String(status)).inc();
- timer();
- await insertUsageEvent(deps.db, {
- principal: auth.principal,
- apiKeyHash: auth.apiKeyHash,
- authMode: auth.authMode,
- model: parseModelFromBody(body),
- endpoint: route,
- method: req.method,
- status,
- latencyMs: Date.now() - startMs,
- cached: false,
- error: "token_rate_limited",
- });
- return reply.status(429).send({ error: { message: "token rate limited", type: "rate_limit_error" } });
- }
- }
-
- if (deps.cfg.cacheEnabled && req.method === "POST") {
- const decision = decideCache(route, body);
- if (decision.shouldCache) {
- const hit = await cacheGet(deps.redis, decision.cacheKey);
- if (hit) {
- cached = true;
- cacheHitsTotal.labels(route).inc();
- status = 200;
- reply.header("X-Cache", "hit");
-
- const isStream = (body as any)?.stream === true;
- const modelName = parseModelFromBody(body) ?? "unknown";
- const a = auth!;
-
- if (isStream) {
- reply.header("content-type", "text/event-stream");
- const cachedSse = parseCachedSseV1(hit);
- const hitText = cachedSse ? cachedSse.chunks.join("") : hit;
- let tokens: any = {};
- const lines = hitText.split("\n");
- for (let i = lines.length - 1; i >= 0; i--) {
- if (lines[i].startsWith("data: ") && lines[i] !== "data: [DONE]") {
- try {
- const j = JSON.parse(lines[i].slice(6));
- if (j.usage) {
- tokens = parseTokensFromResponse(j);
- break;
- }
- } catch {}
- }
- }
-
- const maxTotalMs = Number.isFinite(deps.cfg.cacheReplayMaxTotalMs) ? deps.cfg.cacheReplayMaxTotalMs : 0;
- const baseDelayMs = Number.isFinite(deps.cfg.cacheReplayChunkDelayMs) ? deps.cfg.cacheReplayChunkDelayMs : 0;
-
- let firstChunkTime: number | undefined;
- let streamError: any;
-
- async function* cachedStreamGenerator() {
- try {
- if (deps.cfg.cacheReplayMode === "original" && cachedSse) {
- const totalOriginalMs = cachedSse.delays_ms.reduce((s, v) => s + (Number.isFinite(v) ? Math.max(0, v) : 0), 0);
- const scale = maxTotalMs > 0 && totalOriginalMs > 0 ? Math.min(1, maxTotalMs / totalOriginalMs) : 1;
- for (let i = 0; i < cachedSse.chunks.length; i++) {
- const d = cachedSse.delays_ms[i];
- if (Number.isFinite(d) && d > 0) await sleep(Math.floor(d * scale));
- if (firstChunkTime === undefined) {
- firstChunkTime = Date.now();
- ttftDurationSeconds.labels(route, modelName, "true").observe((firstChunkTime - startMs) / 1000);
- }
- let chunk = cachedSse.chunks[i];
- if (deps.cfg.guardrails.enabled && deps.cfg.guardrails.piiMaskEnabled) chunk = maskPiiText(chunk);
- if (chunk) yield Buffer.from(chunk);
- }
- } else {
- const rawChunks = hitText.split("\n\n");
- const nonEmptyChunks = rawChunks.filter((c) => c && c.length);
- const delayMs =
- baseDelayMs > 0 && maxTotalMs > 0
- ? Math.min(baseDelayMs, Math.floor(maxTotalMs / Math.max(1, nonEmptyChunks.length)))
- : baseDelayMs;
- for (let i = 0; i < rawChunks.length; i++) {
- if (!rawChunks[i]) continue;
- if (firstChunkTime === undefined) {
- firstChunkTime = Date.now();
- ttftDurationSeconds.labels(route, modelName, "true").observe((firstChunkTime - startMs) / 1000);
- }
- let chunk = rawChunks[i] + "\n\n";
- if (deps.cfg.guardrails.enabled && deps.cfg.guardrails.piiMaskEnabled) chunk = maskPiiText(chunk);
- yield Buffer.from(chunk);
- if (delayMs > 0) await sleep(delayMs);
- }
- }
- } catch (err) {
- streamError = err;
- throw err;
- } finally {
- const endMs = Date.now();
- const ttftMs = firstChunkTime ? firstChunkTime - startMs : undefined;
- const tps = computeTps(tokens.total, startMs, firstChunkTime, endMs);
- if (typeof tps === "number") tpsTokensPerSecond.labels(route, modelName, "true").observe(tps);
-
- httpRequestsTotal.labels(route, req.method, String(status)).inc();
- timer();
-
- await insertUsageEvent(deps.db, {
- principal: a.principal,
- apiKeyId: a.apiKeyId,
- apiKeyHash: a.apiKeyHash,
- tenantId: a.tenantId,
- authMode: a.authMode,
- model: modelName,
- endpoint: route,
- method: req.method,
- status: streamError ? 499 : status,
- latencyMs: endMs - startMs,
- cached: true,
- ttftMs,
- tps,
- requestBytes: jsonBytes(body),
- responseBytes: Buffer.byteLength(hitText),
- promptTokens: tokens.prompt,
- completionTokens: tokens.completion,
- totalTokens: tokens.total,
- error: streamError ? "client_disconnected" : undefined,
- }).catch(console.error);
-
- if (typeof a.tenantTpmLimit === "number" && typeof tokens.total === "number" && !streamError) {
- await recordTpm(deps.redis, tenantKey, tokens.total, Date.now());
- }
- }
- }
- return reply.status(200).send(Readable.from(cachedStreamGenerator()));
- } else {
- const payload = JSON.parse(hit);
- const t = parseTokensFromResponse(payload);
- const tps = computeTps(t.total, startMs, undefined, Date.now());
- if (typeof tps === "number") tpsTokensPerSecond.labels(route, modelName, "true").observe(tps);
- const ttftMs = Date.now() - startMs;
- ttftDurationSeconds.labels(route, modelName, "true").observe(ttftMs / 1000);
- httpRequestsTotal.labels(route, req.method, String(status)).inc();
- timer();
- const safePayload = deps.cfg.guardrails.enabled && deps.cfg.guardrails.piiMaskEnabled ? maskPiiJson(payload) : payload;
- await insertUsageEvent(deps.db, {
- principal: a.principal,
- apiKeyId: a.apiKeyId,
- apiKeyHash: a.apiKeyHash,
- tenantId: a.tenantId,
- authMode: a.authMode,
- model: modelName,
- endpoint: route,
- method: req.method,
- status,
- latencyMs: Date.now() - startMs,
- cached: true,
- ttftMs,
- requestBytes: jsonBytes(body),
- responseBytes: jsonBytes(safePayload),
- promptTokens: t.prompt,
- completionTokens: t.completion,
- totalTokens: t.total,
- tps,
- });
- if (typeof a.tenantTpmLimit === "number" && typeof payload?.usage?.total_tokens === "number") {
- await recordTpm(deps.redis, tenantKey, payload.usage.total_tokens, Date.now());
- }
- return reply.status(200).send(safePayload);
- }
- }
- }
- }
-
- const originalModel = parseModelFromBody(body) ?? "unknown";
- const fallbacks = deps.cfg.fallbackMap[originalModel] ?? [];
- const modelsToTry = [originalModel, ...fallbacks];
-
- const headers: Record = {
- "content-type": "application/json",
- "x-oneapi-principal": auth.principal,
- "x-request-id": String((req as any).id ?? ""),
- };
- const tp = req.headers["traceparent"];
- if (typeof tp === "string" && tp.length) headers["traceparent"] = tp;
-
- const poolList = deps.pool.list();
- const maxUpstreamAttempts = Math.max(1, Math.min(poolList.length, 3));
-
- let lastResponse: Response | undefined;
- let lastText: string | undefined;
- let finalModelUsed = originalModel;
-
- outer: for (const currentModel of modelsToTry) {
- finalModelUsed = currentModel;
- const currentBody = updateModelInBody(body, currentModel);
- const requestBody = currentBody ? JSON.stringify(currentBody) : undefined;
-
- for (let attempt = 0; attempt < maxUpstreamAttempts; attempt++) {
- const upstream = deps.pool.pick(Date.now());
- if (!upstream) break;
- upstreamUsed = upstream.baseUrl;
-
- const upstreamUrl = `${upstream.baseUrl}${route}${req.url.includes("?") ? "?" + req.url.split("?")[1] : ""}`;
- try {
- const res = await fetchWithTimeout(
- upstreamUrl,
- {
- method: req.method,
- headers,
- body: requestBody,
- },
- deps.cfg.upstreamTimeoutMs,
- );
- status = res.status;
- upstreamRequestsTotal.labels(upstream.baseUrl, String(status)).inc();
- lastResponse = res;
- lastText = undefined;
+ auth = authenticate(deps.cfg, req.headers as any);
+ } catch {
+ return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
+ }
- if (status >= 200 && status < 300) {
- deps.pool.reportSuccess(upstream.baseUrl);
- break outer;
- }
+ const rl = await enforceRpm(deps.redis, auth.principal, deps.cfg.rateLimitRpm, Date.now());
+ reply.header("X-RateLimit-Limit", rl.limit);
+ reply.header("X-RateLimit-Remaining", rl.remaining);
+ reply.header("X-RateLimit-Reset", rl.resetSeconds);
+ if (!rl.ok) {
+ return reply.status(429).send({ error: { message: "rate limited", type: "rate_limit_error" } });
+ }
- lastText = await res.text();
+ const headers: Record = {
+ "x-request-id": String((req as any).id ?? ""),
+ };
+ const contentType = req.headers["content-type"];
+ if (typeof contentType === "string") headers["content-type"] = contentType;
+ const traceparent = req.headers["traceparent"];
+ if (typeof traceparent === "string") headers["traceparent"] = traceparent;
+
+ if (auth.useMasterKey) {
+ headers["authorization"] = `Bearer ${deps.cfg.litellmMasterKey}`;
+ } else {
+ const authorization = req.headers["authorization"];
+ if (typeof authorization === "string") headers["authorization"] = authorization;
+ const xApiKey = req.headers["x-api-key"];
+ if (typeof xApiKey === "string") headers["x-api-key"] = xApiKey;
+ }
- if (shouldFailover(status)) {
- deps.pool.reportFailure(upstream.baseUrl, Date.now());
- continue;
- }
- deps.pool.reportFailure(upstream.baseUrl, Date.now());
- break; // Not a failover-able error, stop trying this model
- } catch (e: any) {
- deps.pool.reportFailure(upstream.baseUrl, Date.now());
- error = e?.name === "AbortError" ? "upstream_timeout" : "upstream_error";
- status = 504;
- upstreamRequestsTotal.labels(upstream.baseUrl, String(status)).inc();
- continue;
- }
- }
- }
+ const hasBody = req.method !== "GET" && req.method !== "HEAD" && req.body !== undefined;
- if (!lastResponse) {
- status = 503;
- httpRequestsTotal.labels(route, req.method, String(status)).inc();
- timer();
- await insertUsageEvent(deps.db, {
- principal: auth!.principal,
- apiKeyId: auth!.apiKeyId,
- apiKeyHash: auth!.apiKeyHash,
- tenantId: auth!.tenantId,
- authMode: auth!.authMode,
- model: finalModelUsed,
- endpoint: route,
+ let res: Response;
+ try {
+ res = await fetchWithTimeout(
+ `${deps.cfg.litellmBaseUrl}${req.url}`,
+ {
method: req.method,
- status,
- latencyMs: Date.now() - startMs,
- cached,
- upstream: upstreamUsed,
- error: error ?? "no_upstream",
- });
-
- let parsedErrorMsg = "no upstream available: Failed to connect to any upstream service (e.g., litellm).";
- let parsedErrorType = "upstream_error";
- let details: any = error;
-
- if (lastText) {
- try {
- const upstreamJson = JSON.parse(lastText);
- if (upstreamJson && upstreamJson.error) {
- parsedErrorMsg = upstreamJson.error.message || parsedErrorMsg;
- parsedErrorType = upstreamJson.error.type || parsedErrorType;
- details = upstreamJson.error.details || details;
- if (status === 503 && (parsedErrorMsg.includes("Model not found") || parsedErrorMsg.includes("Upstream connection error") || parsedErrorMsg.includes("Insufficient memory") || parsedErrorMsg.includes("Upstream internal error"))) {
- // pass through upstream status codes
- if (parsedErrorMsg.includes("Model not found")) status = 404;
- if (parsedErrorMsg.includes("Upstream connection error")) status = 502;
- if (parsedErrorMsg.includes("Insufficient memory")) status = 507;
- if (parsedErrorMsg.includes("Upstream internal error")) status = 500;
- }
- }
- } catch(e) {}
- } else if (error === "upstream_timeout") {
- parsedErrorMsg = "upstream timeout: The gateway timed out waiting for the upstream service.";
- status = 504;
- }
-
- return reply.status(status).send({ error: { message: parsedErrorMsg, type: parsedErrorType, details: details } });
+ headers,
+ body: hasBody ? JSON.stringify(req.body) : undefined,
+ },
+ deps.cfg.upstreamTimeoutMs,
+ );
+ } catch (e: any) {
+ if (e?.name === "AbortError") {
+ return reply.status(504).send({ error: { message: "upstream timeout", type: "timeout_error" } });
}
+ return reply.status(502).send({ error: { message: "model service unavailable", type: "upstream_error" } });
+ }
- const responseContentType = lastResponse.headers.get("content-type") ?? "application/json";
- reply.header("content-type", responseContentType);
- reply.header("X-Cache", "miss");
- if (upstreamUsed) reply.header("X-Upstream", upstreamUsed);
- if (finalModelUsed !== originalModel) reply.header("X-Model-Fallback", finalModelUsed);
-
- const isStreamResponse = responseContentType.includes("text/event-stream");
-
- if (status >= 200 && status < 300 && isStreamResponse && lastResponse.body) {
- async function* streamGenerator() {
- const reader = lastResponse!.body!.getReader();
- const decoder = new TextDecoder("utf-8");
- let responseText = "";
- let streamError: any;
- let firstTokenTime: number | undefined;
- const chunks: string[] = [];
- const delaysMs: number[] = [];
- let lastChunkAt: number | undefined;
- const modelName = finalModelUsed;
- const piiEnabled = deps.cfg.guardrails.enabled && deps.cfg.guardrails.piiMaskEnabled;
-
- try {
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- if (value) {
- const now = Date.now();
- if (firstTokenTime === undefined) {
- firstTokenTime = now;
- const ttftMs = firstTokenTime - startMs;
- ttftDurationSeconds.labels(route, modelName, "false").observe(ttftMs / 1000);
- }
- const d = lastChunkAt === undefined ? now - startMs : now - lastChunkAt;
- delaysMs.push(d);
- lastChunkAt = now;
- let chunkStr = decoder.decode(value, { stream: true });
- if (piiEnabled) chunkStr = maskPiiText(chunkStr);
- responseText += chunkStr;
- chunks.push(chunkStr);
- yield Buffer.from(chunkStr);
- }
- }
- const finalChunk = decoder.decode();
- if (finalChunk) {
- const maskedFinal = piiEnabled ? maskPiiText(finalChunk) : finalChunk;
- responseText += maskedFinal;
- chunks.push(maskedFinal);
- delaysMs.push(0);
- yield Buffer.from(maskedFinal);
- }
- } catch (err) {
- streamError = err;
- throw err;
- } finally {
- reader.releaseLock();
- const isComplete = responseText.includes("data: [DONE]");
-
- if (isComplete && !streamError && deps.cfg.cacheEnabled && req.method === "POST") {
- const decision = decideCache(route, updateModelInBody(body, finalModelUsed));
- if (decision.shouldCache) {
- await cacheSet(
- deps.redis,
- decision.cacheKey,
- JSON.stringify({ kind: "sse_v1", delays_ms: delaysMs, chunks } satisfies CachedSseV1),
- deps.cfg.cacheTtlSeconds,
- );
- }
- }
-
- httpRequestsTotal.labels(route, req.method, String(status)).inc();
- timer();
-
- let tokens: any = {};
- const lines = responseText.split("\n");
- for (let i = lines.length - 1; i >= 0; i--) {
- if (lines[i].startsWith("data: ") && lines[i] !== "data: [DONE]") {
- try {
- const j = JSON.parse(lines[i].slice(6));
- if (j.usage) {
- tokens = parseTokensFromResponse(j);
- break;
- }
- } catch {}
- }
- }
-
- const endMs = Date.now();
- const tps = computeTps(tokens.total, startMs, firstTokenTime, endMs);
- if (typeof tps === "number") tpsTokensPerSecond.labels(route, modelName, "false").observe(tps);
-
- await insertUsageEvent(deps.db, {
- principal: auth!.principal,
- apiKeyId: auth!.apiKeyId,
- apiKeyHash: auth!.apiKeyHash,
- tenantId: auth!.tenantId,
- authMode: auth!.authMode,
- model: finalModelUsed,
- endpoint: route,
- method: req.method,
- status: streamError ? 499 : status,
- latencyMs: endMs - startMs,
- cached: false,
- upstream: upstreamUsed,
- ttftMs: firstTokenTime ? firstTokenTime - startMs : undefined,
- tps,
- requestBytes: body ? Buffer.byteLength(JSON.stringify(updateModelInBody(body, finalModelUsed))) : undefined,
- responseBytes: Buffer.byteLength(responseText),
- promptTokens: tokens.prompt,
- completionTokens: tokens.completion,
- totalTokens: tokens.total,
- error: streamError ? "client_disconnected" : undefined,
- }).catch(console.error);
- if (typeof auth!.tenantTpmLimit === "number" && typeof tokens.total === "number" && !streamError) {
- await recordTpm(deps.redis, tenantKey, tokens.total, Date.now());
- }
- }
- }
- return reply.status(status).send(Readable.from(streamGenerator()));
- } else {
- if (lastText === undefined) {
- lastText = await lastResponse.text();
- }
- const ttftMs = Date.now() - startMs;
- const modelName = finalModelUsed;
- ttftDurationSeconds.labels(route, modelName, "false").observe(ttftMs / 1000);
-
- let responseJson: any | undefined;
- if (responseContentType.includes("application/json")) {
- try {
- responseJson = JSON.parse(lastText);
- } catch {
- responseJson = undefined;
- }
- }
- if (deps.cfg.guardrails.enabled && deps.cfg.guardrails.piiMaskEnabled) {
- if (responseJson !== undefined) {
- responseJson = maskPiiJson(responseJson);
- try {
- lastText = JSON.stringify(responseJson);
- } catch {}
- } else {
- lastText = maskPiiText(lastText);
- }
- }
+ const resContentType = res.headers.get("content-type") ?? "application/json";
+ reply.status(res.status).header("content-type", resContentType);
+ for (const header of ["x-ratelimit-remaining", "x-ratelimit-limit", "retry-after", "x-litellm-model-id"]) {
+ const value = res.headers.get(header);
+ if (value) reply.header(header, value);
+ }
- if (deps.cfg.cacheEnabled && req.method === "POST" && status >= 200 && status < 300) {
- const decision = decideCache(route, updateModelInBody(body, finalModelUsed));
- if (decision.shouldCache) {
- await cacheSet(deps.redis, decision.cacheKey, lastText, deps.cfg.cacheTtlSeconds);
+ if (resContentType.includes("text/event-stream") && res.body) {
+ async function* streamGenerator() {
+ const reader = res.body!.getReader();
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (value) yield Buffer.from(value);
}
+ } finally {
+ reader.releaseLock();
}
-
- httpRequestsTotal.labels(route, req.method, String(status)).inc();
- timer();
-
- const tokens = responseJson ? parseTokensFromResponse(responseJson) : {};
- const endMs = Date.now();
- const tps = computeTps(tokens.total, startMs, undefined, endMs);
- if (typeof tps === "number") tpsTokensPerSecond.labels(route, modelName, "false").observe(tps);
- await insertUsageEvent(deps.db, {
- principal: auth!.principal,
- apiKeyId: auth!.apiKeyId,
- apiKeyHash: auth!.apiKeyHash,
- tenantId: auth!.tenantId,
- authMode: auth!.authMode,
- model: finalModelUsed,
- endpoint: route,
- method: req.method,
- status,
- latencyMs: endMs - startMs,
- cached,
- upstream: upstreamUsed,
- requestBytes: body ? Buffer.byteLength(JSON.stringify(updateModelInBody(body, finalModelUsed))) : undefined,
- responseBytes: Buffer.byteLength(lastText),
- promptTokens: tokens.prompt,
- completionTokens: tokens.completion,
- totalTokens: tokens.total,
- tps,
- error: status >= 400 ? JSON.stringify(responseJson ?? { raw: lastText }).slice(0, 2000) : undefined,
- });
- if (typeof auth!.tenantTpmLimit === "number" && typeof tokens.total === "number" && status >= 200 && status < 300) {
- await recordTpm(deps.redis, tenantKey, tokens.total, Date.now());
- }
-
- return reply.status(status).send(responseJson ?? lastText);
- }
- } catch (e: any) {
- status = status === 500 ? 401 : status;
- httpRequestsTotal.labels(route, req.method, String(status)).inc();
- timer();
-
- if (auth) {
- await insertUsageEvent(deps.db, {
- principal: auth.principal,
- apiKeyId: auth.apiKeyId,
- apiKeyHash: auth.apiKeyHash,
- tenantId: auth.tenantId,
- authMode: auth.authMode,
- model: parseModelFromBody(req.body),
- endpoint: route,
- method: req.method,
- status,
- latencyMs: Date.now() - startMs,
- cached,
- upstream: upstreamUsed,
- error: String(e?.message ?? "error").slice(0, 2000),
- });
}
+ return reply.status(res.status).send(Readable.from(streamGenerator()));
+ }
- if (status === 401) {
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
+ const text = await res.text();
+ if (resContentType.includes("application/json") && text) {
+ try {
+ return reply.status(res.status).send(JSON.parse(text));
+ } catch {
+ return reply.status(res.status).send(text);
}
- return reply.status(502).send({ error: { message: "gateway error", type: "gateway_error" } });
}
+ return reply.status(res.status).send(text);
},
});
}
diff --git a/oneapi-gateway/src/rate_limit.ts b/oneapi-gateway/src/rate_limit.ts
index d15f526..e17c32b 100644
--- a/oneapi-gateway/src/rate_limit.ts
+++ b/oneapi-gateway/src/rate_limit.ts
@@ -22,24 +22,3 @@ export async function enforceRpm(
if (count > rpm) return { ok: false, limit: rpm, remaining, resetSeconds };
return { ok: true, limit: rpm, remaining, resetSeconds };
}
-
-export type TokenLimitResult = { ok: true } | { ok: false; limit: number; used: number; resetSeconds: number };
-
-export async function checkTpm(redis: RedisClient, tenantKey: string, tpm: number, nowMs: number): Promise {
- const windowSeconds = 60;
- const bucket = Math.floor(nowMs / 1000 / windowSeconds);
- const key = `tpm:v1:${tenantKey}:${bucket}`;
- const usedStr = await redis.get(key);
- const used = usedStr ? Number(usedStr) : 0;
- const resetSeconds = windowSeconds - (Math.floor(nowMs / 1000) % windowSeconds);
- if (used > tpm) return { ok: false, limit: tpm, used, resetSeconds };
- return { ok: true };
-}
-
-export async function recordTpm(redis: RedisClient, tenantKey: string, tokens: number, nowMs: number): Promise {
- const windowSeconds = 60;
- const bucket = Math.floor(nowMs / 1000 / windowSeconds);
- const key = `tpm:v1:${tenantKey}:${bucket}`;
- const v = await redis.incrBy(key, tokens);
- if (v === tokens) await redis.expire(key, windowSeconds);
-}
diff --git a/oneapi-gateway/src/redis.ts b/oneapi-gateway/src/redis.ts
index 8b60d05..833fbb2 100644
--- a/oneapi-gateway/src/redis.ts
+++ b/oneapi-gateway/src/redis.ts
@@ -6,6 +6,6 @@ export async function createRedis(url: string): Promise {
const client = createClient({ url });
client.on("error", () => {});
await client.connect();
- return client;
+ return client as RedisClient;
}
diff --git a/oneapi-gateway/src/ui-shell.ts b/oneapi-gateway/src/ui-shell.ts
index 89b3282..2d82c53 100644
--- a/oneapi-gateway/src/ui-shell.ts
+++ b/oneapi-gateway/src/ui-shell.ts
@@ -1,21 +1,14 @@
-type NavItem = "home" | "chat" | "docs" | "dashboard";
+type NavItem = "home" | "chat" | "docs" | "console";
type GlobalNavOptions = {
active: NavItem;
- isAdmin?: boolean;
- loginState?: string;
+ consoleHref?: string;
};
function navLink(key: NavItem, active: NavItem, href: string, label: string): string {
return `${label}`;
}
-function loginNotice(loginState?: string): string {
- if (loginState === "failed") return `账号或密码错误。
`;
- if (loginState === "required") return `请先登录。
`;
- return "";
-}
-
export function buildThemeInitScript(): string {
return `
-
-
diff --git a/oneapi-gateway/chat-ui/package-lock.json b/oneapi-gateway/chat-ui/package-lock.json
deleted file mode 100644
index 21c35e8..0000000
--- a/oneapi-gateway/chat-ui/package-lock.json
+++ /dev/null
@@ -1,1390 +0,0 @@
-{
- "name": "oneapi-chat-ui",
- "version": "0.1.0",
- "lockfileVersion": 3,
- "requires": true,
- "packages": {
- "": {
- "name": "oneapi-chat-ui",
- "version": "0.1.0",
- "dependencies": {
- "react": "^19.3.1",
- "react-dom": "^19.3.1"
- },
- "devDependencies": {
- "@types/react": "^19.3.0",
- "@types/react-dom": "^19.3.0",
- "@vitejs/plugin-react": "^6.3.0",
- "typescript": "^7.0.2",
- "vite": "^8.3.8"
- }
- },
- "node_modules/@emnapi/core": {
- "version": "2.0.0-beta.2",
- "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz",
- "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==",
- "dev": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "@emnapi/wasi-threads": "2.2.0",
- "tslib": "^2.4.0"
- }
- },
- "node_modules/@emnapi/runtime": {
- "version": "2.0.0-beta.2",
- "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz",
- "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==",
- "dev": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "tslib": "^2.4.0"
- }
- },
- "node_modules/@emnapi/wasi-threads": {
- "version": "2.2.0",
- "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz",
- "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==",
- "dev": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "tslib": "^2.4.0"
- }
- },
- "node_modules/@napi-rs/wasm-runtime": {
- "version": "1.2.6",
- "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz",
- "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==",
- "dev": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "@tybys/wasm-util": "^0.10.3"
- },
- "engines": {
- "node": "^20.19.0 || ^22.13.0 || >=23.5.0"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/Brooooooklyn"
- },
- "peerDependencies": {
- "@emnapi/core": "^1.7.1 || 2.0.0-beta.2",
- "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2"
- }
- },
- "node_modules/@oxc-project/types": {
- "version": "0.156.0",
- "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz",
- "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==",
- "dev": true,
- "license": "MIT",
- "funding": {
- "url": "https://github.com/sponsors/oxc-project"
- }
- },
- "node_modules/@rolldown/binding-android-arm-eabi": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz",
- "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==",
- "cpu": [
- "arm"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "android"
- ],
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- }
- },
- "node_modules/@rolldown/binding-android-arm64": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz",
- "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "android"
- ],
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- }
- },
- "node_modules/@rolldown/binding-darwin-arm64": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz",
- "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- }
- },
- "node_modules/@rolldown/binding-darwin-x64": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz",
- "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- }
- },
- "node_modules/@rolldown/binding-freebsd-x64": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz",
- "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "freebsd"
- ],
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- }
- },
- "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz",
- "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==",
- "cpu": [
- "arm"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- }
- },
- "node_modules/@rolldown/binding-linux-arm64-gnu": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz",
- "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- }
- },
- "node_modules/@rolldown/binding-linux-arm64-musl": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz",
- "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "libc": [
- "musl"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- }
- },
- "node_modules/@rolldown/binding-linux-ppc64-gnu": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz",
- "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==",
- "cpu": [
- "ppc64"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- }
- },
- "node_modules/@rolldown/binding-linux-s390x-gnu": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz",
- "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==",
- "cpu": [
- "s390x"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- }
- },
- "node_modules/@rolldown/binding-linux-x64-gnu": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz",
- "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- }
- },
- "node_modules/@rolldown/binding-linux-x64-musl": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz",
- "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "libc": [
- "musl"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- }
- },
- "node_modules/@rolldown/binding-openharmony-arm64": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz",
- "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "openharmony"
- ],
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- }
- },
- "node_modules/@rolldown/binding-wasm32-wasi": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz",
- "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==",
- "cpu": [
- "wasm32"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "@emnapi/core": "2.0.0-beta.2",
- "@emnapi/runtime": "2.0.0-beta.2",
- "@napi-rs/wasm-runtime": "1.2.6"
- },
- "engines": {
- "node": "^20.19.0 || ^22.13.0 || >=23.5.0"
- }
- },
- "node_modules/@rolldown/binding-win32-arm64-msvc": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz",
- "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- }
- },
- "node_modules/@rolldown/binding-win32-x64-msvc": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz",
- "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- }
- },
- "node_modules/@rolldown/pluginutils": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz",
- "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==",
- "dev": true,
- "license": "MIT"
- },
- "node_modules/@tybys/wasm-util": {
- "version": "0.10.5",
- "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz",
- "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==",
- "dev": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "tslib": "^2.4.0"
- }
- },
- "node_modules/@types/react": {
- "version": "19.3.0",
- "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
- "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "csstype": "^3.2.2"
- }
- },
- "node_modules/@types/react-dom": {
- "version": "19.3.0",
- "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz",
- "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==",
- "dev": true,
- "license": "MIT",
- "peerDependencies": {
- "@types/react": "^19.3.0"
- }
- },
- "node_modules/@typescript/typescript-aix-ppc64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
- "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
- "cpu": [
- "ppc64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "aix"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-darwin-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
- "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-darwin-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
- "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-freebsd-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
- "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "freebsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-freebsd-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
- "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "freebsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-arm": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
- "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
- "cpu": [
- "arm"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
- "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-loong64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
- "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
- "cpu": [
- "loong64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-mips64el": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
- "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
- "cpu": [
- "mips64el"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-ppc64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
- "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
- "cpu": [
- "ppc64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-riscv64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
- "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
- "cpu": [
- "riscv64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-s390x": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
- "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
- "cpu": [
- "s390x"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
- "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-netbsd-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
- "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "netbsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-netbsd-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
- "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "netbsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-openbsd-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
- "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "openbsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-openbsd-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
- "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "openbsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-sunos-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
- "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "sunos"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-win32-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
- "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-win32-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
- "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@vitejs/plugin-react": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.3.0.tgz",
- "integrity": "sha512-H9E955aVvD2F4zNHCw4eIZbIfF6xKldlh7MNu+hSU7xwQzh65lI/N+CJWqmfhi0PEjDXIt/H7T7J/4wU63KJiw==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@rolldown/pluginutils": "^1.0.1"
- },
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- },
- "peerDependencies": {
- "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0 || ^0.3.0",
- "babel-plugin-react-compiler": "^1.0.0",
- "oxc-transform-react": ">=0.152.0 <0.157.0",
- "vite": "^8.0.0"
- },
- "peerDependenciesMeta": {
- "@rolldown/plugin-babel": {
- "optional": true
- },
- "babel-plugin-react-compiler": {
- "optional": true
- },
- "oxc-transform-react": {
- "optional": true
- }
- }
- },
- "node_modules/csstype": {
- "version": "3.2.3",
- "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
- "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
- "dev": true,
- "license": "MIT"
- },
- "node_modules/detect-libc": {
- "version": "2.1.2",
- "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
- "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
- "dev": true,
- "license": "Apache-2.0",
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/fdir": {
- "version": "6.5.0",
- "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
- "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=12.0.0"
- },
- "peerDependencies": {
- "picomatch": "^3 || ^4"
- },
- "peerDependenciesMeta": {
- "picomatch": {
- "optional": true
- }
- }
- },
- "node_modules/fsevents": {
- "version": "2.3.3",
- "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
- "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
- "dev": true,
- "hasInstallScript": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
- }
- },
- "node_modules/lightningcss": {
- "version": "1.33.0",
- "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
- "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
- "dev": true,
- "license": "MPL-2.0",
- "dependencies": {
- "detect-libc": "^2.0.3"
- },
- "engines": {
- "node": ">= 12.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/parcel"
- },
- "optionalDependencies": {
- "lightningcss-android-arm64": "1.33.0",
- "lightningcss-darwin-arm64": "1.33.0",
- "lightningcss-darwin-x64": "1.33.0",
- "lightningcss-freebsd-x64": "1.33.0",
- "lightningcss-linux-arm-gnueabihf": "1.33.0",
- "lightningcss-linux-arm64-gnu": "1.33.0",
- "lightningcss-linux-arm64-musl": "1.33.0",
- "lightningcss-linux-x64-gnu": "1.33.0",
- "lightningcss-linux-x64-musl": "1.33.0",
- "lightningcss-win32-arm64-msvc": "1.33.0",
- "lightningcss-win32-x64-msvc": "1.33.0"
- }
- },
- "node_modules/lightningcss-android-arm64": {
- "version": "1.33.0",
- "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",
- "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MPL-2.0",
- "optional": true,
- "os": [
- "android"
- ],
- "engines": {
- "node": ">= 12.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/parcel"
- }
- },
- "node_modules/lightningcss-darwin-arm64": {
- "version": "1.33.0",
- "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",
- "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MPL-2.0",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">= 12.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/parcel"
- }
- },
- "node_modules/lightningcss-darwin-x64": {
- "version": "1.33.0",
- "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",
- "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MPL-2.0",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">= 12.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/parcel"
- }
- },
- "node_modules/lightningcss-freebsd-x64": {
- "version": "1.33.0",
- "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",
- "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MPL-2.0",
- "optional": true,
- "os": [
- "freebsd"
- ],
- "engines": {
- "node": ">= 12.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/parcel"
- }
- },
- "node_modules/lightningcss-linux-arm-gnueabihf": {
- "version": "1.33.0",
- "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",
- "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",
- "cpu": [
- "arm"
- ],
- "dev": true,
- "license": "MPL-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 12.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/parcel"
- }
- },
- "node_modules/lightningcss-linux-arm64-gnu": {
- "version": "1.33.0",
- "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",
- "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "MPL-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 12.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/parcel"
- }
- },
- "node_modules/lightningcss-linux-arm64-musl": {
- "version": "1.33.0",
- "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",
- "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "libc": [
- "musl"
- ],
- "license": "MPL-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 12.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/parcel"
- }
- },
- "node_modules/lightningcss-linux-x64-gnu": {
- "version": "1.33.0",
- "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",
- "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "MPL-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 12.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/parcel"
- }
- },
- "node_modules/lightningcss-linux-x64-musl": {
- "version": "1.33.0",
- "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",
- "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "libc": [
- "musl"
- ],
- "license": "MPL-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 12.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/parcel"
- }
- },
- "node_modules/lightningcss-win32-arm64-msvc": {
- "version": "1.33.0",
- "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",
- "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MPL-2.0",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">= 12.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/parcel"
- }
- },
- "node_modules/lightningcss-win32-x64-msvc": {
- "version": "1.33.0",
- "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",
- "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MPL-2.0",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">= 12.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/parcel"
- }
- },
- "node_modules/nanoid": {
- "version": "3.3.20",
- "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
- "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
- "dev": true,
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/ai"
- }
- ],
- "license": "MIT",
- "bin": {
- "nanoid": "bin/nanoid.cjs"
- },
- "engines": {
- "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
- }
- },
- "node_modules/picocolors": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
- "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
- "dev": true,
- "license": "ISC"
- },
- "node_modules/picomatch": {
- "version": "4.0.7",
- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
- "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://github.com/sponsors/jonschlinkert"
- }
- },
- "node_modules/postcss": {
- "version": "8.5.33",
- "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz",
- "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==",
- "dev": true,
- "funding": [
- {
- "type": "opencollective",
- "url": "https://opencollective.com/postcss/"
- },
- {
- "type": "tidelift",
- "url": "https://tidelift.com/funding/github/npm/postcss"
- },
- {
- "type": "github",
- "url": "https://github.com/sponsors/ai"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "nanoid": "^3.3.20",
- "picocolors": "^1.1.1",
- "source-map-js": "^1.2.2"
- },
- "engines": {
- "node": "^10 || ^12 || >=14"
- }
- },
- "node_modules/react": {
- "version": "19.3.1",
- "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz",
- "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==",
- "license": "MIT",
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/react-dom": {
- "version": "19.3.1",
- "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz",
- "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==",
- "license": "MIT",
- "dependencies": {
- "scheduler": "^0.28.0"
- },
- "peerDependencies": {
- "react": "^19.3.1"
- }
- },
- "node_modules/rolldown": {
- "version": "1.2.19",
- "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz",
- "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@oxc-project/types": "=0.156.0",
- "@rolldown/pluginutils": "^1.0.0"
- },
- "bin": {
- "rolldown": "bin/cli.mjs"
- },
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- },
- "optionalDependencies": {
- "@rolldown/binding-android-arm-eabi": "1.2.19",
- "@rolldown/binding-android-arm64": "1.2.19",
- "@rolldown/binding-darwin-arm64": "1.2.19",
- "@rolldown/binding-darwin-x64": "1.2.19",
- "@rolldown/binding-freebsd-x64": "1.2.19",
- "@rolldown/binding-linux-arm-gnueabihf": "1.2.19",
- "@rolldown/binding-linux-arm64-gnu": "1.2.19",
- "@rolldown/binding-linux-arm64-musl": "1.2.19",
- "@rolldown/binding-linux-ppc64-gnu": "1.2.19",
- "@rolldown/binding-linux-s390x-gnu": "1.2.19",
- "@rolldown/binding-linux-x64-gnu": "1.2.19",
- "@rolldown/binding-linux-x64-musl": "1.2.19",
- "@rolldown/binding-openharmony-arm64": "1.2.19",
- "@rolldown/binding-wasm32-wasi": "1.2.19",
- "@rolldown/binding-win32-arm64-msvc": "1.2.19",
- "@rolldown/binding-win32-x64-msvc": "1.2.19"
- }
- },
- "node_modules/scheduler": {
- "version": "0.28.0",
- "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",
- "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==",
- "license": "MIT"
- },
- "node_modules/source-map-js": {
- "version": "1.2.4",
- "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz",
- "integrity": "sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==",
- "dev": true,
- "license": "BSD-3-Clause",
- "engines": {
- "node": ">=6.0.0"
- }
- },
- "node_modules/tinyglobby": {
- "version": "0.2.17",
- "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
- "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "fdir": "^6.5.0",
- "picomatch": "^4.0.4"
- },
- "engines": {
- "node": ">=12.0.0"
- },
- "funding": {
- "url": "https://github.com/sponsors/SuperchupuDev"
- }
- },
- "node_modules/tslib": {
- "version": "2.9.1",
- "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",
- "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",
- "dev": true,
- "license": "0BSD",
- "optional": true
- },
- "node_modules/typescript": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
- "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
- "dev": true,
- "license": "Apache-2.0",
- "bin": {
- "tsc": "bin/tsc"
- },
- "engines": {
- "node": ">=16.20.0"
- },
- "optionalDependencies": {
- "@typescript/typescript-aix-ppc64": "7.0.2",
- "@typescript/typescript-darwin-arm64": "7.0.2",
- "@typescript/typescript-darwin-x64": "7.0.2",
- "@typescript/typescript-freebsd-arm64": "7.0.2",
- "@typescript/typescript-freebsd-x64": "7.0.2",
- "@typescript/typescript-linux-arm": "7.0.2",
- "@typescript/typescript-linux-arm64": "7.0.2",
- "@typescript/typescript-linux-loong64": "7.0.2",
- "@typescript/typescript-linux-mips64el": "7.0.2",
- "@typescript/typescript-linux-ppc64": "7.0.2",
- "@typescript/typescript-linux-riscv64": "7.0.2",
- "@typescript/typescript-linux-s390x": "7.0.2",
- "@typescript/typescript-linux-x64": "7.0.2",
- "@typescript/typescript-netbsd-arm64": "7.0.2",
- "@typescript/typescript-netbsd-x64": "7.0.2",
- "@typescript/typescript-openbsd-arm64": "7.0.2",
- "@typescript/typescript-openbsd-x64": "7.0.2",
- "@typescript/typescript-sunos-x64": "7.0.2",
- "@typescript/typescript-win32-arm64": "7.0.2",
- "@typescript/typescript-win32-x64": "7.0.2"
- }
- },
- "node_modules/vite": {
- "version": "8.3.8",
- "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz",
- "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "lightningcss": "^1.33.0",
- "picomatch": "^4.0.7",
- "postcss": "^8.5.32",
- "rolldown": "~1.2.18",
- "tinyglobby": "^0.2.17"
- },
- "bin": {
- "vite": "bin/vite.js"
- },
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- },
- "funding": {
- "url": "https://github.com/vitejs/vite?sponsor=1"
- },
- "optionalDependencies": {
- "fsevents": "~2.3.3"
- },
- "peerDependencies": {
- "@types/node": "^20.19.0 || >=22.12.0",
- "@vitejs/devtools": "^0.7.1 || ^0.8.0",
- "esbuild": "^0.27.0 || ^0.28.0",
- "jiti": ">=1.21.0",
- "less": "^4.0.0",
- "sass": "^1.70.0",
- "sass-embedded": "^1.70.0",
- "stylus": ">=0.54.8",
- "sugarss": "^5.0.0",
- "terser": "^5.16.0",
- "tsx": "^4.8.1",
- "yaml": "^2.4.2"
- },
- "peerDependenciesMeta": {
- "@types/node": {
- "optional": true
- },
- "@vitejs/devtools": {
- "optional": true
- },
- "esbuild": {
- "optional": true
- },
- "jiti": {
- "optional": true
- },
- "less": {
- "optional": true
- },
- "sass": {
- "optional": true
- },
- "sass-embedded": {
- "optional": true
- },
- "stylus": {
- "optional": true
- },
- "sugarss": {
- "optional": true
- },
- "terser": {
- "optional": true
- },
- "tsx": {
- "optional": true
- },
- "yaml": {
- "optional": true
- }
- }
- }
- }
-}
diff --git a/oneapi-gateway/chat-ui/package.json b/oneapi-gateway/chat-ui/package.json
deleted file mode 100644
index 95576d3..0000000
--- a/oneapi-gateway/chat-ui/package.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "name": "oneapi-chat-ui",
- "private": true,
- "version": "0.1.0",
- "type": "module",
- "scripts": {
- "dev": "vite --host 0.0.0.0 --port 5174",
- "build": "tsc -p tsconfig.json --noEmit && vite build"
- },
- "dependencies": {
- "react": "^19.3.1",
- "react-dom": "^19.3.1"
- },
- "devDependencies": {
- "@types/react": "^19.3.0",
- "@types/react-dom": "^19.3.0",
- "@vitejs/plugin-react": "^6.3.0",
- "typescript": "^7.0.2",
- "vite": "^8.3.8"
- }
-}
diff --git a/oneapi-gateway/chat-ui/src/main.tsx b/oneapi-gateway/chat-ui/src/main.tsx
deleted file mode 100644
index 2708c9c..0000000
--- a/oneapi-gateway/chat-ui/src/main.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-import React from "react";
-import { createRoot } from "react-dom/client";
-import { App } from "./ui/App";
-import { ThemeProvider } from "@easyai/ui";
-import "@easyai/ui/styles.css";
-
-createRoot(document.getElementById("root")!).render(
-
-
-
-
- ,
-);
diff --git a/oneapi-gateway/chat-ui/src/ui/App.tsx b/oneapi-gateway/chat-ui/src/ui/App.tsx
deleted file mode 100644
index e3d9e00..0000000
--- a/oneapi-gateway/chat-ui/src/ui/App.tsx
+++ /dev/null
@@ -1,1328 +0,0 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { ActionBar, Button, Center, Field, Grid, Input, Inline, Select, Section, Stack, TextArea } from "@easyai/ui";
-import { createClientId } from "./id";
-import { shouldApplyLoadedMessages } from "./messageLoad";
-import { parseSseDataEvents } from "./stream";
-
-type Conversation = {
- id: string;
- title: string;
- message_count: number;
- created_at: string;
- updated_at: string;
-};
-
-type Message = {
- id: string;
- conversation_id: string;
- role: string;
- content: string;
- model: string | null;
- created_at: string;
-};
-
-type ViewMode = "chat" | "test";
-
-type HealthStatus = {
- ok: boolean;
- service: string;
- appEnv?: string;
- modelPlane?: string;
- consoleUrl?: string | null;
-};
-
-const LS_KEY = "easyai_chat_api_key";
-
-function getStoredKey(): string | null {
- try {
- return localStorage.getItem(LS_KEY);
- } catch {
- return null;
- }
-}
-
-function setStoredKey(k: string) {
- try {
- localStorage.setItem(LS_KEY, k);
- } catch {}
-}
-
-function clearStoredKey() {
- try {
- localStorage.removeItem(LS_KEY);
- } catch {}
-}
-
-function authHeaders(): Record {
- const k = getStoredKey();
- if (!k) return {};
- return { authorization: `Bearer ${k}` };
-}
-
-async function fetchJson(url: string, init?: RequestInit) {
- const headers: Record = {
- ...authHeaders(),
- accept: "application/json",
- };
- if (init?.method !== "GET" && init?.body !== undefined && init?.body !== null) {
- headers["content-type"] = "application/json";
- }
-
- const res = await fetch(url, {
- ...init,
- headers: {
- ...(init?.headers ?? {}),
- ...headers,
- },
- });
- const text = await res.text();
- if (!res.ok) {
- let msg = text || String(res.status);
- try {
- const j = JSON.parse(text);
- msg = j.error || msg;
- } catch {}
- throw new Error(msg);
- }
- return text ? JSON.parse(text) : null;
-}
-
-function truncate(s: string, n: number): string {
- if (s.length <= n) return s;
- return s.slice(0, n - 1) + "…";
-}
-
-function cx(...parts: Array) {
- return parts.filter(Boolean).join(" ");
-}
-
-function formatTime(s: string): string {
- const d = new Date(s);
- if (Number.isNaN(d.getTime())) return s;
- const now = new Date();
- const diffMs = now.getTime() - d.getTime();
- const diffMin = Math.floor(diffMs / 60000);
- if (diffMin < 1) return "刚刚";
- if (diffMin < 60) return `${diffMin} 分钟前`;
- const diffHour = Math.floor(diffMin / 60);
- if (diffHour < 24) return `${diffHour} 小时前`;
- const diffDay = Math.floor(diffHour / 24);
- if (diffDay < 7) return `${diffDay} 天前`;
- return d.toISOString().replace("T", " ").slice(0, 16);
-}
-
-function extractAssistantText(payload: any): string {
- const content = payload?.choices?.[0]?.message?.content;
- if (typeof content === "string") return content;
- if (Array.isArray(content)) {
- return content
- .map((part) => {
- if (typeof part === "string") return part;
- if (typeof part?.text === "string") return part.text;
- try {
- return JSON.stringify(part);
- } catch {
- return String(part ?? "");
- }
- })
- .join("\n");
- }
- try {
- return JSON.stringify(payload, null, 2);
- } catch {
- return String(payload ?? "");
- }
-}
-
-function formatUsage(payload: any): string {
- const usage = payload?.usage;
- if (!usage || typeof usage !== "object") return "";
- const prompt = typeof usage.prompt_tokens === "number" ? usage.prompt_tokens : "-";
- const completion = typeof usage.completion_tokens === "number" ? usage.completion_tokens : "-";
- const total = typeof usage.total_tokens === "number" ? usage.total_tokens : "-";
- return `Prompt ${prompt} / Completion ${completion} / Total ${total}`;
-}
-
-function extractStreamChunkText(payload: any): string {
- const delta = payload?.choices?.[0]?.delta;
- if (typeof delta?.content === "string") return delta.content;
- if (Array.isArray(delta?.content)) {
- return delta.content
- .map((part: any) => {
- if (typeof part === "string") return part;
- if (typeof part?.text === "string") return part.text;
- return "";
- })
- .join("");
- }
- const message = payload?.choices?.[0]?.message;
- if (typeof message?.content === "string") return message.content;
- return "";
-}
-
-function getDeploymentLabel(appEnv?: string | null): { text: string; tone: string } {
- if (appEnv === undefined) return { text: "环境检测中", tone: "#6b7280" };
- if (appEnv === null) return { text: "环境未知", tone: "#6b7280" };
- return appEnv === "production"
- ? { text: "线上环境", tone: "#137333" }
- : { text: "开发环境", tone: "#b45309" };
-}
-
-function DeploymentBadge(props: { appEnv?: string }) {
- const { text, tone } = getDeploymentLabel(props.appEnv);
- return (
-
-
- {text}
-
- );
-}
-
-export function App() {
- const [apiKey, setApiKey] = useState(getStoredKey);
- const [keyInput, setKeyInput] = useState(getStoredKey() ?? "");
- const [loginError, setLoginError] = useState("");
- const [viewMode, setViewMode] = useState("chat");
- const [conversations, setConversations] = useState([]);
- const [currentId, setCurrentId] = useState(null);
- const [messages, setMessages] = useState([]);
- const [models, setModels] = useState([]);
- const [selectedModel, setSelectedModel] = useState("");
- const [inputText, setInputText] = useState("");
- const [isStreaming, setIsStreaming] = useState(false);
- const [streamContent, setStreamContent] = useState("");
- const [status, setStatus] = useState("");
- const [showSettings, setShowSettings] = useState(false);
- const [temperature, setTemperature] = useState("0.7");
- const [maxTokens, setMaxTokens] = useState("2048");
- const [testSystemPrompt, setTestSystemPrompt] = useState("你是一个有帮助的 AI 助手。");
- const [testUserPrompt, setTestUserPrompt] = useState("");
- const [testStream, setTestStream] = useState(false);
- const [testLoading, setTestLoading] = useState(false);
- const [testResult, setTestResult] = useState("");
- const [testRaw, setTestRaw] = useState("");
- const [testUsage, setTestUsage] = useState("");
- const [testLatencyMs, setTestLatencyMs] = useState(null);
- const [health, setHealth] = useState(undefined);
- const [convLoading, setConvLoading] = useState(false);
- const [renamingId, setRenamingId] = useState(null);
- const [renameInput, setRenameInput] = useState("");
- const [pendingDelete, setPendingDelete] = useState<{ id: string; title: string } | null>(null);
-
- const abortRef = useRef(null);
- const testAbortRef = useRef(null);
- const messagesScrollRef = useRef(null);
- const messagesEndRef = useRef(null);
- const inputRef = useRef(null);
- const currentIdRef = useRef(null);
- const isStreamingRef = useRef(false);
- const messageLoadSeqRef = useRef(0);
-
- const currentConv = useMemo(
- () => conversations.find((c) => c.id === currentId) ?? null,
- [conversations, currentId],
- );
-
- const scrollToBottom = useCallback(() => {
- const panel = messagesScrollRef.current;
- if (!panel) return;
- panel.scrollTo({ top: panel.scrollHeight, behavior: "auto" });
- }, []);
-
- useEffect(() => {
- scrollToBottom();
- }, [messages, streamContent, scrollToBottom]);
-
- useEffect(() => {
- currentIdRef.current = currentId;
- }, [currentId]);
-
- useEffect(() => {
- isStreamingRef.current = isStreaming;
- }, [isStreaming]);
-
- const loadModels = useCallback(async () => {
- try {
- const data = await fetchJson("/chat-api/models");
- const list = Array.isArray(data?.data)
- ? (data.data as any[]).map((m) => String(m?.id ?? "").trim()).filter(Boolean)
- : [];
- setModels(list);
- if (list.length > 0 && !selectedModel) setSelectedModel(list[0]!);
- } catch {}
- }, []);
-
- const loadHealth = useCallback(async () => {
- try {
- const res = await fetch("/healthz", { headers: { accept: "application/json" } });
- const data = await res.json();
- if (!res.ok) throw new Error(String(res.status));
- setHealth(data as HealthStatus);
- } catch {
- setHealth(null);
- }
- }, []);
-
- const loadConversations = useCallback(async () => {
- setConvLoading(true);
- try {
- const data = await fetchJson("/chat-api/conversations");
- setConversations(data?.conversations ?? []);
- } catch (e: any) {
- if (e?.message?.includes("unauthorized")) {
- setLoginError("登录已失效,请重新输入 API Key。");
- handleLogout();
- return;
- }
- } finally {
- setConvLoading(false);
- }
- }, []);
-
- const loadMessages = useCallback(async (convId: string) => {
- const seq = ++messageLoadSeqRef.current;
- try {
- const data = await fetchJson(`/chat-api/conversations/${encodeURIComponent(convId)}/messages`);
- if (!shouldApplyLoadedMessages({
- requestSeq: seq,
- currentSeq: messageLoadSeqRef.current,
- requestedConversationId: convId,
- currentConversationId: currentIdRef.current,
- isStreaming: isStreamingRef.current,
- })) return;
- setMessages(data?.messages ?? []);
- } catch {}
- }, []);
-
- const handleLogin = useCallback(async () => {
- const key = keyInput.trim();
- if (!key) return;
- setLoginError("");
- try {
- const res = await fetch("/chat-api/models", {
- headers: {
- authorization: `Bearer ${key}`,
- accept: "application/json",
- },
- });
- if (!res.ok) throw new Error("invalid_api_key");
- setStoredKey(key);
- setApiKey(key);
- } catch {
- setLoginError("API Key 无效或服务未就绪,请检查后重试。");
- }
- }, [keyInput]);
-
- function handleLogout() {
- clearStoredKey();
- setApiKey(null);
- setKeyInput("");
- setViewMode("chat");
- setConversations([]);
- setCurrentId(null);
- setMessages([]);
- setIsStreaming(false);
- setStreamContent("");
- setTestLoading(false);
- setTestResult("");
- setTestRaw("");
- setTestUsage("");
- setTestLatencyMs(null);
- setTestUserPrompt("");
- testAbortRef.current?.abort();
- testAbortRef.current = null;
- abortRef.current?.abort();
- abortRef.current = null;
- }
-
- const handleNewConversation = useCallback(async () => {
- if (isStreaming) return;
- try {
- const data = await fetchJson("/chat-api/conversations", { method: "POST" });
- const id = data?.id;
- if (id) {
- setCurrentId(id);
- setMessages([]);
- setStreamContent("");
- await loadConversations();
- }
- } catch (e: any) {
- setStatus(e?.message ?? "创建失败");
- }
- }, [isStreaming, loadConversations]);
-
- const handleSelectConversation = useCallback(
- async (id: string) => {
- if (isStreaming) return;
- setCurrentId(id);
- setMessages([]);
- setStreamContent("");
- await loadMessages(id);
- },
- [isStreaming, loadMessages],
- );
-
- const handleDeleteConversation = useCallback(
- async (id: string) => {
- if (isStreaming) return;
- try {
- await fetchJson(`/chat-api/conversations/${encodeURIComponent(id)}`, { method: "DELETE" });
- setConversations((prev) => prev.filter((c) => c.id !== id));
- if (currentId === id) {
- setCurrentId(null);
- setMessages([]);
- setStreamContent("");
- setStatus("会话已删除");
- }
- await loadConversations();
- } catch (e: any) {
- setStatus(e?.message ?? "删除失败");
- }
- },
- [isStreaming, currentId, loadConversations],
- );
-
- const handleCloseConversation = useCallback(() => {
- if (isStreaming) return;
- setCurrentId(null);
- setMessages([]);
- setStreamContent("");
- setStatus("");
- }, [isStreaming]);
-
- const requestDeleteConversation = useCallback(
- (id: string, title?: string) => {
- if (isStreaming) return;
- setPendingDelete({ id, title: title?.trim() || "新对话" });
- },
- [isStreaming],
- );
-
- const confirmDeleteConversation = useCallback(async () => {
- const target = pendingDelete;
- if (!target) return;
- setPendingDelete(null);
- await handleDeleteConversation(target.id);
- }, [pendingDelete, handleDeleteConversation]);
-
- useEffect(() => {
- if (apiKey) {
- loadConversations();
- loadModels();
- }
- }, [apiKey, loadConversations, loadModels]);
-
- useEffect(() => {
- loadHealth();
- }, [loadHealth]);
-
- useEffect(() => {
- if (currentId) {
- loadMessages(currentId);
- } else {
- setMessages([]);
- }
- }, [currentId, loadMessages]);
-
- useEffect(() => {
- return () => {
- abortRef.current?.abort();
- abortRef.current = null;
- testAbortRef.current?.abort();
- testAbortRef.current = null;
- };
- }, []);
-
- const handleSend = useCallback(async () => {
- const msg = inputText.trim();
- if (!msg || isStreaming || !selectedModel) return;
-
- setInputText("");
- messageLoadSeqRef.current += 1;
- setIsStreaming(true);
- setStreamContent("");
- setStatus("发送中...");
-
- let activeConvId: string;
- if (!currentId) {
- try {
- const created = await fetchJson("/chat-api/conversations", { method: "POST" });
- const createdId = created?.id;
- if (!createdId || typeof createdId !== "string") throw new Error("创建会话失败");
- activeConvId = createdId;
- setCurrentId(activeConvId);
- await loadConversations();
- } catch (e: any) {
- setIsStreaming(false);
- setStatus(e?.message ?? "创建会话失败");
- return;
- }
- } else {
- activeConvId = currentId;
- }
-
- const userMsg: Message = {
- id: createClientId(),
- conversation_id: activeConvId,
- role: "user",
- content: msg,
- model: selectedModel,
- created_at: new Date().toISOString(),
- };
- setMessages((prev) => [...prev, userMsg]);
-
- const controller = new AbortController();
- abortRef.current = controller;
-
- try {
- const body = JSON.stringify({
- model: selectedModel,
- message: msg,
- temperature: Number(temperature) || undefined,
- max_tokens: Number(maxTokens) || undefined,
- stream: true,
- });
-
- const res = await fetch(`/chat-api/conversations/${encodeURIComponent(activeConvId)}/chat`, {
- method: "POST",
- headers: {
- ...authHeaders(),
- "content-type": "application/json",
- accept: "text/event-stream",
- },
- body,
- signal: controller.signal,
- });
-
- if (!res.ok) {
- const text = await res.text();
- throw new Error(text || String(res.status));
- }
-
- const reader = res.body?.getReader();
- if (!reader) throw new Error("stream not available");
-
- const decoder = new TextDecoder();
- let buffer = "";
- let output = "";
- let doneSeen = false;
-
- while (!doneSeen) {
- const { done, value } = await reader.read();
- if (done) break;
- const chunk = decoder.decode(value, { stream: true });
- buffer += chunk;
-
- const parsedEvents = parseSseDataEvents(buffer);
- buffer = parsedEvents.rest;
- for (const dataText of parsedEvents.dataEvents) {
- if (dataText === "[DONE]") {
- doneSeen = true;
- break;
- }
- let parsed: any;
- try {
- parsed = JSON.parse(dataText);
- } catch {
- continue;
- }
- if (parsed?.error?.message) {
- throw new Error(String(parsed.error.message));
- }
- const text = extractStreamChunkText(parsed);
- if (text) {
- output += text;
- setStreamContent(output);
- }
- }
- }
- if (buffer) {
- const parsedEvents = parseSseDataEvents(buffer, true);
- buffer = parsedEvents.rest;
- for (const dataText of parsedEvents.dataEvents) {
- if (dataText === "[DONE]") break;
- let parsed: any;
- try {
- parsed = JSON.parse(dataText);
- } catch {
- continue;
- }
- if (parsed?.error?.message) {
- throw new Error(String(parsed.error.message));
- }
- const text = extractStreamChunkText(parsed);
- if (text) {
- output += text;
- setStreamContent(output);
- }
- }
- }
- if (doneSeen) {
- await reader.cancel().catch(() => {});
- }
-
- const assistantMsg: Message = {
- id: createClientId(),
- conversation_id: activeConvId,
- role: "assistant",
- content: output,
- model: selectedModel,
- created_at: new Date().toISOString(),
- };
- setMessages((prev) => [...prev, assistantMsg]);
- setStreamContent("");
- setStatus("");
- await loadConversations();
- } catch (e: any) {
- if (e?.name === "AbortError") {
- setStatus("已停止");
- } else {
- setStatus(e?.message ?? "请求失败");
- const errMsg: Message = {
- id: createClientId(),
- conversation_id: activeConvId,
- role: "assistant",
- content: `**错误:** ${e?.message ?? "请求失败"}`,
- model: selectedModel,
- created_at: new Date().toISOString(),
- };
- setMessages((prev) => [...prev, errMsg]);
- setStreamContent("");
- }
- } finally {
- if (abortRef.current === controller) abortRef.current = null;
- setIsStreaming(false);
- }
- }, [inputText, isStreaming, currentId, selectedModel, temperature, maxTokens, loadConversations]);
-
- const handleStop = useCallback(() => {
- abortRef.current?.abort();
- abortRef.current = null;
- setIsStreaming(false);
- setStatus("已停止");
- }, []);
-
- const handleStopTest = useCallback(() => {
- testAbortRef.current?.abort();
- testAbortRef.current = null;
- setTestLoading(false);
- setStatus("已停止");
- }, []);
-
- const runTest = useCallback(async () => {
- const model = selectedModel.trim();
- const userPrompt = testUserPrompt.trim();
- if (!model) {
- setStatus("请先选择模型");
- return;
- }
- if (!userPrompt) {
- setStatus("请输入用户消息");
- return;
- }
-
- const messagesPayload: Array<{ role: string; content: string }> = [];
- if (testSystemPrompt.trim()) {
- messagesPayload.push({ role: "system", content: testSystemPrompt.trim() });
- }
- messagesPayload.push({ role: "user", content: userPrompt });
-
- const body: Record = {
- model,
- messages: messagesPayload,
- stream: testStream,
- };
- if (temperature.trim()) body.temperature = Number(temperature);
- if (maxTokens.trim()) body.max_tokens = Number(maxTokens);
-
- setTestLoading(true);
- setTestResult("");
- setTestRaw("");
- setTestUsage("");
- setTestLatencyMs(null);
- setStatus("请求中...");
-
- const startedAt = performance.now();
- const controller = new AbortController();
- testAbortRef.current = controller;
-
- try {
- if (testStream) {
- const res = await fetch("/v1/chat/completions", {
- method: "POST",
- headers: {
- ...authHeaders(),
- accept: "text/event-stream",
- "content-type": "application/json",
- },
- signal: controller.signal,
- body: JSON.stringify(body),
- });
- if (!res.ok) {
- const text = await res.text();
- throw new Error(text || String(res.status));
- }
-
- const reader = res.body?.getReader();
- if (!reader) throw new Error("stream not supported by browser");
- const decoder = new TextDecoder();
- let buffer = "";
- let raw = "";
- let output = "";
- let usageText = "";
- let doneSeen = false;
-
- while (!doneSeen) {
- const { done, value } = await reader.read();
- if (done) break;
- const chunk = decoder.decode(value, { stream: true });
- raw += chunk;
- buffer += chunk;
- setTestRaw(raw);
-
- const parsedEvents = parseSseDataEvents(buffer);
- buffer = parsedEvents.rest;
- for (const dataText of parsedEvents.dataEvents) {
- if (dataText === "[DONE]") {
- doneSeen = true;
- break;
- }
- let parsed: any;
- try {
- parsed = JSON.parse(dataText);
- } catch {
- continue;
- }
- if (parsed?.error?.message) {
- throw new Error(String(parsed.error.message));
- }
- const text = extractStreamChunkText(parsed);
- if (text) {
- output += text;
- setTestResult(output);
- }
- const nextUsage = formatUsage(parsed);
- if (nextUsage) {
- usageText = nextUsage;
- setTestUsage(nextUsage);
- }
- }
- }
- if (buffer) {
- const parsedEvents = parseSseDataEvents(buffer, true);
- buffer = parsedEvents.rest;
- for (const dataText of parsedEvents.dataEvents) {
- if (dataText === "[DONE]") break;
- let parsed: any;
- try {
- parsed = JSON.parse(dataText);
- } catch {
- continue;
- }
- if (parsed?.error?.message) {
- throw new Error(String(parsed.error.message));
- }
- const text = extractStreamChunkText(parsed);
- if (text) {
- output += text;
- setTestResult(output);
- }
- const nextUsage = formatUsage(parsed);
- if (nextUsage) {
- usageText = nextUsage;
- setTestUsage(nextUsage);
- }
- }
- }
- if (doneSeen) {
- await reader.cancel().catch(() => {});
- }
-
- const latency = Math.round(performance.now() - startedAt);
- setTestLatencyMs(latency);
- setTestUsage((current) => current || usageText);
- setStatus("成功");
- } else {
- const data = await fetchJson("/v1/chat/completions", {
- method: "POST",
- signal: controller.signal,
- body: JSON.stringify(body),
- });
- const latency = Math.round(performance.now() - startedAt);
- setTestLatencyMs(latency);
- setTestResult(extractAssistantText(data));
- setTestRaw(JSON.stringify(data, null, 2));
- setTestUsage(formatUsage(data));
- setStatus("成功");
- }
- } catch (e: any) {
- if (e?.name === "AbortError") {
- setStatus("已停止");
- } else {
- setStatus(e?.message ?? "失败");
- }
- } finally {
- if (testAbortRef.current === controller) {
- testAbortRef.current = null;
- }
- setTestLoading(false);
- }
- }, [maxTokens, selectedModel, temperature, testStream, testSystemPrompt, testUserPrompt]);
-
- const handleKeyDown = useCallback(
- (e: React.KeyboardEvent) => {
- if (e.key === "Enter" && !e.shiftKey) {
- e.preventDefault();
- handleSend();
- }
- },
- [handleSend],
- );
-
- const handleUpdateTitle = useCallback(
- async (id: string, title: string) => {
- try {
- await fetchJson(`/chat-api/conversations/${encodeURIComponent(id)}/title`, {
- method: "PUT",
- body: JSON.stringify({ title }),
- });
- await loadConversations();
- } catch {}
- },
- [loadConversations],
- );
-
- if (!apiKey) {
- return (
-
-
-
- );
- }
-
- const sidebarWidth = 280;
- const modelList = models;
-
- return (
-
- {/* Sidebar */}
-
-
-
- EasyAI Chat
-
-
-
-
-
-
- {convLoading && conversations.length === 0 ? (
-
加载中...
- ) : conversations.length === 0 ? (
-
暂无对话
- ) : (
- conversations.map((conv) => (
-
handleSelectConversation(conv.id)}
- className={cx(
- "ui-chat-conversation-item",
- conv.id === currentId && "ui-chat-conversation-active",
- )}
- style={{
- cursor: isStreaming ? "default" : "pointer",
- opacity: isStreaming ? 0.6 : 1,
- }}
- >
-
- {renamingId === conv.id ? (
-
setRenameInput(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- e.stopPropagation();
- const trimmed = renameInput.trim();
- if (trimmed) handleUpdateTitle(conv.id, trimmed);
- setRenamingId(null);
- }
- if (e.key === "Escape") {
- e.stopPropagation();
- setRenamingId(null);
- }
- }}
- onBlur={() => {
- const trimmed = renameInput.trim();
- if (trimmed) handleUpdateTitle(conv.id, trimmed);
- setRenamingId(null);
- }}
- onClick={(e) => e.stopPropagation()}
- autoFocus
- className="ui-input"
- style={{ width: "100%", padding: "2px 6px", fontSize: "var(--ui-font-size-md)" }}
- />
- ) : (
-
{
- if (isStreaming) return;
- setRenamingId(conv.id);
- setRenameInput(conv.title || "");
- }}
- className="ui-chat-conversation-name"
- style={{
- fontWeight: conv.id === currentId ? 600 : 400,
- cursor: isStreaming ? "default" : "text",
- }}
- title="点击重命名"
- >
- {conv.title || "新对话"}
-
- )}
-
- {conv.message_count} 条消息 · {formatTime(conv.updated_at)}
-
-
-
-
- ))
- )}
-
-
-
- {truncate(apiKey, 24)}
-
-
-
-
- {/* Main area */}
-
- {/* Top bar */}
-
-
-
-
-
-
-
- {isStreaming && (
-
- )}
-
- {viewMode === "test" && testLoading && (
-
- )}
-
- {status && {status}}
- {currentConv && (
-
- )}
- {currentConv && (
-
- )}
-
-
- {viewMode === "chat" ? (
- <>
- {/* Settings panel */}
- {showSettings && (
-
-
- setTemperature(e.target.value)}
- style={{ width: 70, fontSize: "var(--ui-font-size-sm)" }}
- />
-
-
- setMaxTokens(e.target.value)}
- style={{ width: 90, fontSize: "var(--ui-font-size-sm)" }}
- />
-
-
- )}
-
- {/* Messages */}
-
- {!currentConv && (
-
- 💬
- 选择或创建一个对话开始聊天
-
- )}
-
- {messages.map((msg) => (
-
- ))}
-
- {isStreaming && (
-
-
- {streamContent}
-
-
-
- )}
-
-
-
-
- {/* Input area */}
-
-
-
-
- >
- ) : (
-
- )}
-
- {pendingDelete && (
-
setPendingDelete(null)}>
-
e.stopPropagation()}
- >
-
- 确认删除会话?
-
- 该操作不可撤销。将删除会话及其全部消息:
- {pendingDelete.title}
-
-
-
-
-
-
-
-
- )}
-
- );
-}
diff --git a/oneapi-gateway/chat-ui/src/ui/id.ts b/oneapi-gateway/chat-ui/src/ui/id.ts
deleted file mode 100644
index d5abfde..0000000
--- a/oneapi-gateway/chat-ui/src/ui/id.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-export function createClientId(): string {
- const randomUUID = globalThis.crypto?.randomUUID;
- if (typeof randomUUID === "function") {
- try {
- return randomUUID.call(globalThis.crypto);
- } catch {}
- }
-
- const bytes = new Uint8Array(16);
- const getRandomValues = globalThis.crypto?.getRandomValues;
- if (typeof getRandomValues === "function") {
- try {
- getRandomValues.call(globalThis.crypto, bytes);
- } catch {
- fillPseudoRandom(bytes);
- }
- } else {
- fillPseudoRandom(bytes);
- }
-
- bytes[6] = (bytes[6]! & 0x0f) | 0x40;
- bytes[8] = (bytes[8]! & 0x3f) | 0x80;
- const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0"));
- return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10, 16).join("")}`;
-}
-
-function fillPseudoRandom(bytes: Uint8Array) {
- for (let i = 0; i < bytes.length; i += 1) {
- bytes[i] = Math.floor(Math.random() * 256);
- }
-}
diff --git a/oneapi-gateway/chat-ui/src/ui/messageLoad.ts b/oneapi-gateway/chat-ui/src/ui/messageLoad.ts
deleted file mode 100644
index d5cda2d..0000000
--- a/oneapi-gateway/chat-ui/src/ui/messageLoad.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-export function shouldApplyLoadedMessages(args: {
- requestSeq: number;
- currentSeq: number;
- requestedConversationId: string;
- currentConversationId: string | null;
- isStreaming: boolean;
-}): boolean {
- return (
- args.requestSeq === args.currentSeq &&
- args.currentConversationId === args.requestedConversationId &&
- !args.isStreaming
- );
-}
diff --git a/oneapi-gateway/chat-ui/src/ui/stream.ts b/oneapi-gateway/chat-ui/src/ui/stream.ts
deleted file mode 100644
index b9a7d0f..0000000
--- a/oneapi-gateway/chat-ui/src/ui/stream.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-export function parseSseDataEvents(buffer: string, flush = false): { dataEvents: string[]; rest: string } {
- const normalized = buffer.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
- const chunks = normalized.split("\n\n");
- const rest = flush ? "" : chunks.pop() ?? "";
- if (flush && chunks[chunks.length - 1] === "") chunks.pop();
- const dataEvents = chunks
- .map((event) =>
- event
- .split("\n")
- .map((line) => line.trim())
- .filter((line) => line.startsWith("data:"))
- .map((line) => line.slice(5).trimStart())
- .join("\n"),
- )
- .filter(Boolean);
- return { dataEvents, rest };
-}
diff --git a/oneapi-gateway/chat-ui/tsconfig.json b/oneapi-gateway/chat-ui/tsconfig.json
deleted file mode 100644
index 88fea78..0000000
--- a/oneapi-gateway/chat-ui/tsconfig.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES2022",
- "lib": ["ES2022", "DOM", "DOM.Iterable"],
- "module": "ESNext",
- "moduleResolution": "Bundler",
- "jsx": "react-jsx",
- "strict": true,
- "skipLibCheck": true,
- "noEmit": true,
- "paths": {
- "@easyai/ui": ["../shared-ui/src/index"],
- "@easyai/ui/*": ["../shared-ui/src/*"]
- },
- "types": ["vite/client"]
- },
- "include": ["src"]
-}
diff --git a/oneapi-gateway/chat-ui/vite.config.ts b/oneapi-gateway/chat-ui/vite.config.ts
deleted file mode 100644
index 19156b1..0000000
--- a/oneapi-gateway/chat-ui/vite.config.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { defineConfig } from "vite";
-import react from "@vitejs/plugin-react";
-import path from "node:path";
-import { fileURLToPath } from "node:url";
-
-const repoRoot = fileURLToPath(new URL("../", import.meta.url));
-
-export default defineConfig({
- plugins: [react()],
- base: "/chat/",
- resolve: {
- alias: {
- "@easyai/ui": path.resolve(repoRoot, "shared-ui/src"),
- },
- dedupe: ["react", "react-dom"],
- },
- server: {
- fs: {
- allow: [repoRoot],
- },
- },
- build: {
- outDir: "dist",
- emptyOutDir: true,
- },
-});
diff --git a/oneapi-gateway/package-lock.json b/oneapi-gateway/package-lock.json
index 03fddb9..72799b3 100644
--- a/oneapi-gateway/package-lock.json
+++ b/oneapi-gateway/package-lock.json
@@ -9,7 +9,6 @@
"version": "0.1.0",
"dependencies": {
"@fastify/cors": "^11.4.3",
- "@fastify/static": "^10.1.12",
"fastify": "^5.12.8",
"js-yaml": "^5.5.0",
"pg": "^8.23.1",
@@ -464,22 +463,6 @@
"node": ">=18"
}
},
- "node_modules/@fastify/accept-negotiator": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/@fastify/accept-negotiator/-/accept-negotiator-2.0.1.tgz",
- "integrity": "sha512-/c/TW2bO/v9JeEgoD/g1G5GxGeCF1Hafdf79WPmUlgYiBXummY0oX3VVq4yFkKKVBKDNlaDUYoab7g38RpPqCQ==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/fastify"
- },
- {
- "type": "opencollective",
- "url": "https://opencollective.com/fastify"
- }
- ],
- "license": "MIT"
- },
"node_modules/@fastify/ajv-compiler": {
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/@fastify/ajv-compiler/-/ajv-compiler-4.0.5.tgz",
@@ -611,69 +594,6 @@
"ipaddr.js": "^2.1.0"
}
},
- "node_modules/@fastify/send": {
- "version": "4.2.1",
- "resolved": "https://registry.npmjs.org/@fastify/send/-/send-4.2.1.tgz",
- "integrity": "sha512-zOB8L9z444PnGbd1Nd7gNXPz/7bnDR8Z4KNTNSwLVQuE3cTGsU9qUj1N4SjXKK0Tq4cauZYTwB+tqvlqosuKsw==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/fastify"
- },
- {
- "type": "opencollective",
- "url": "https://opencollective.com/fastify"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "@lukeed/ms": "^2.0.2",
- "escape-html": "~1.0.3",
- "fast-decode-uri-component": "^1.0.1",
- "http-errors": "^2.0.0",
- "mime": "^3"
- }
- },
- "node_modules/@fastify/static": {
- "version": "10.1.12",
- "resolved": "https://registry.npmjs.org/@fastify/static/-/static-10.1.12.tgz",
- "integrity": "sha512-D0pmf8OgurIsKiIjxC8ZJP/bCYnUSAiU6PS/se/6Me63UoliAu8FqrzDRX8FdgJMqFMXy45ISlfUZ1Gi6AJnqA==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/fastify"
- },
- {
- "type": "opencollective",
- "url": "https://opencollective.com/fastify"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "@fastify/accept-negotiator": "^2.0.0",
- "@fastify/error": "^4.0.0",
- "@fastify/send": "^4.2.0",
- "content-disposition": "^3.0.0",
- "fastify-plugin": "^6.0.0",
- "fastq": "^1.17.1",
- "glob": "^14.0.0"
- }
- },
- "node_modules/@isaacs/nonrecursive-glob-match": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz",
- "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==",
- "license": "BlueOak-1.0.0"
- },
- "node_modules/@lukeed/ms": {
- "version": "2.0.2",
- "resolved": "https://registry.npmjs.org/@lukeed/ms/-/ms-2.0.2.tgz",
- "integrity": "sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA==",
- "license": "MIT",
- "engines": {
- "node": ">=8"
- }
- },
"node_modules/@pinojs/redact": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
@@ -1195,40 +1115,6 @@
"fastq": "^1.17.1"
}
},
- "node_modules/balanced-match": {
- "version": "4.0.4",
- "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
- "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
- "license": "MIT",
- "engines": {
- "node": "18 || 20 || >=22"
- }
- },
- "node_modules/brace-expansion": {
- "version": "5.0.13",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz",
- "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==",
- "license": "MIT",
- "dependencies": {
- "balanced-match": "^4.0.2"
- },
- "engines": {
- "node": "20 || >=22"
- }
- },
- "node_modules/content-disposition": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-3.1.0.tgz",
- "integrity": "sha512-6lwVDK9bsenmMu7hxcLuUiu+FzFBDAdfQR1LKbE+SCo7/Qfpm2NG8X9f8AJgumfoVID/4r1stSxcmCeiT7pfkQ==",
- "license": "MIT",
- "engines": {
- "node": ">=22"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/express"
- }
- },
"node_modules/cookie": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
@@ -1242,15 +1128,6 @@
"url": "https://opencollective.com/express"
}
},
- "node_modules/depd": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
- "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.8"
- }
- },
"node_modules/dequal": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
@@ -1302,12 +1179,6 @@
"@esbuild/win32-x64": "0.28.0"
}
},
- "node_modules/escape-html": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
- "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
- "license": "MIT"
- },
"node_modules/fast-decode-uri-component": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz",
@@ -1496,49 +1367,6 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
- "node_modules/glob": {
- "version": "14.0.6",
- "resolved": "https://registry.npmjs.org/glob/-/glob-14.0.6.tgz",
- "integrity": "sha512-OwXjVP2svY5EyLY75Vek96C8qK43gqrt4xsZ+qSILdnaEiJPXkd62mcfUSNx/TQErQRdu5uM5kF67sfONragKw==",
- "license": "BlueOak-1.0.0",
- "dependencies": {
- "minimatch": "^11.0.5",
- "minipass": "^7.1.3",
- "path-scurry": "^3.0.0"
- },
- "engines": {
- "node": "18 || 20 || >=22"
- },
- "funding": {
- "url": "https://github.com/sponsors/isaacs"
- }
- },
- "node_modules/http-errors": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
- "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
- "license": "MIT",
- "dependencies": {
- "depd": "~2.0.0",
- "inherits": "~2.0.4",
- "setprototypeof": "~1.2.0",
- "statuses": "~2.0.2",
- "toidentifier": "~1.0.1"
- },
- "engines": {
- "node": ">= 0.8"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/express"
- }
- },
- "node_modules/inherits": {
- "version": "2.0.4",
- "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
- "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
- "license": "ISC"
- },
"node_modules/ipaddr.js": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.4.0.tgz",
@@ -1632,52 +1460,6 @@
],
"license": "MIT"
},
- "node_modules/lru-cache": {
- "version": "11.5.3",
- "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
- "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
- "license": "BlueOak-1.0.0",
- "engines": {
- "node": "20 || >=22"
- }
- },
- "node_modules/mime": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz",
- "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==",
- "license": "MIT",
- "bin": {
- "mime": "cli.js"
- },
- "engines": {
- "node": ">=10.0.0"
- }
- },
- "node_modules/minimatch": {
- "version": "11.0.9",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz",
- "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==",
- "license": "BlueOak-1.0.0",
- "dependencies": {
- "@isaacs/nonrecursive-glob-match": "^1.1.0",
- "brace-expansion": "^5.0.12"
- },
- "engines": {
- "node": "20 || >=22"
- },
- "funding": {
- "url": "https://github.com/sponsors/isaacs"
- }
- },
- "node_modules/minipass": {
- "version": "7.1.3",
- "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
- "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
- "license": "BlueOak-1.0.0",
- "engines": {
- "node": ">=16 || 14 >=14.17"
- }
- },
"node_modules/on-exit-leak-free": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",
@@ -1687,22 +1469,6 @@
"node": ">=14.0.0"
}
},
- "node_modules/path-scurry": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz",
- "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==",
- "license": "BlueOak-1.0.0",
- "dependencies": {
- "lru-cache": "^11.0.0",
- "minipass": "^7.1.2"
- },
- "engines": {
- "node": "18 || 20 || >=22"
- },
- "funding": {
- "url": "https://github.com/sponsors/isaacs"
- }
- },
"node_modules/pg": {
"version": "8.23.1",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz",
@@ -2014,12 +1780,6 @@
"integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
"license": "MIT"
},
- "node_modules/setprototypeof": {
- "version": "1.2.0",
- "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
- "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
- "license": "ISC"
- },
"node_modules/sonic-boom": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz",
@@ -2038,15 +1798,6 @@
"node": ">= 10.x"
}
},
- "node_modules/statuses": {
- "version": "2.0.2",
- "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
- "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.8"
- }
- },
"node_modules/thread-stream": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz",
@@ -2074,15 +1825,6 @@
"node": ">=20"
}
},
- "node_modules/toidentifier": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
- "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
- "license": "MIT",
- "engines": {
- "node": ">=0.6"
- }
- },
"node_modules/tsx": {
"version": "4.23.15",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz",
diff --git a/oneapi-gateway/package.json b/oneapi-gateway/package.json
index c973e09..1c8efed 100644
--- a/oneapi-gateway/package.json
+++ b/oneapi-gateway/package.json
@@ -12,7 +12,6 @@
},
"dependencies": {
"@fastify/cors": "^11.4.3",
- "@fastify/static": "^10.1.12",
"fastify": "^5.12.8",
"js-yaml": "^5.5.0",
"pg": "^8.23.1",
diff --git a/oneapi-gateway/shared-ui/package-lock.json b/oneapi-gateway/shared-ui/package-lock.json
deleted file mode 100644
index fc59c7e..0000000
--- a/oneapi-gateway/shared-ui/package-lock.json
+++ /dev/null
@@ -1,453 +0,0 @@
-{
- "name": "@easyai/ui",
- "version": "0.1.0",
- "lockfileVersion": 3,
- "requires": true,
- "packages": {
- "": {
- "name": "@easyai/ui",
- "version": "0.1.0",
- "devDependencies": {
- "@types/react": "^19.3.0",
- "@types/react-dom": "^19.3.0",
- "typescript": "^7.0.2"
- },
- "peerDependencies": {
- "react": "^19.1.1",
- "react-dom": "^19.1.1"
- }
- },
- "node_modules/@types/react": {
- "version": "19.3.0",
- "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
- "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "csstype": "^3.2.2"
- }
- },
- "node_modules/@types/react-dom": {
- "version": "19.3.0",
- "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz",
- "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==",
- "dev": true,
- "license": "MIT",
- "peerDependencies": {
- "@types/react": "^19.3.0"
- }
- },
- "node_modules/@typescript/typescript-aix-ppc64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
- "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
- "cpu": [
- "ppc64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "aix"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-darwin-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
- "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-darwin-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
- "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-freebsd-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
- "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "freebsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-freebsd-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
- "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "freebsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-arm": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
- "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
- "cpu": [
- "arm"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
- "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-loong64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
- "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
- "cpu": [
- "loong64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-mips64el": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
- "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
- "cpu": [
- "mips64el"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-ppc64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
- "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
- "cpu": [
- "ppc64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-riscv64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
- "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
- "cpu": [
- "riscv64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-s390x": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
- "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
- "cpu": [
- "s390x"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
- "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-netbsd-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
- "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "netbsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-netbsd-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
- "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "netbsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-openbsd-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
- "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "openbsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-openbsd-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
- "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "openbsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-sunos-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
- "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "sunos"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-win32-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
- "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-win32-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
- "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/csstype": {
- "version": "3.2.3",
- "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
- "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
- "dev": true,
- "license": "MIT"
- },
- "node_modules/react": {
- "version": "19.2.7",
- "resolved": "https://registry.npmjs.org/react/-/react-19.2.7.tgz",
- "integrity": "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==",
- "license": "MIT",
- "peer": true,
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/react-dom": {
- "version": "19.2.7",
- "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.7.tgz",
- "integrity": "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ==",
- "license": "MIT",
- "peer": true,
- "dependencies": {
- "scheduler": "^0.27.0"
- },
- "peerDependencies": {
- "react": "^19.2.7"
- }
- },
- "node_modules/scheduler": {
- "version": "0.27.0",
- "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
- "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
- "license": "MIT",
- "peer": true
- },
- "node_modules/typescript": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
- "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
- "dev": true,
- "license": "Apache-2.0",
- "bin": {
- "tsc": "bin/tsc"
- },
- "engines": {
- "node": ">=16.20.0"
- },
- "optionalDependencies": {
- "@typescript/typescript-aix-ppc64": "7.0.2",
- "@typescript/typescript-darwin-arm64": "7.0.2",
- "@typescript/typescript-darwin-x64": "7.0.2",
- "@typescript/typescript-freebsd-arm64": "7.0.2",
- "@typescript/typescript-freebsd-x64": "7.0.2",
- "@typescript/typescript-linux-arm": "7.0.2",
- "@typescript/typescript-linux-arm64": "7.0.2",
- "@typescript/typescript-linux-loong64": "7.0.2",
- "@typescript/typescript-linux-mips64el": "7.0.2",
- "@typescript/typescript-linux-ppc64": "7.0.2",
- "@typescript/typescript-linux-riscv64": "7.0.2",
- "@typescript/typescript-linux-s390x": "7.0.2",
- "@typescript/typescript-linux-x64": "7.0.2",
- "@typescript/typescript-netbsd-arm64": "7.0.2",
- "@typescript/typescript-netbsd-x64": "7.0.2",
- "@typescript/typescript-openbsd-arm64": "7.0.2",
- "@typescript/typescript-openbsd-x64": "7.0.2",
- "@typescript/typescript-sunos-x64": "7.0.2",
- "@typescript/typescript-win32-arm64": "7.0.2",
- "@typescript/typescript-win32-x64": "7.0.2"
- }
- }
- }
-}
diff --git a/oneapi-gateway/shared-ui/package.json b/oneapi-gateway/shared-ui/package.json
deleted file mode 100644
index b573575..0000000
--- a/oneapi-gateway/shared-ui/package.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "name": "@easyai/ui",
- "private": true,
- "version": "0.1.0",
- "type": "module",
- "peerDependencies": {
- "react": "^19.3.1",
- "react-dom": "^19.3.1"
- },
- "devDependencies": {
- "@types/react": "^19.3.0",
- "@types/react-dom": "^19.3.0",
- "typescript": "^7.0.2"
- }
-}
diff --git a/oneapi-gateway/shared-ui/src/components.tsx b/oneapi-gateway/shared-ui/src/components.tsx
deleted file mode 100644
index 52ec931..0000000
--- a/oneapi-gateway/shared-ui/src/components.tsx
+++ /dev/null
@@ -1,277 +0,0 @@
-import { forwardRef } from "react";
-import type {
- CSSProperties,
- ButtonHTMLAttributes,
- InputHTMLAttributes,
- ReactNode,
- SelectHTMLAttributes,
- TextareaHTMLAttributes,
-} from "react";
-
-function cx(...parts: Array) {
- return parts.filter(Boolean).join(" ");
-}
-
-type ButtonVariant = "primary" | "secondary" | "ghost" | "danger" | "dashed";
-type ButtonSize = "sm" | "md";
-
-export type ButtonProps = ButtonHTMLAttributes & {
- variant?: ButtonVariant;
- size?: ButtonSize;
- block?: boolean;
-};
-
-export const Button = forwardRef(function Button(
- { className, variant = "secondary", size = "md", block, type = "button", style, ...props },
- ref,
-) {
- return (
-
- );
-});
-
-export type InputProps = InputHTMLAttributes & {
- fullWidth?: boolean;
-};
-
-export const Input = forwardRef(function Input(
- { className, fullWidth, style, ...props },
- ref,
-) {
- return (
-
- );
-});
-
-export type SelectProps = SelectHTMLAttributes & {
- fullWidth?: boolean;
-};
-
-export const Select = forwardRef(function Select(
- { className, fullWidth, style, ...props },
- ref,
-) {
- return (
-
- );
-});
-
-export type TextAreaProps = TextareaHTMLAttributes & {
- fullWidth?: boolean;
-};
-
-export const TextArea = forwardRef(function TextArea(
- { className, fullWidth, style, ...props },
- ref,
-) {
- return (
-
- );
-});
-
-export function Card(props: { children: ReactNode; className?: string; style?: CSSProperties }) {
- const { children, className, style } = props;
- return (
-
- {children}
-
- );
-}
-
-type TableProps = {
- children: ReactNode;
- className?: string;
- style?: CSSProperties;
- minWidth?: number | string;
-};
-
-export function Table(props: TableProps) {
- const { children, className, style, minWidth } = props;
- return (
-
- );
-}
-
-export function TableHead(props: { children: ReactNode; className?: string }) {
- return {props.children};
-}
-
-export function TableBody(props: { children: ReactNode; className?: string }) {
- return {props.children};
-}
-
-export function TableRow(props: { children: ReactNode; className?: string }) {
- return {props.children}
;
-}
-
-export function TableHeadCell(props: {
- children: ReactNode;
- className?: string;
- scope?: "col" | "row";
-}) {
- return (
-
- {props.children}
- |
- );
-}
-
-export function TableCell(props: { children: ReactNode; className?: string }) {
- return {props.children} | ;
-}
-
-export function Page(props: { children: ReactNode; className?: string; style?: CSSProperties }) {
- const { children, className, style } = props;
- return (
-
- {children}
-
- );
-}
-
-export function Center(props: { children: ReactNode; className?: string; style?: CSSProperties }) {
- const { children, className, style } = props;
- return (
-
- {children}
-
- );
-}
-
-export function Stack(props: {
- children: ReactNode;
- className?: string;
- style?: CSSProperties;
- gap?: number | string;
- align?: CSSProperties["alignItems"];
-}) {
- const { children, className, style, gap = 12, align } = props;
- return (
-
- {children}
-
- );
-}
-
-export function Inline(props: {
- children: ReactNode;
- className?: string;
- style?: CSSProperties;
- gap?: number | string;
- align?: CSSProperties["alignItems"];
- justify?: CSSProperties["justifyContent"];
- wrap?: boolean;
-}) {
- const { children, className, style, gap = 12, align = "center", justify, wrap = true } = props;
- return (
-
- {children}
-
- );
-}
-
-export function Grid(props: {
- children: ReactNode;
- className?: string;
- style?: CSSProperties;
- gap?: number | string;
- columns?: string;
- minChildWidth?: number | string;
-}) {
- const { children, className, style, gap = 12, columns, minChildWidth } = props;
- const gridTemplateColumns = columns ?? (minChildWidth ? `repeat(auto-fit, minmax(${typeof minChildWidth === "number" ? `${minChildWidth}px` : minChildWidth}, 1fr))` : undefined);
- return (
-
- {children}
-
- );
-}
-
-export function Section(props: {
- title?: ReactNode;
- description?: ReactNode;
- children?: ReactNode;
- className?: string;
- style?: CSSProperties;
-}) {
- const { title, description, children, className, style } = props;
- return (
-
- {(title || description) && (
-
- {title ?
{title}
: null}
- {description ?
{description}
: null}
-
- )}
- {children}
-
- );
-}
-
-export function Field(props: {
- label: ReactNode;
- children: ReactNode;
- hint?: ReactNode;
- className?: string;
- style?: CSSProperties;
- compact?: boolean;
- orientation?: "stack" | "inline";
-}) {
- const { label, children, hint, className, style, compact, orientation = "stack" } = props;
- return (
-
- );
-}
-
-export function ActionBar(props: {
- children: ReactNode;
- className?: string;
- style?: CSSProperties;
- align?: CSSProperties["alignItems"];
- justify?: CSSProperties["justifyContent"];
-}) {
- const { children, className, style, align, justify } = props;
- return (
-
- {children}
-
- );
-}
diff --git a/oneapi-gateway/shared-ui/src/index.ts b/oneapi-gateway/shared-ui/src/index.ts
deleted file mode 100644
index ad8d9ff..0000000
--- a/oneapi-gateway/shared-ui/src/index.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-export { ThemeProvider, ThemeToggle, useTheme } from "./theme";
-export type { ThemeMode, ThemeValue } from "./theme";
-export {
- ActionBar,
- Button,
- Card,
- Center,
- Field,
- Grid,
- Input,
- Inline,
- Page,
- Select,
- Section,
- Stack,
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeadCell,
- TableRow,
- TextArea,
-} from "./components";
diff --git a/oneapi-gateway/shared-ui/src/styles.css b/oneapi-gateway/shared-ui/src/styles.css
deleted file mode 100644
index dc1c255..0000000
--- a/oneapi-gateway/shared-ui/src/styles.css
+++ /dev/null
@@ -1,941 +0,0 @@
-:root {
- --ui-font-sans: "Inter", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
- --ui-font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
- --ui-radius-sm: 10px;
- --ui-radius-md: 14px;
- --ui-radius-lg: 18px;
- --ui-control-height: 40px;
- --ui-control-height-compact: 36px;
- --ui-control-gap: 10px;
- --ui-control-padding-x: 14px;
- --ui-control-font-size: var(--ui-font-size-md);
- --ui-control-line-height: 1.35;
- --ui-card-padding: 16px;
- --ui-text-line-height: 1.62;
- --ui-font-size-xs: 12px;
- --ui-font-size-sm: 13px;
- --ui-font-size-md: 14px;
- --ui-font-size-lg: 16px;
- --ui-font-size-xl: 18px;
- --ui-font-size-2xl: 24px;
- --ui-font-size-3xl: 32px;
- --ui-space-1: 4px;
- --ui-space-2: 8px;
- --ui-space-3: 12px;
- --ui-space-4: 16px;
- --ui-space-5: 20px;
- --ui-space-6: 24px;
- --ui-bg: #f4f7fb;
- --ui-bg-elevated: rgba(255, 255, 255, 0.84);
- --ui-bg-strong: #ffffff;
- --ui-text: #0f172a;
- --ui-text-muted: #64748b;
- --ui-border: rgba(148, 163, 184, 0.28);
- --ui-border-strong: rgba(148, 163, 184, 0.38);
- --ui-primary: #2563eb;
- --ui-primary-strong: #1d4ed8;
- --ui-danger: #dc2626;
- --ui-success: #15803d;
- --ui-warning: #b45309;
- --ui-shadow: 0 18px 48px rgba(15, 23, 42, 0.08);
- --ui-shadow-soft: 0 8px 24px rgba(15, 23, 42, 0.06);
- --ui-input-bg: rgba(255, 255, 255, 0.92);
-}
-
-html[data-theme="dark"] {
- --ui-bg: #08111f;
- --ui-bg-elevated: rgba(15, 23, 42, 0.82);
- --ui-bg-strong: #0f172a;
- --ui-text: #e2e8f0;
- --ui-text-muted: #94a3b8;
- --ui-border: rgba(148, 163, 184, 0.2);
- --ui-border-strong: rgba(148, 163, 184, 0.3);
- --ui-primary: #60a5fa;
- --ui-primary-strong: #93c5fd;
- --ui-danger: #f87171;
- --ui-success: #4ade80;
- --ui-warning: #f59e0b;
- --ui-shadow: 0 20px 48px rgba(0, 0, 0, 0.32);
- --ui-shadow-soft: 0 10px 28px rgba(0, 0, 0, 0.24);
- --ui-input-bg: rgba(15, 23, 42, 0.9);
-}
-
-html,
-body,
-#root {
- min-height: 100%;
-}
-
-body {
- margin: 0;
- color: var(--ui-text);
- background:
- radial-gradient(circle at top left, rgba(37, 99, 235, 0.12), transparent 28%),
- radial-gradient(circle at right top, rgba(14, 165, 233, 0.1), transparent 24%),
- var(--ui-bg);
- font-family: var(--ui-font-sans);
- font-size: var(--ui-font-size-md);
- line-height: var(--ui-text-line-height);
- text-rendering: optimizeLegibility;
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
-}
-
-h1,
-h2,
-h3,
-p {
- margin-top: 0;
-}
-
-h1,
-.ui-page-title {
- margin-bottom: 0;
- font-size: clamp(var(--ui-font-size-2xl), 2.4vw, var(--ui-font-size-3xl));
- font-weight: 750;
- letter-spacing: -0.03em;
- line-height: 1.12;
-}
-
-h2,
-.ui-page-subtitle {
- margin-bottom: 0;
- font-size: var(--ui-font-size-2xl);
- font-weight: 720;
- letter-spacing: -0.025em;
- line-height: 1.18;
-}
-
-h3 {
- font-size: var(--ui-font-size-xl);
- line-height: 1.28;
-}
-
-* {
- box-sizing: border-box;
-}
-
-button,
-input,
-select,
-textarea {
- font: inherit;
- color: inherit;
-}
-
-button,
-input[type="button"],
-input[type="submit"],
-input[type="reset"],
-select {
- min-height: var(--ui-control-height) !important;
- padding: 0 var(--ui-control-padding-x) !important;
- border-radius: var(--ui-radius-md) !important;
- border: 1px solid var(--ui-border) !important;
- background: var(--ui-bg-elevated);
- box-shadow: var(--ui-shadow-soft);
-}
-
-button {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- cursor: pointer;
- line-height: var(--ui-control-line-height);
- transition:
- transform 120ms ease,
- border-color 120ms ease,
- box-shadow 120ms ease,
- opacity 120ms ease;
-}
-
-.ui-button {
- gap: 8px;
- white-space: nowrap;
- min-width: max-content;
- letter-spacing: 0.01em;
-}
-
-.ui-button[data-size="sm"] {
- min-height: 34px !important;
- padding: 0 12px !important;
- border-radius: 12px !important;
- font-size: var(--ui-font-size-xs);
-}
-
-.ui-button[data-variant="primary"] {
- background: var(--ui-primary) !important;
- border-color: transparent !important;
- color: #fff !important;
-}
-
-.ui-button[data-variant="secondary"] {
- background: var(--ui-bg-elevated) !important;
- color: var(--ui-text);
-}
-
-.ui-button[data-variant="ghost"] {
- background: transparent !important;
- box-shadow: none !important;
- color: var(--ui-text-muted);
-}
-
-.ui-button[data-variant="dashed"] {
- background: transparent !important;
- border-style: dashed !important;
- box-shadow: none !important;
- color: var(--ui-primary);
-}
-
-.ui-button[data-variant="danger"] {
- background: var(--ui-danger) !important;
- border-color: transparent !important;
- color: #fff !important;
-}
-
-button:hover:not(:disabled) {
- transform: translateY(-1px);
- border-color: var(--ui-border-strong);
-}
-
-button:disabled {
- cursor: not-allowed;
- opacity: 0.55;
- transform: none;
-}
-
-input,
-select,
-textarea {
- width: auto;
- min-width: 0;
- border-radius: var(--ui-radius-md) !important;
- border: 1px solid var(--ui-border) !important;
- background: var(--ui-input-bg) !important;
- outline: none;
- font-size: var(--ui-control-font-size);
- line-height: var(--ui-control-line-height);
- transition:
- border-color 120ms ease,
- box-shadow 120ms ease,
- background 120ms ease;
-}
-
-.ui-input,
-.ui-select,
-.ui-textarea {
- box-shadow: none;
-}
-
-input:not([type="checkbox"]):not([type="radio"]),
-select {
- padding-inline: var(--ui-control-padding-x) !important;
-}
-
-input:not([type="checkbox"]):not([type="radio"]),
-select {
- height: var(--ui-control-height) !important;
-}
-
-.ui-input,
-.ui-select {
- height: var(--ui-control-height) !important;
-}
-
-.ui-input[data-full-width="true"],
-.ui-select[data-full-width="true"],
-.ui-textarea[data-full-width="true"] {
- width: 100%;
-}
-
-textarea {
- padding: 13px 15px !important;
- resize: vertical;
- min-height: 120px;
- line-height: var(--ui-text-line-height);
-}
-
-input:focus,
-select:focus,
-textarea:focus,
-button:focus-visible {
- border-color: color-mix(in srgb, var(--ui-primary) 70%, white) !important;
- box-shadow: 0 0 0 4px color-mix(in srgb, var(--ui-primary) 18%, transparent);
-}
-
-input::placeholder,
-textarea::placeholder {
- color: var(--ui-text-muted);
-}
-
-input[type="checkbox"],
-input[type="radio"] {
- width: 16px;
- height: 16px;
- min-height: 16px;
- padding: 0;
- accent-color: var(--ui-primary);
- box-shadow: none;
-}
-
-code,
-pre {
- font-family: var(--ui-font-mono);
-}
-
-code {
- color: color-mix(in srgb, var(--ui-primary) 70%, var(--ui-text));
-}
-
-a {
- color: var(--ui-primary);
-}
-
-.ui-shell {
- min-height: 100%;
- color: var(--ui-text);
-}
-
-.ui-page {
- width: 100%;
- min-height: 100%;
-}
-
-.ui-center {
- display: grid;
- place-items: center;
- min-height: 100%;
-}
-
-.ui-surface {
- background: var(--ui-bg-elevated);
- border: 1px solid var(--ui-border);
- border-radius: var(--ui-radius-lg);
- box-shadow: var(--ui-shadow);
- backdrop-filter: blur(14px);
-}
-
-.ui-card {
- background: var(--ui-bg-elevated);
- border: 1px solid var(--ui-border);
- border-radius: var(--ui-radius-lg);
- box-shadow: var(--ui-shadow-soft);
- padding: var(--ui-card-padding);
-}
-
-.ui-section {
- display: grid;
- gap: var(--ui-space-4);
- min-width: 0;
-}
-
-.ui-section-header {
- display: grid;
- gap: 5px;
- min-width: 0;
-}
-
-.ui-section-title {
- margin: 0;
- font-size: var(--ui-font-size-xl);
- line-height: 1.32;
- letter-spacing: -0.01em;
-}
-
-.ui-section-description {
- color: var(--ui-text-muted);
- font-size: var(--ui-font-size-sm);
- line-height: var(--ui-text-line-height);
-}
-
-.ui-field {
- display: grid;
- gap: 7px;
- min-width: 0;
-}
-
-.ui-field[data-compact="true"] {
- gap: 4px;
-}
-
-.ui-field[data-orientation="inline"] {
- grid-template-columns: auto minmax(0, 1fr);
- align-items: center;
- gap: 8px;
-}
-
-.ui-field-label {
- color: var(--ui-text-muted);
- font-size: var(--ui-font-size-xs);
- font-weight: 650;
- letter-spacing: 0.01em;
- line-height: 1.35;
-}
-
-.ui-field-hint {
- color: var(--ui-text-muted);
- font-size: var(--ui-font-size-xs);
- line-height: 1.5;
-}
-
-.ui-action-bar {
- display: flex;
- flex-wrap: wrap;
- align-items: flex-end;
- gap: var(--ui-control-gap);
-}
-
-.ui-action-bar > * {
- min-width: 0;
-}
-
-.ui-action-bar > div {
- min-width: 0;
-}
-
-.ui-action-bar .ui-spacer {
- margin-left: auto;
-}
-
-.ui-action-bar .ui-field {
- flex: 0 1 220px;
-}
-
-.ui-action-bar .ui-field[data-compact="true"] {
- flex-basis: auto;
-}
-
-.ui-action-bar .ui-input,
-.ui-action-bar .ui-select,
-.ui-action-bar .ui-button,
-.ui-action-bar button,
-.ui-action-bar input:not([type="checkbox"]):not([type="radio"]),
-.ui-action-bar select {
- min-height: var(--ui-control-height) !important;
- height: var(--ui-control-height) !important;
-}
-
-.ui-action-bar > .ui-button,
-.ui-action-bar > button {
- align-self: flex-end;
-}
-
-.ui-action-bar .ui-button[data-size="sm"] {
- min-height: var(--ui-control-height) !important;
- height: var(--ui-control-height) !important;
- padding: 0 14px !important;
- font-size: var(--ui-font-size-sm);
-}
-
-.ui-popover {
- border-radius: var(--ui-radius-lg);
- box-shadow: var(--ui-shadow);
- backdrop-filter: blur(14px);
-}
-
-.ui-muted {
- color: var(--ui-text-muted);
-}
-
-.ui-toolbar {
- display: flex;
- flex-wrap: wrap;
- align-items: flex-end;
- gap: var(--ui-control-gap);
-}
-
-.ui-toolbar > * {
- min-width: 0;
-}
-
-.ui-toolbar .ui-spacer {
- margin-left: auto;
-}
-
-.ui-stack {
- display: grid;
- gap: var(--ui-space-4);
- min-width: 0;
-}
-
-.ui-grid {
- display: grid;
- gap: var(--ui-space-3);
- min-width: 0;
-}
-
-.ui-inline {
- display: flex;
- gap: var(--ui-control-gap);
- align-items: center;
- flex-wrap: wrap;
-}
-
-.ui-stat-grid {
- display: grid;
- gap: var(--ui-space-3);
- grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
-}
-
-.ui-stat {
- padding: var(--ui-space-4);
-}
-
-.ui-badge {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- min-height: 30px;
- padding: 0 12px;
- border-radius: 999px;
- border: 1px solid var(--ui-border);
- background: var(--ui-bg-elevated);
- color: var(--ui-text);
- box-shadow: var(--ui-shadow-soft);
- white-space: nowrap;
- line-height: 1;
-}
-
-.ui-badge-dot {
- width: 8px;
- height: 8px;
- border-radius: 999px;
- flex: 0 0 auto;
-}
-
-.ui-tabbar {
- display: flex;
- flex-wrap: wrap;
- align-items: center;
- gap: 10px;
-}
-
-.ui-tab {
- min-height: var(--ui-control-height);
- padding: 0 14px;
- border-radius: 999px;
- border: 1px solid var(--ui-border);
- background: transparent;
- color: var(--ui-text-muted);
-}
-
-.ui-tab[aria-selected="true"] {
- background: var(--ui-primary);
- border-color: transparent;
- color: white;
-}
-
-.ui-table-wrap {
- overflow: auto;
- border: 1px solid var(--ui-border);
- border-radius: var(--ui-radius-lg);
- background: var(--ui-bg-elevated);
- box-shadow: var(--ui-shadow-soft);
-}
-
-.ui-table {
- width: 100%;
- border-collapse: collapse;
- min-width: 640px;
-}
-
-.ui-table th,
-.ui-table td {
- padding: 13px 14px;
- text-align: left;
- border-bottom: 1px solid var(--ui-border);
- vertical-align: top;
- line-height: 1.52;
-}
-
-.ui-table thead th {
- position: sticky;
- top: 0;
- background: var(--ui-bg-elevated);
- z-index: 1;
- color: var(--ui-text-muted);
- font-size: var(--ui-font-size-xs);
- font-weight: 700;
- letter-spacing: 0.02em;
- white-space: nowrap;
-}
-
-.ui-table--compact th,
-.ui-table--compact td {
- padding: 10px 12px;
-}
-
-.ui-dialog-overlay {
- position: fixed;
- inset: 0;
- display: grid;
- place-items: center;
- background: rgba(2, 6, 23, 0.55);
- padding: 24px;
- z-index: 1000;
-}
-
-.ui-dialog {
- width: min(520px, 100%);
- padding: 24px;
- border-radius: 22px;
- background: var(--ui-bg-strong);
- border: 1px solid var(--ui-border);
- box-shadow: 0 24px 68px rgba(0, 0, 0, 0.28);
-}
-
-.ui-dialog-actions {
- display: flex;
- justify-content: flex-end;
- gap: 10px;
- flex-wrap: wrap;
-}
-
-.ui-layout-chat {
- --ui-chat-bottom-height: 89px;
- display: flex;
- height: 100%;
- max-height: 100%;
- min-height: 100%;
- min-width: 0;
- overflow: hidden;
-}
-
-.ui-layout-chat .ui-sidebar {
- width: 280px;
- min-width: 280px;
- display: flex;
- flex-direction: column;
-}
-
-.ui-layout-chat .ui-main {
- flex: 1;
- min-width: 0;
- display: flex;
- flex-direction: column;
-}
-
-.ui-chat-login {
- padding: 40px;
- width: 420px;
- max-width: 92vw;
-}
-
-.ui-chat-sidebar-header {
- padding: 16px;
- border-bottom: 1px solid var(--ui-border);
-}
-
-.ui-chat-conversation-list {
- flex: 1;
- min-height: 0;
- overflow: auto;
- -webkit-overflow-scrolling: touch;
- padding: 8px;
-}
-
-.ui-chat-conversation-item {
- padding: 11px 12px;
- border-radius: var(--ui-radius-sm);
- margin-bottom: 4px;
- display: flex;
- gap: 8px;
- align-items: flex-start;
- transition:
- background 120ms ease,
- transform 120ms ease;
-}
-
-.ui-chat-conversation-item:hover {
- background: color-mix(in srgb, var(--ui-primary) 8%, transparent);
-}
-
-.ui-chat-conversation-active {
- background: color-mix(in srgb, var(--ui-primary) 12%, transparent);
-}
-
-.ui-chat-conversation-name {
- font-size: var(--ui-font-size-md);
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.ui-chat-conversation-meta {
- font-size: var(--ui-font-size-xs);
- color: var(--ui-text-muted);
- margin-top: 2px;
-}
-
-.ui-chat-footer {
- flex: 0 0 var(--ui-chat-bottom-height);
- height: var(--ui-chat-bottom-height);
- min-height: var(--ui-chat-bottom-height);
- padding: 16px 16px calc(16px + env(safe-area-inset-bottom, 0px));
- border-top: 1px solid var(--ui-border);
- font-size: var(--ui-font-size-xs);
- color: var(--ui-text-muted);
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: 12px;
- background:
- linear-gradient(180deg, color-mix(in srgb, var(--ui-bg-strong) 72%, transparent), transparent 140%),
- var(--ui-bg);
- box-shadow: inset 0 1px 0 color-mix(in srgb, white 34%, transparent);
-}
-
-html[data-theme="dark"] .ui-chat-footer {
- box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04);
-}
-
-.ui-chat-footer > span {
- min-width: 0;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.ui-chat-main {
- min-height: 0;
- background: var(--ui-bg-elevated);
-}
-
-.ui-chat-topbar {
- padding: 12px 24px;
- border-bottom: 1px solid var(--ui-border);
- align-items: center;
-}
-
-.ui-chat-topbar .ui-select {
- flex: 1 1 220px;
- max-width: 360px;
-}
-
-.ui-chat-topbar .ui-spacer {
- margin-left: auto;
-}
-
-.ui-chat-settings {
- padding: 12px 24px;
- border-bottom: 1px solid var(--ui-border);
- font-size: var(--ui-font-size-sm);
- background: var(--ui-bg);
- align-items: flex-end;
-}
-
-.ui-chat-messages {
- flex: 1;
- overflow: auto;
- min-height: 0;
- -webkit-overflow-scrolling: touch;
- overscroll-behavior: contain;
- padding: 24px;
-}
-
-.ui-chat-message-row {
- margin-bottom: 20px;
- display: flex;
-}
-
-.ui-chat-message-row--user {
- justify-content: flex-end;
-}
-
-.ui-chat-message-row--assistant {
- justify-content: flex-start;
-}
-
-.ui-chat-message-bubble {
- max-width: 75%;
- padding: 14px 17px;
- border-radius: 16px;
- font-size: var(--ui-font-size-md);
- line-height: var(--ui-text-line-height);
- white-space: pre-wrap;
- overflow-wrap: break-word;
- box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
-}
-
-.ui-chat-message-bubble--user {
- background: var(--ui-primary);
- color: #fff;
-}
-
-.ui-chat-message-bubble--assistant {
- background: color-mix(in srgb, var(--ui-bg-strong) 72%, var(--ui-bg-elevated));
- color: var(--ui-text);
- border: 1px solid var(--ui-border);
-}
-
-.ui-chat-message-caret {
- display: inline-block;
- width: 8px;
- height: 16px;
- margin-left: 2px;
- vertical-align: middle;
- background: var(--ui-primary);
- animation: blink 1s infinite;
-}
-
-.ui-chat-input-panel {
- flex: 0 0 var(--ui-chat-bottom-height);
- height: var(--ui-chat-bottom-height);
- min-height: var(--ui-chat-bottom-height);
- padding: 16px 24px calc(16px + env(safe-area-inset-bottom, 0px));
- border-top: 1px solid var(--ui-border);
- background:
- linear-gradient(180deg, color-mix(in srgb, var(--ui-bg-strong) 72%, transparent), transparent 140%),
- var(--ui-bg);
- box-shadow: inset 0 1px 0 color-mix(in srgb, white 34%, transparent);
-}
-
-html[data-theme="dark"] .ui-chat-input-panel {
- box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04);
-}
-
-.ui-chat-input-panel .ui-inline {
- align-items: flex-end;
-}
-
-.ui-chat-input-panel .ui-textarea {
- min-height: 56px;
- max-height: 180px;
- padding-top: 12px !important;
- padding-bottom: 12px !important;
-}
-
-.ui-chat-input-panel .ui-button {
- min-height: 56px !important;
- height: 56px !important;
- padding-inline: 20px !important;
-}
-
-.ui-chat-test-panel {
- flex: 1;
- min-height: 0;
- max-height: 100%;
- overflow: auto;
- -webkit-overflow-scrolling: touch;
- overscroll-behavior: contain;
- align-content: start;
- padding: 24px;
-}
-
-.ui-chat-test-grid {
- display: grid;
- gap: 12px;
-}
-
-.ui-chat-empty {
- height: 100%;
- color: #cbd5e1;
- font-size: var(--ui-font-size-lg);
- display: grid;
- place-items: center;
-}
-
-.ui-chat-empty-icon {
- font-size: clamp(40px, 6vw, 48px);
- margin-bottom: 16px;
- opacity: 0.3;
-}
-
-@media (max-width: 1080px) {
- .ui-layout-chat {
- flex-direction: column;
- }
-
- .ui-layout-chat .ui-sidebar {
- width: 100%;
- min-width: 0;
- border-right: none;
- border-bottom: 1px solid var(--ui-border);
- max-height: 34dvh;
- }
-}
-
-@media (max-width: 720px) {
- :root {
- --ui-control-height: 44px;
- }
-
- .ui-page {
- min-width: 0;
- }
-
- .ui-section,
- .ui-card,
- .ui-surface {
- min-width: 0;
- }
-
- .ui-action-bar,
- .ui-toolbar {
- align-items: stretch;
- }
-
- .ui-action-bar > :where(.ui-field, .ui-input, .ui-select, .ui-button, button, div, input:not([type="checkbox"]):not([type="radio"]), select),
- .ui-toolbar > * {
- min-width: 0;
- }
-
- .ui-action-bar > :where(.ui-field, .ui-input, .ui-select, .ui-button, button, div, input:not([type="checkbox"]):not([type="radio"]), select),
- .ui-toolbar > * {
- flex: 1 1 100%;
- }
-
- .ui-action-bar .ui-spacer {
- margin-left: 0;
- }
-
- .ui-field[data-orientation="inline"] {
- grid-template-columns: 1fr;
- }
-
- .ui-tabbar {
- align-items: stretch;
- }
-
- .ui-tabbar .ui-tab,
- .ui-tabbar .ui-muted {
- flex: 1 1 auto;
- }
-
- .ui-chat-topbar,
- .ui-chat-settings,
- .ui-chat-messages,
- .ui-chat-test-panel,
- .ui-chat-footer,
- .ui-chat-input-panel {
- flex-basis: auto;
- height: auto;
- padding-left: 14px;
- padding-right: 14px;
- }
-
- .ui-chat-topbar .ui-select,
- .ui-chat-topbar .ui-button {
- flex: 1 1 calc(50% - var(--ui-control-gap));
- max-width: none;
- }
-
- .ui-chat-topbar .ui-spacer {
- flex: 1 1 100%;
- margin-left: 0;
- min-height: auto !important;
- }
-
- .ui-chat-input-panel .ui-textarea,
- .ui-chat-input-panel .ui-button {
- flex: 1 1 100%;
- }
-
- .ui-chat-message-bubble {
- max-width: 92%;
- }
-
- .ui-dialog {
- padding: 18px;
- }
-}
diff --git a/oneapi-gateway/shared-ui/src/theme.tsx b/oneapi-gateway/shared-ui/src/theme.tsx
deleted file mode 100644
index 8ed2d85..0000000
--- a/oneapi-gateway/shared-ui/src/theme.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-import { createContext, useContext, useEffect, useMemo, useState } from "react";
-import { Button } from "./components";
-
-export type ThemeMode = "light" | "dark" | "system";
-export type ThemeValue = "light" | "dark";
-
-type ThemeContextValue = {
- theme: ThemeMode;
- resolvedTheme: ThemeValue;
- setTheme: (theme: ThemeMode) => void;
- toggleTheme: () => void;
-};
-
-const STORAGE_KEY = "easyai-ui-theme";
-
-const ThemeContext = createContext(null);
-
-function getSystemTheme(): ThemeValue {
- if (typeof window === "undefined") return "light";
- return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
-}
-
-function getInitialTheme(defaultTheme: ThemeMode): ThemeMode {
- if (typeof window === "undefined") return defaultTheme;
- try {
- const stored = window.localStorage.getItem(STORAGE_KEY);
- if (stored === "light" || stored === "dark" || stored === "system") {
- return stored;
- }
- } catch {
- // Ignore storage errors.
- }
- return defaultTheme;
-}
-
-function applyTheme(theme: ThemeMode, resolvedTheme: ThemeValue) {
- if (typeof document === "undefined") return;
- document.documentElement.dataset.theme = resolvedTheme;
- document.documentElement.style.colorScheme = resolvedTheme;
- document.documentElement.dataset.themeMode = theme;
-}
-
-export function ThemeProvider(props: {
- children: React.ReactNode;
- defaultTheme?: ThemeMode;
-}) {
- const defaultTheme = props.defaultTheme ?? "system";
- const [theme, setThemeState] = useState(() => getInitialTheme(defaultTheme));
- const [systemTheme, setSystemTheme] = useState(() => getSystemTheme());
-
- useEffect(() => {
- const media = window.matchMedia("(prefers-color-scheme: dark)");
- const onChange = () => setSystemTheme(media.matches ? "dark" : "light");
- onChange();
- media.addEventListener("change", onChange);
- return () => media.removeEventListener("change", onChange);
- }, []);
-
- const resolvedTheme = theme === "system" ? systemTheme : theme;
-
- useEffect(() => {
- applyTheme(theme, resolvedTheme);
- try {
- window.localStorage.setItem(STORAGE_KEY, theme);
- } catch {
- // Ignore storage errors.
- }
- }, [resolvedTheme, theme]);
-
- const value = useMemo(
- () => ({
- theme,
- resolvedTheme,
- setTheme: (nextTheme) => setThemeState(nextTheme),
- toggleTheme: () => setThemeState((current) => (current === "dark" ? "light" : "dark")),
- }),
- [resolvedTheme, theme],
- );
-
- return {props.children};
-}
-
-export function useTheme() {
- const value = useContext(ThemeContext);
- if (!value) {
- throw new Error("useTheme must be used within ThemeProvider");
- }
- return value;
-}
-
-export function ThemeToggle(props: { className?: string; compact?: boolean }) {
- const { resolvedTheme, toggleTheme } = useTheme();
- return (
-
- );
-}
diff --git a/oneapi-gateway/src/auth.ts b/oneapi-gateway/src/auth.ts
index a5e5fcd..70542c4 100644
--- a/oneapi-gateway/src/auth.ts
+++ b/oneapi-gateway/src/auth.ts
@@ -2,7 +2,7 @@ import { sha256Hex } from "./crypto.js";
import type { Config } from "./config.js";
export type AuthContext = {
- /** Stable identity used to scope conversations and batches. */
+ /** Stable identity used for rate limiting and batch ownership. */
principal: string;
/**
* true -> the gateway authenticates the key itself and talks to LiteLLM with the master key
diff --git a/oneapi-gateway/src/chat.ts b/oneapi-gateway/src/chat.ts
deleted file mode 100644
index d4532f3..0000000
--- a/oneapi-gateway/src/chat.ts
+++ /dev/null
@@ -1,285 +0,0 @@
-import type { FastifyInstance } from "fastify";
-import { randomUUID } from "node:crypto";
-import { Readable } from "node:stream";
-import type { Config } from "./config.js";
-import type { Db, ConversationRow } from "./db.js";
-import { createConversation, listConversations, getConversation, updateConversationTitle, touchConversation, deleteConversation, insertMessage, listMessages } from "./db.js";
-import { authenticate, type AuthContext } from "./auth.js";
-
-function authHeaderFromRequest(req: any): string {
- const h = req.headers["authorization"] ?? req.headers["x-api-key"];
- return h ? String(Array.isArray(h) ? h[0] : h) : "";
-}
-
-function parseSseDataEvents(buffer: string): string[] {
- return buffer
- .replace(/\r\n/g, "\n")
- .replace(/\r/g, "\n")
- .split("\n\n")
- .map((event) =>
- event
- .split("\n")
- .map((line) => line.trim())
- .filter((line) => line.startsWith("data:"))
- .map((line) => line.slice(5).trimStart())
- .join("\n"),
- )
- .filter(Boolean);
-}
-
-function extractAssistantContent(sseText: string): { content: string; promptTokens: number; completionTokens: number } {
- let content = "";
- let promptTokens = 0;
- let completionTokens = 0;
-
- for (const dataText of parseSseDataEvents(sseText)) {
- if (dataText === "[DONE]") continue;
- try {
- const j = JSON.parse(dataText);
- const delta = j?.choices?.[0]?.delta?.content;
- if (typeof delta === "string") content += delta;
- if (j?.usage) {
- promptTokens = j.usage.prompt_tokens ?? 0;
- completionTokens = j.usage.completion_tokens ?? 0;
- }
- } catch {}
- }
- return { content, promptTokens, completionTokens };
-}
-
-export async function registerChatRoutes(app: FastifyInstance, cfg: Config, db: Db): Promise {
- app.addHook("onRequest", async (req, reply) => {
- const p = (req.url.split("?")[0] ?? req.url) as string;
- if (!p.startsWith("/chat-api/")) return;
- try {
- (req as any).authContext = authenticate(cfg, req.headers as any);
- } catch {
- return reply.status(401).send({ error: { message: "unauthorized", type: "auth_error" } });
- }
- });
-
- app.get("/chat-api/models", async (req, reply) => {
- const clientAuthHeader = authHeaderFromRequest(req);
- const injectRes = await app.inject({
- method: "GET",
- url: "/v1/models",
- headers: {
- authorization: clientAuthHeader,
- },
- });
- reply.status(injectRes.statusCode);
- const contentType = injectRes.headers["content-type"];
- if (contentType) reply.header("content-type", String(contentType));
- const payload = injectRes.body;
- if (!payload) return reply.send({});
- try {
- return reply.send(JSON.parse(payload));
- } catch {
- return reply.send(payload);
- }
- });
-
- app.get("/chat-api/conversations", async (req, reply) => {
- const auth = (req as any).authContext as AuthContext;
- const rows = await listConversations(db, auth.principal);
- return { conversations: rows };
- });
-
- app.post("/chat-api/conversations", async (req, reply) => {
- const auth = (req as any).authContext as AuthContext;
- const id = randomUUID();
- await createConversation(db, id, auth.principal);
- return { id };
- });
-
- app.delete("/chat-api/conversations/:id", async (req, reply) => {
- const auth = (req as any).authContext as AuthContext;
- const id = String((req.params as any).id ?? "");
- if (!id) return reply.status(400).send({ error: { message: "invalid id", type: "invalid_request_error" } });
- const r = await deleteConversation(db, id, auth.principal);
- if (r === "not_found") return reply.status(404).send({ error: { message: "not found", type: "not_found" } });
- return { ok: true };
- });
-
- app.put("/chat-api/conversations/:id/title", async (req, reply) => {
- const auth = (req as any).authContext as AuthContext;
- const id = String((req.params as any).id ?? "");
- if (!id) return reply.status(400).send({ error: { message: "invalid id", type: "invalid_request_error" } });
- const body = (req.body ?? {}) as any;
- const title = String(body.title ?? "").trim().slice(0, 200);
- if (!title) return reply.status(400).send({ error: { message: "title is required", type: "invalid_request_error" } });
- const conv = await getConversation(db, id, auth.principal);
- if (!conv) return reply.status(404).send({ error: { message: "not found", type: "not_found" } });
- await updateConversationTitle(db, id, title);
- return { ok: true };
- });
-
- app.get("/chat-api/conversations/:id/messages", async (req, reply) => {
- const auth = (req as any).authContext as AuthContext;
- const id = String((req.params as any).id ?? "");
- if (!id) return reply.status(400).send({ error: { message: "invalid id", type: "invalid_request_error" } });
- const conv = await getConversation(db, id, auth.principal);
- if (!conv) return reply.status(404).send({ error: { message: "not found", type: "not_found" } });
- const messages = await listMessages(db, id);
- return { messages };
- });
-
- app.post("/chat-api/conversations/:id/chat", async (req, reply) => {
- const auth = (req as any).authContext as AuthContext;
- const id = String((req.params as any).id ?? "");
- if (!id) return reply.status(400).send({ error: { message: "invalid id", type: "invalid_request_error" } });
- const conv = await getConversation(db, id, auth.principal);
- if (!conv) return reply.status(404).send({ error: { message: "not found", type: "not_found" } });
-
- const body = (req.body ?? {}) as any;
- if (!body || typeof body !== "object") return reply.status(400).send({ error: { message: "invalid body", type: "invalid_request_error" } });
- if (typeof body.model !== "string" || !body.model.trim()) return reply.status(400).send({ error: { message: "model is required", type: "invalid_request_error" } });
- if (typeof body.message !== "string" || !body.message.trim()) return reply.status(400).send({ error: { message: "message is required", type: "invalid_request_error" } });
-
- const model = body.model.trim();
- const userMessage = body.message.trim();
- const temperature = typeof body.temperature === "number" ? body.temperature : undefined;
- const maxTokens = typeof body.max_tokens === "number" ? body.max_tokens : undefined;
-
- const userMsgId = randomUUID();
- await insertMessage(db, userMsgId, id, "user", userMessage, model, null, null);
- await touchConversation(db, id);
-
- const isFirstMessage = (conv as any).message_count === 0;
- if (isFirstMessage) {
- const title = userMessage.length > 60 ? userMessage.slice(0, 57) + "..." : userMessage;
- await updateConversationTitle(db, id, title);
- }
-
- const isStream = body.stream !== false;
-
- const history = await listMessages(db, id);
- const messages: Array<{ role: string; content: string }> = [];
- for (const msg of history) {
- if (msg.role === "system") continue;
- if (msg.id === userMsgId) continue;
- messages.push({ role: msg.role, content: msg.content });
- }
- messages.push({ role: "user", content: userMessage });
-
- const payload: Record = {
- model,
- messages,
- stream: isStream,
- };
- if (temperature !== undefined) payload.temperature = temperature;
- if (maxTokens !== undefined) payload.max_tokens = maxTokens;
-
- const clientAuthHeader = authHeaderFromRequest(req);
-
- if (!isStream) {
- const injectRes = await app.inject({
- method: "POST",
- url: "/v1/chat/completions",
- headers: {
- authorization: clientAuthHeader,
- "content-type": "application/json",
- },
- payload,
- });
-
- const status = injectRes.statusCode;
- reply.status(status);
- const contentType = injectRes.headers["content-type"];
- if (contentType) reply.header("content-type", String(contentType));
-
- const bodyText = injectRes.body;
- if (status >= 400) {
- return reply.send(bodyText || { error: { message: "upstream error", type: "gateway_error" } });
- }
-
- let parsed: any;
- try { parsed = JSON.parse(bodyText); } catch { parsed = null; }
-
- const assistantText = parsed?.choices?.[0]?.message?.content ?? "";
- const promptTokens = parsed?.usage?.prompt_tokens ?? 0;
- const completionTokens = parsed?.usage?.completion_tokens ?? 0;
-
- if (assistantText) {
- const assistantMsgId = randomUUID();
- await insertMessage(db, assistantMsgId, id, "assistant", assistantText, model, promptTokens || null, completionTokens || null);
- await touchConversation(db, id);
- }
-
- return reply.send(parsed ?? bodyText);
- }
-
- if (cfg.port <= 0) return reply.status(500).send({ error: { message: "streaming not available", type: "gateway_error" } });
-
- const upstreamAbort = new AbortController();
- reply.raw.on("close", () => {
- if (!reply.raw.writableEnded) upstreamAbort.abort();
- });
-
- const upstream = await fetch(`http://127.0.0.1:${cfg.port}/v1/chat/completions`, {
- method: "POST",
- headers: {
- authorization: clientAuthHeader,
- "content-type": "application/json",
- accept: "text/event-stream",
- },
- body: JSON.stringify(payload),
- signal: upstreamAbort.signal,
- });
-
- reply.status(upstream.status);
- const contentType = upstream.headers.get("content-type");
- if (contentType) reply.header("content-type", contentType);
- reply.header("cache-control", "no-store");
- reply.header("x-accel-buffering", "no");
-
- if (!upstream.body) {
- return reply.send(await upstream.text());
- }
-
- if (upstream.status >= 400) {
- const errText = await upstream.text();
- return reply.send(errText);
- }
-
- async function* streamGenerator() {
- const reader = upstream.body!.getReader();
- const decoder = new TextDecoder("utf-8");
- let responseText = "";
-
- try {
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- if (value) {
- const chunk = decoder.decode(value, { stream: true });
- responseText += chunk;
- yield Buffer.from(chunk);
- }
- }
- const final = decoder.decode();
- if (final) {
- responseText += final;
- yield Buffer.from(final);
- }
- } catch (err: any) {
- if (err?.name === "AbortError") return;
- throw err;
- } finally {
- reader.releaseLock();
-
- const isComplete = parseSseDataEvents(responseText).includes("[DONE]");
- if (isComplete) {
- const { content, promptTokens, completionTokens } = extractAssistantContent(responseText);
- if (content) {
- const assistantMsgId = randomUUID();
- await insertMessage(db, assistantMsgId, id, "assistant", content, model, promptTokens || null, completionTokens || null).catch(console.error);
- await touchConversation(db, id).catch(console.error);
- }
- }
- }
- }
-
- return reply.send(Readable.from(streamGenerator()));
- });
-}
diff --git a/oneapi-gateway/src/config.ts b/oneapi-gateway/src/config.ts
index 5f413cb..2acfd03 100644
--- a/oneapi-gateway/src/config.ts
+++ b/oneapi-gateway/src/config.ts
@@ -16,6 +16,8 @@ export type Config = {
litellmMasterKey: string;
/** Public URL of the LiteLLM console (`/ui`). */
consoleUrl?: string;
+ /** Public URL of the optional chat UI (Open WebUI). */
+ chatUrl?: string;
upstreamTimeoutMs: number;
rateLimitRpm: number;
corsOrigin: string | string[];
@@ -106,6 +108,7 @@ export function loadConfig(configPath = "/app/config/easyai.yaml"): Config {
}
const consoleUrl = app.console_url ? String(app.console_url) : undefined;
+ const chatUrl = app.chat_url ? String(app.chat_url) : undefined;
const upstreamTimeoutMs = Number(app.upstream_timeout_ms ?? 60000);
const rateLimitRpm = Number(app.rate_limit_rpm ?? 120);
const corsOrigin = "*";
@@ -129,6 +132,7 @@ export function loadConfig(configPath = "/app/config/easyai.yaml"): Config {
litellmBaseUrl,
litellmMasterKey,
consoleUrl,
+ chatUrl,
upstreamTimeoutMs,
rateLimitRpm,
corsOrigin,
diff --git a/oneapi-gateway/src/db.ts b/oneapi-gateway/src/db.ts
index afd77db..5a3ddea 100644
--- a/oneapi-gateway/src/db.ts
+++ b/oneapi-gateway/src/db.ts
@@ -17,8 +17,8 @@ export async function createDb(databaseUrl: string): Promise {
}
/**
- * EasyAI only owns chat history + batch bookkeeping.
- * API keys, tenants, spend and request logs live in LiteLLM.
+ * EasyAI only owns batch bookkeeping.
+ * API keys, budgets, spend and request logs live in LiteLLM.
*/
async function migrate(pool: pg.Pool): Promise {
await pool.query(`
@@ -49,30 +49,6 @@ async function migrate(pool: pg.Pool): Promise {
`);
await pool.query(`create index if not exists batch_items_batch_idx on batch_items(batch_id, idx);`);
- await pool.query(`
- create table if not exists conversations (
- id uuid primary key,
- title text not null default '',
- principal text not null,
- created_at timestamptz not null default now(),
- updated_at timestamptz not null default now()
- );
- `);
- await pool.query(`create index if not exists conversations_principal_idx on conversations(principal, updated_at desc);`);
-
- await pool.query(`
- create table if not exists messages (
- id uuid primary key,
- conversation_id uuid not null references conversations(id) on delete cascade,
- role text not null,
- content text not null,
- model text,
- prompt_tokens int,
- completion_tokens int,
- created_at timestamptz not null default now()
- );
- `);
- await pool.query(`create index if not exists messages_conversation_idx on messages(conversation_id, created_at asc);`);
}
export type BatchStatus = "queued" | "running" | "completed" | "failed";
@@ -143,107 +119,3 @@ export async function listBatchItems(
);
return res.rows;
}
-
-export type ConversationRow = {
- id: string;
- title: string;
- principal: string;
- created_at: string;
- updated_at: string;
- message_count: number;
-};
-
-export async function createConversation(db: Db, id: string, principal: string): Promise {
- await db.pool.query(`insert into conversations (id, title, principal) values ($1, $2, $3)`, [id, "", principal]);
-}
-
-export async function listConversations(db: Db, principal: string): Promise {
- const res = await db.pool.query(
- `
- select
- c.id, c.title, c.principal, c.created_at::text, c.updated_at::text,
- coalesce(msg_counts.cnt, 0)::int as message_count
- from conversations c
- left join (
- select conversation_id, count(*)::int as cnt from messages group by conversation_id
- ) msg_counts on msg_counts.conversation_id = c.id
- where c.principal = $1
- order by c.updated_at desc
- limit 100
- `,
- [principal],
- );
- return res.rows;
-}
-
-export async function getConversation(db: Db, id: string, principal: string): Promise {
- const res = await db.pool.query(
- `
- select
- c.id, c.title, c.principal, c.created_at::text, c.updated_at::text,
- coalesce(msg_counts.cnt, 0)::int as message_count
- from conversations c
- left join (
- select conversation_id, count(*)::int as cnt from messages group by conversation_id
- ) msg_counts on msg_counts.conversation_id = c.id
- where c.id = $1 and c.principal = $2
- limit 1
- `,
- [id, principal],
- );
- if (!res.rows?.length) return;
- return res.rows[0];
-}
-
-export async function updateConversationTitle(db: Db, id: string, title: string): Promise {
- await db.pool.query(`update conversations set title = $2, updated_at = now() where id = $1`, [id, title]);
-}
-
-export async function touchConversation(db: Db, id: string): Promise {
- await db.pool.query(`update conversations set updated_at = now() where id = $1`, [id]);
-}
-
-export async function deleteConversation(db: Db, id: string, principal: string): Promise<"deleted" | "not_found"> {
- const res = await db.pool.query(`delete from conversations where id = $1 and principal = $2`, [id, principal]);
- return res.rowCount === 1 ? "deleted" : "not_found";
-}
-
-export type MessageRow = {
- id: string;
- conversation_id: string;
- role: string;
- content: string;
- model: string | null;
- prompt_tokens: number | null;
- completion_tokens: number | null;
- created_at: string;
-};
-
-export async function insertMessage(
- db: Db,
- id: string,
- conversationId: string,
- role: string,
- content: string,
- model: string | null,
- promptTokens: number | null,
- completionTokens: number | null,
-): Promise {
- await db.pool.query(
- `insert into messages (id, conversation_id, role, content, model, prompt_tokens, completion_tokens) values ($1,$2,$3,$4,$5,$6,$7)`,
- [id, conversationId, role, content, model, promptTokens, completionTokens],
- );
-}
-
-export async function listMessages(db: Db, conversationId: string): Promise {
- const res = await db.pool.query(
- `
- select id, conversation_id, role, content, model, prompt_tokens, completion_tokens, created_at::text
- from messages
- where conversation_id = $1
- order by created_at asc
- `,
- [conversationId],
- );
- return res.rows;
-}
diff --git a/oneapi-gateway/src/index.ts b/oneapi-gateway/src/index.ts
index be62c83..788e2dc 100644
--- a/oneapi-gateway/src/index.ts
+++ b/oneapi-gateway/src/index.ts
@@ -6,7 +6,6 @@ import { createDb } from "./db.js";
import { registerProxyRoutes } from "./proxy.js";
import { registerUi } from "./ui.js";
import { registerBatchRoutes } from "./batch.js";
-import { registerChatRoutes } from "./chat.js";
const cfg = loadConfig();
@@ -71,7 +70,6 @@ await registerUi(app, cfg);
await registerProxyRoutes(app, { cfg, redis });
await registerBatchRoutes(app, cfg, db, redis);
-await registerChatRoutes(app, cfg, db);
await app.listen({ host: "0.0.0.0", port: cfg.port });
diff --git a/oneapi-gateway/src/ui-shell.ts b/oneapi-gateway/src/ui-shell.ts
deleted file mode 100644
index 2d82c53..0000000
--- a/oneapi-gateway/src/ui-shell.ts
+++ /dev/null
@@ -1,363 +0,0 @@
-type NavItem = "home" | "chat" | "docs" | "console";
-
-type GlobalNavOptions = {
- active: NavItem;
- consoleHref?: string;
-};
-
-function navLink(key: NavItem, active: NavItem, href: string, label: string): string {
- return `${label}`;
-}
-
-export function buildThemeInitScript(): string {
- return ``;
-}
-
-export function buildGlobalNav(options: GlobalNavOptions): string {
- const { active, consoleHref = "/ui" } = options;
- return `
-
-
-
-`;
-}
-
-export function injectGlobalNav(html: string, options: GlobalNavOptions): string {
- const withTheme = html.includes("window.EasyAITheme")
- ? html
- : html.replace(/]*)>/i, `${buildThemeInitScript()}`);
- if (withTheme.includes("data-easyai-global-nav")) return withTheme;
- return withTheme.replace(/]*)>/i, (_m, attrs) => {
- const bodyAttrs = String(attrs ?? "");
- if (/\bclass\s*=\s*["'][^"']*["']/i.test(bodyAttrs)) {
- return ` ` class=${q}${cls} easyai-page-${options.active}${q}`)}>${buildGlobalNav(options)}`;
- }
- return `${buildGlobalNav(options)}`;
- });
-}
diff --git a/oneapi-gateway/src/ui.ts b/oneapi-gateway/src/ui.ts
index 0438578..c8df503 100644
--- a/oneapi-gateway/src/ui.ts
+++ b/oneapi-gateway/src/ui.ts
@@ -1,202 +1,94 @@
import type { FastifyInstance } from "fastify";
-import fastifyStatic from "@fastify/static";
-import fs from "node:fs";
-import path from "node:path";
-import { fileURLToPath } from "node:url";
import type { Config } from "./config.js";
-import { buildGlobalNav, buildThemeInitScript } from "./ui-shell.js";
function buildHomeHtml(cfg: Config): string {
const consoleHref = cfg.consoleUrl ?? "/ui";
- const baseUrl = cfg.consoleUrl ? "" : "http://localhost:3004";
-
- const capabilities = [
- "统一 OpenAI-compatible 入口,屏蔽不同厂商的协议差异",
- "模型别名来自一份 YAML,换厂商不用改客户端代码",
- "内置控制台:密钥、预算、用量、日志与请求重放",
- "支持流式输出、内置聊天页和离线 Batch 批处理",
- "自动重试与故障转移、Redis 响应缓存、内容护栏",
- ];
-
- const steps = [
- {
- title: "1. 启动服务",
- body: "一条 compose 命令拉起网关、模型接入层与本地 Ollama。",
- hint: "docker compose up -d --build",
- },
- {
- title: "2. 发起请求",
- body: "用 YAML 里的 API Key 调用统一入口,模型名使用 YAML 中的别名。",
- hint: `curl ${baseUrl}/v1/chat/completions -H "Authorization: Bearer dev-key" ...`,
- },
- {
- title: "3. 管理密钥",
- body: "打开控制台创建/吊销密钥、设置预算与限流,界面右上角可切换中文。",
- hint: consoleHref,
- },
- ];
+ const chatHref = cfg.chatUrl ?? "/chat";
+ const gateway = "http://localhost:3004";
+ const deepseekNote = "把 providers.deepseek.api_key 和 models 填好后,客户端只需要改 model 名。";
return `
- ${buildThemeInitScript()}
-
-
- EasyAI · 统一 LLM 接入层
-
+
+
+EasyAI · 统一 LLM 接入层
+
- ${buildGlobalNav({ active: "home", consoleHref })}
-
-
- EasyAI · 统一 LLM 接入层
- 个人和小团队免费自部署。一个入口、一份 YAML,统一接入不同厂商的模型服务,模型接入与治理交给 LiteLLM。
-
-
-
-
- ${steps
- .map(
- (s) => `
${s.title}
${s.body}
${s.hint}`,
- )
- .join("\n")}
+
+
+ EasyAI · 统一 LLM 接入层
+ 一份 YAML 屏蔽不同厂商的协议差异。网关只做入口与限流,模型接入、缓存、护栏、密钥与用量交给 LiteLLM。
+
+
-
- 能做什么
-
- ${capabilities.map((c) => `- ${c}
`).join("\n ")}
-
-
+
+ 三步上手
+
+ - 启动:
docker compose up -d --build
+ - 拉模型:
docker compose exec -T ollama ollama pull qwen2.5:0.5b
+ - 发请求(默认 key
dev-key):
+
+ curl ${gateway}/v1/chat/completions \\
+ -H "Authorization: Bearer dev-key" \\
+ -H "Content-Type: application/json" \\
+ -d '{"model":"chat","messages":[{"role":"user","content":"hello"}]}'
+
-
-
+
+ 换成任意厂商
+ ${deepseekNote}模型接入能力由 LiteLLM 提供(OpenAI、Anthropic、Gemini、DeepSeek、Bedrock、Ollama 等 100+)。
+
+
`;
}
export async function registerUi(app: FastifyInstance, cfg: Config): Promise
{
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
app.get("/", async (_req, reply) => {
reply.type("text/html; charset=utf-8");
return reply.send(buildHomeHtml(cfg));
});
- const redirectToConsole = async (_req: any, reply: any) => {
- if (!cfg.consoleUrl) {
- return reply
- .status(503)
- .type("text/plain; charset=utf-8")
- .send("控制台未配置:请在 YAML 的 app.console_url 填写 LiteLLM 控制台地址,例如 http://localhost:3005/ui");
- }
- return reply.redirect(cfg.consoleUrl, 302);
+ const redirect = (target: string | undefined, hint: string) => async (_req: any, reply: any) => {
+ if (!target) return reply.status(503).type("text/plain; charset=utf-8").send(hint);
+ return reply.redirect(target, 302);
};
- // The console is LiteLLM's own Admin UI (keys / budgets / spend / logs).
- app.get("/ui", redirectToConsole);
- app.get("/dashboard", redirectToConsole);
-
- const chatRoot = path.resolve(__dirname, "../chat-ui/dist");
- if (fs.existsSync(chatRoot)) {
- const assetsRoot = path.join(chatRoot, "assets");
- if (fs.existsSync(assetsRoot)) {
- await app.register(fastifyStatic, { root: assetsRoot, prefix: "/chat/assets/" });
- }
-
- const sendChat = async (_req: any, reply: any) => {
- const html = fs.readFileSync(path.join(chatRoot, "index.html"), "utf8");
- reply.type("text/html; charset=utf-8");
- return reply.send(
- injectNav(html, { active: "chat", consoleHref: cfg.consoleUrl ?? "/ui" }),
- );
- };
-
- app.get("/chat", sendChat);
- app.get("/chat/*", sendChat);
- } else {
- app.get("/chat", async (_req, reply) => reply.status(503).send("Chat UI not built"));
- }
-}
-
-function injectNav(html: string, options: { active: "chat"; consoleHref: string }): string {
- const withTheme = html.includes("window.EasyAITheme")
- ? html
- : html.replace(/]*)>/i, `${buildThemeInitScript()}`);
- if (withTheme.includes("data-easyai-global-nav")) return withTheme;
- return withTheme.replace(/]*)>/i, (_m, attrs) => {
- const bodyAttrs = String(attrs ?? "");
- if (/\bclass\s*=\s*["'][^"']*["']/i.test(bodyAttrs)) {
- return ` ` class=${q}${cls} easyai-page-${options.active}${q}`,
- )}>${buildGlobalNav(options)}`;
- }
- return `${buildGlobalNav(options)}`;
- });
+ app.get(
+ "/ui",
+ redirect(cfg.consoleUrl, "控制台未配置:请在 YAML 的 app.console_url 填写 LiteLLM 控制台地址,例如 http://localhost:3005/ui"),
+ );
+ app.get("/dashboard", redirect(cfg.consoleUrl, "控制台未配置:请在 YAML 的 app.console_url 填写 LiteLLM 控制台地址"));
+ app.get(
+ "/chat",
+ redirect(cfg.chatUrl, "聊天界面未配置:docker compose --profile chat up -d 启动 Open WebUI,并设置 app.chat_url"),
+ );
}
diff --git a/oneapi-gateway/test/chat-ui-id.test.ts b/oneapi-gateway/test/chat-ui-id.test.ts
deleted file mode 100644
index 2778073..0000000
--- a/oneapi-gateway/test/chat-ui-id.test.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-import { createClientId } from "../chat-ui/src/ui/id.ts";
-
-test("chat ui: creates client ids when crypto.randomUUID is unavailable", () => {
- const originalCrypto = Object.getOwnPropertyDescriptor(globalThis, "crypto");
- Object.defineProperty(globalThis, "crypto", {
- configurable: true,
- value: undefined,
- });
-
- try {
- const id = createClientId();
- assert.match(id, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
- } finally {
- if (originalCrypto) Object.defineProperty(globalThis, "crypto", originalCrypto);
- }
-});
diff --git a/oneapi-gateway/test/chat-ui-message-load.test.ts b/oneapi-gateway/test/chat-ui-message-load.test.ts
deleted file mode 100644
index 2830a4c..0000000
--- a/oneapi-gateway/test/chat-ui-message-load.test.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-import { shouldApplyLoadedMessages } from "../chat-ui/src/ui/messageLoad.ts";
-
-test("chat ui: ignores stale message loads while a send is streaming", () => {
- assert.equal(shouldApplyLoadedMessages({
- requestSeq: 1,
- currentSeq: 2,
- requestedConversationId: "c1",
- currentConversationId: "c1",
- isStreaming: false,
- }), false);
-
- assert.equal(shouldApplyLoadedMessages({
- requestSeq: 2,
- currentSeq: 2,
- requestedConversationId: "c1",
- currentConversationId: "c1",
- isStreaming: true,
- }), false);
-
- assert.equal(shouldApplyLoadedMessages({
- requestSeq: 2,
- currentSeq: 2,
- requestedConversationId: "c1",
- currentConversationId: "c2",
- isStreaming: false,
- }), false);
-
- assert.equal(shouldApplyLoadedMessages({
- requestSeq: 2,
- currentSeq: 2,
- requestedConversationId: "c1",
- currentConversationId: "c1",
- isStreaming: false,
- }), true);
-});
diff --git a/oneapi-gateway/test/chat-ui-stream.test.ts b/oneapi-gateway/test/chat-ui-stream.test.ts
deleted file mode 100644
index 153ba38..0000000
--- a/oneapi-gateway/test/chat-ui-stream.test.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-import { parseSseDataEvents } from "../chat-ui/src/ui/stream.ts";
-
-test("chat ui: parses SSE data events without requiring a space after data colon", () => {
- const first = parseSseDataEvents('data:{"choices":[{"delta":{"content":"he"}}]}\n\n');
- assert.deepEqual(first, {
- dataEvents: ['{"choices":[{"delta":{"content":"he"}}]}'],
- rest: "",
- });
-
- const split = parseSseDataEvents('data: {"choices":[{"delta":{"content":"l');
- assert.deepEqual(split, {
- dataEvents: [],
- rest: 'data: {"choices":[{"delta":{"content":"l',
- });
-
- const finished = parseSseDataEvents(`${split.rest}lo"}}]}\n\ndata:[DONE]\n\n`);
- assert.deepEqual(finished, {
- dataEvents: ['{"choices":[{"delta":{"content":"llo"}}]}', "[DONE]"],
- rest: "",
- });
-});
diff --git a/oneapi-gateway/test/chat.api.test.ts b/oneapi-gateway/test/chat.api.test.ts
deleted file mode 100644
index 20ee2d4..0000000
--- a/oneapi-gateway/test/chat.api.test.ts
+++ /dev/null
@@ -1,274 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-import Fastify from "fastify";
-import { registerChatRoutes } from "../src/chat.js";
-import { registerProxyRoutes } from "../src/proxy.js";
-import type { Config } from "../src/config.js";
-
-class FakeRedis {
- private readonly kv = new Map();
- private readonly counters = new Map();
- async connect() {}
- async disconnect() {}
- on() {}
- async get(k: string) {
- return this.kv.get(k) ?? null;
- }
- async set(k: string, v: string) {
- this.kv.set(k, v);
- return "OK";
- }
- async incr(k: string) {
- const v = (this.counters.get(k) ?? 0) + 1;
- this.counters.set(k, v);
- return v;
- }
- async incrBy(k: string, by: number) {
- const v = (this.counters.get(k) ?? 0) + by;
- this.counters.set(k, v);
- return v;
- }
- async expire() {
- return 1;
- }
-}
-
-class MemoryChatDb {
- readonly conversations = new Map();
- readonly messages: any[] = [];
- readonly pool = {
- query: async (sql: string, params: any[] = []) => this.query(sql, params),
- };
- async close() {}
-
- private async query(sql: string, params: any[]) {
- if (sql.includes("insert into conversations")) {
- const [id, title, principal, tenantId] = params;
- this.conversations.set(id, {
- id,
- title,
- principal,
- tenant_id: tenantId,
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString(),
- });
- return { rows: [], rowCount: 1 };
- }
-
- if (sql.includes("from conversations c") && sql.includes("where c.id = $1")) {
- const [id, principal] = params;
- const row = this.conversations.get(id);
- if (!row || row.principal !== principal) return { rows: [] };
- return {
- rows: [{
- ...row,
- message_count: this.messages.filter((m) => m.conversation_id === id).length,
- }],
- };
- }
-
- if (sql.includes("from conversations c") && sql.includes("where c.principal = $1")) {
- const [principal] = params;
- return {
- rows: Array.from(this.conversations.values())
- .filter((row) => row.principal === principal)
- .map((row) => ({
- ...row,
- message_count: this.messages.filter((m) => m.conversation_id === row.id).length,
- })),
- };
- }
-
- if (sql.includes("update conversations set title")) {
- const [id, title] = params;
- const row = this.conversations.get(id);
- if (row) row.title = title;
- return { rows: [], rowCount: row ? 1 : 0 };
- }
-
- if (sql.includes("update conversations set updated_at")) {
- const [id] = params;
- const row = this.conversations.get(id);
- if (row) row.updated_at = new Date().toISOString();
- return { rows: [], rowCount: row ? 1 : 0 };
- }
-
- if (sql.includes("insert into messages")) {
- const [id, conversationId, role, content, model, promptTokens, completionTokens] = params;
- this.messages.push({
- id,
- conversation_id: conversationId,
- role,
- content,
- model,
- prompt_tokens: promptTokens,
- completion_tokens: completionTokens,
- created_at: new Date().toISOString(),
- });
- return { rows: [], rowCount: 1 };
- }
-
- if (sql.includes("from messages") && sql.includes("where conversation_id = $1")) {
- const [conversationId] = params;
- return { rows: this.messages.filter((m) => m.conversation_id === conversationId) };
- }
-
- if (sql.includes("insert into usage_events")) return { rows: [], rowCount: 1 };
- if (sql.includes("from api_keys")) return { rows: [] };
- if (sql.includes("from tenants")) return { rows: [] };
-
- throw new Error(`unexpected query: ${sql}`);
- }
-}
-
-function makeConfig(overrides: Partial = {}): Config {
- return {
- appEnv: "test",
- port: 0,
- logLevel: "info",
- trustProxy: false,
- apiKeys: new Set(["k1"]),
- litellmBaseUrl: "http://u",
- litellmMasterKey: "sk-test-master",
- upstreamTimeoutMs: 2000,
- rateLimitRpm: 1000,
- corsOrigin: "*",
- internalToken: undefined,
- redisUrl: "redis://fake",
- databaseUrl: "postgres://fake",
- ...overrides,
- };
-}
-
-test("chat api: streams assistant response and persists it", async () => {
- const upstream = Fastify();
- upstream.post("/v1/chat/completions", async (_req, reply) => {
- reply.header("content-type", "text/event-stream");
- return reply.send([
- 'data: {"choices":[{"delta":{"content":"hello"}}]}',
- "",
- 'data: {"choices":[{"delta":{"content":" world"}}],"usage":{"prompt_tokens":2,"completion_tokens":3,"total_tokens":5}}',
- "",
- "data: [DONE]",
- "",
- ].join("\n"));
- });
- await upstream.listen({ host: "127.0.0.1", port: 0 });
- const upstreamAddr = upstream.server.address();
- assert.ok(upstreamAddr && typeof upstreamAddr === "object");
- const upstreamUrl = `http://127.0.0.1:${upstreamAddr.port}`;
-
- const app = Fastify({ logger: false });
- try {
- const cfg = makeConfig({ litellmBaseUrl: upstreamUrl });
- const redis = new FakeRedis() as any;
- const db = new MemoryChatDb() as any;
-
- await registerProxyRoutes(app, { cfg, redis });
- await registerChatRoutes(app, cfg, db);
-
- await app.listen({ host: "127.0.0.1", port: 0 });
- const appAddr = app.server.address();
- assert.ok(appAddr && typeof appAddr === "object");
- cfg.port = appAddr.port;
- const baseUrl = `http://127.0.0.1:${appAddr.port}`;
-
- const created = await fetch(`${baseUrl}/chat-api/conversations`, {
- method: "POST",
- headers: { authorization: "Bearer k1" },
- });
- const createdText = await created.text();
- assert.equal(created.status, 200, createdText);
- const createdJson: any = JSON.parse(createdText);
-
- const chat = await fetch(`${baseUrl}/chat-api/conversations/${createdJson.id}/chat`, {
- method: "POST",
- headers: {
- authorization: "Bearer k1",
- "content-type": "application/json",
- accept: "text/event-stream",
- },
- body: JSON.stringify({ model: "chat", message: "hi", stream: true }),
- });
-
- const text = await chat.text();
- assert.equal(chat.status, 200, text);
- assert.match(String(chat.headers.get("content-type")), /text\/event-stream/);
- assert.equal(text.includes("hello"), true, text);
- assert.equal(text.includes(" world"), true, text);
- assert.equal(text.includes("data: [DONE]"), true);
-
- await new Promise((resolve) => setTimeout(resolve, 20));
- assert.equal(db.messages.filter((m: any) => m.role === "user").length, 1);
- const assistant = db.messages.find((m: any) => m.role === "assistant");
- assert.equal(assistant?.content, "hello world");
- } finally {
- await app.close();
- await upstream.close();
- }
-});
-
-test("chat api: persists stream chunks that use data colon without a space", async () => {
- const upstream = Fastify();
- upstream.post("/v1/chat/completions", async (_req, reply) => {
- reply.header("content-type", "text/event-stream");
- return reply.send([
- 'data:{"choices":[{"delta":{"content":"no"}}]}',
- "",
- 'data:{"choices":[{"delta":{"content":" space"}}],"usage":{"prompt_tokens":1,"completion_tokens":2,"total_tokens":3}}',
- "",
- "data:[DONE]",
- "",
- ].join("\n"));
- });
- await upstream.listen({ host: "127.0.0.1", port: 0 });
- const upstreamAddr = upstream.server.address();
- assert.ok(upstreamAddr && typeof upstreamAddr === "object");
- const upstreamUrl = `http://127.0.0.1:${upstreamAddr.port}`;
-
- const app = Fastify({ logger: false });
- try {
- const cfg = makeConfig({ litellmBaseUrl: upstreamUrl });
- const redis = new FakeRedis() as any;
- const db = new MemoryChatDb() as any;
-
- await registerProxyRoutes(app, { cfg, redis });
- await registerChatRoutes(app, cfg, db);
-
- await app.listen({ host: "127.0.0.1", port: 0 });
- const appAddr = app.server.address();
- assert.ok(appAddr && typeof appAddr === "object");
- cfg.port = appAddr.port;
- const baseUrl = `http://127.0.0.1:${appAddr.port}`;
-
- const created = await fetch(`${baseUrl}/chat-api/conversations`, {
- method: "POST",
- headers: { authorization: "Bearer k1" },
- });
- const createdJson: any = await created.json();
-
- const chat = await fetch(`${baseUrl}/chat-api/conversations/${createdJson.id}/chat`, {
- method: "POST",
- headers: {
- authorization: "Bearer k1",
- "content-type": "application/json",
- accept: "text/event-stream",
- },
- body: JSON.stringify({ model: "chat", message: "hi", stream: true }),
- });
-
- const text = await chat.text();
- assert.equal(chat.status, 200, text);
- assert.equal(text.includes("no"), true, text);
- assert.equal(text.includes(" space"), true, text);
-
- await new Promise((resolve) => setTimeout(resolve, 20));
- const assistant = db.messages.find((m: any) => m.role === "assistant");
- assert.equal(assistant?.content, "no space");
- assert.equal(assistant?.prompt_tokens, 1);
- assert.equal(assistant?.completion_tokens, 2);
- } finally {
- await app.close();
- await upstream.close();
- }
-});
diff --git a/scripts/render-local-compose.py b/scripts/render-local-compose.py
index e7ceb0c..ad25cdb 100644
--- a/scripts/render-local-compose.py
+++ b/scripts/render-local-compose.py
@@ -17,6 +17,29 @@ def read_postgres_password(config_path: Path) -> str:
return ""
+def read_first_api_key(config_path: Path) -> str:
+ in_secrets = False
+ in_api_keys = False
+ for raw in config_path.read_text(encoding="utf-8").splitlines():
+ if raw.strip() == "secrets:":
+ in_secrets = True
+ continue
+ if in_secrets and raw and not raw.startswith(" "):
+ in_secrets = False
+ in_api_keys = False
+ if not in_secrets:
+ continue
+ stripped = raw.strip()
+ if stripped.startswith("api_keys:"):
+ in_api_keys = True
+ continue
+ if in_api_keys and stripped.startswith("-"):
+ return stripped.lstrip("- ").strip().strip("'\"")
+ if in_api_keys and stripped and not stripped.startswith("-"):
+ in_api_keys = False
+ return ""
+
+
def main() -> int:
config_path = Path(sys.argv[1] if len(sys.argv) > 1 else "config/easyai.production.local.yaml")
if not config_path.exists():
@@ -28,6 +51,11 @@ def main() -> int:
print("missing secrets.postgres_password", file=sys.stderr)
return 1
+ api_key = read_first_api_key(config_path)
+ if not api_key:
+ print("missing secrets.api_keys", file=sys.stderr)
+ return 1
+
cfg = config_path.as_posix()
print(
f"""name: easyai-prod
@@ -51,7 +79,14 @@ def main() -> int:
volumes:
- ./{cfg}:/app/config/easyai.yaml:ro
+ openwebui:
+ environment:
+ OPENAI_API_KEY: "{api_key}"
+ WEBUI_AUTH: "true"
+
volumes:
+ openwebui_data:
+ name: easyai_prod_openwebui_data
postgres_data:
name: easyai_prod_postgres_data
ollama_data:
diff --git a/scripts/reset-db.sh b/scripts/reset-db.sh
index 980860d..c961904 100755
--- a/scripts/reset-db.sh
+++ b/scripts/reset-db.sh
@@ -4,7 +4,6 @@ set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
compose_file="${COMPOSE_FILE:-$root/docker-compose.yml}"
-mode="app"
with_redis="false"
assume_yes="false"
@@ -14,36 +13,25 @@ usage() {
./scripts/reset-db.sh [选项]
说明:
- 一键清空当前项目的数据库数据,仅作用于 docker-compose.yml 中的 Postgres/Redis。
- 不会删除 Ollama 模型卷,不会删除源码或配置文件。
+ 清空 EasyAI 的业务数据(batch 表)。LiteLLM 的密钥/用量数据在它自己的表里,
+ 需要清理请使用控制台或直接操作数据库。
选项:
- --usage-only 仅清空 conversations / messages 会话表
- --all 清空 OneAPI 业务表(默认)
--with-redis 同时清空 Redis 缓存和限流计数
--yes, -y 跳过确认提示
--help, -h 显示帮助
默认清空的表:
- batch_items, batches, conversations, messages
+ batch_items, batches
示例:
./scripts/reset-db.sh
- ./scripts/reset-db.sh --usage-only
- ./scripts/reset-db.sh --all --with-redis --yes
+ ./scripts/reset-db.sh --with-redis --yes
EOF
}
while [[ $# -gt 0 ]]; do
case "$1" in
- --usage-only)
- mode="usage"
- shift
- ;;
- --all)
- mode="app"
- shift
- ;;
--with-redis)
with_redis="true"
shift
@@ -80,14 +68,8 @@ if ! docker compose "${compose_args[@]}" ps postgres >/dev/null 2>&1; then
exit 1
fi
-if [[ "$mode" == "usage" ]]; then
- sql="TRUNCATE TABLE messages, conversations RESTART IDENTITY CASCADE;"
- summary="仅清空会话与消息"
-else
- sql="TRUNCATE TABLE batch_items, batches, messages, conversations RESTART IDENTITY CASCADE;"
- summary="清空 batches、batch_items、messages、conversations"
-fi
-
+sql="TRUNCATE TABLE batch_items, batches RESTART IDENTITY CASCADE;"
+summary="清空 batches、batch_items"
if [[ "$with_redis" == "true" ]]; then
summary="$summary,并清空 Redis"
fi
diff --git a/scripts/test-all.sh b/scripts/test-all.sh
index 1a48244..54ddcd2 100755
--- a/scripts/test-all.sh
+++ b/scripts/test-all.sh
@@ -6,31 +6,26 @@ export NODE_OPTIONS="${NODE_OPTIONS---no-deprecation}"
export NPM_CONFIG_FUND="${NPM_CONFIG_FUND-false}"
export NPM_CONFIG_AUDIT="${NPM_CONFIG_AUDIT-false}"
-echo "[1/5] oneapi-gateway: tests + doc-audit"
+echo "[1/4] oneapi-gateway: tests + doc-audit"
cd "$root/oneapi-gateway"
npm ci --no-fund --no-audit
npm run build
npm test
npm run doc-audit
-echo "[2/5] chat-ui: build"
-cd "$root/oneapi-gateway/chat-ui"
-npm ci --no-fund --no-audit
-npm run build
-
-echo "[3/5] batch-worker: build"
+echo "[2/4] batch-worker: build"
cd "$root/batch-worker"
npm ci --no-fund --no-audit
npm run build
-echo "[4/5] litellm config render"
+echo "[3/4] litellm config render"
cd "$root"
python3 scripts/render-litellm-config.py config/easyai.development.yaml >/dev/null
python3 scripts/render-litellm-config.py --print-master-key config/easyai.development.yaml >/dev/null
python3 scripts/render-litellm-config.py --print-database-url config/easyai.development.yaml >/dev/null
python3 scripts/render-litellm-config.py --print-salt-key config/easyai.development.yaml >/dev/null
-echo "[5/5] compose smoke: hard gate"
+echo "[4/4] compose smoke: hard gate"
cleanup() {
docker compose -f "$root/docker-compose.yml" down -v >/dev/null 2>&1 || true
}
diff --git a/tools/mock-upstream/server.ts b/tools/mock-upstream/server.ts
deleted file mode 100644
index dd0cff3..0000000
--- a/tools/mock-upstream/server.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import http from "node:http";
-
-const port = Number(process.env.PORT ?? "18081");
-const status = Number(process.env.STATUS ?? "200");
-const mode = String(process.env.MODE ?? "ok");
-
-function readBody(req: http.IncomingMessage): Promise {
- return new Promise((resolve) => {
- const chunks: Buffer[] = [];
- req.on("data", (c) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(String(c))));
- req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
- req.on("error", () => resolve(""));
- });
-}
-
-const server = http.createServer(async (req, res) => {
- const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
-
- if (req.method === "POST" && url.pathname === "/v1/chat/completions") {
- await readBody(req);
- if (mode === "fail") {
- res.writeHead(status || 503, { "content-type": "application/json" });
- res.end(JSON.stringify({ error: { message: "upstream error", type: "api_error" } }));
- return;
- }
- res.writeHead(200, { "content-type": "application/json" });
- res.end(
- JSON.stringify({
- id: "mock",
- object: "chat.completion",
- choices: [{ index: 0, message: { role: "assistant", content: "ok" } }],
- usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
- }),
- );
- return;
- }
-
- if (req.method === "GET" && url.pathname === "/healthz") {
- res.writeHead(200, { "content-type": "application/json" });
- res.end(JSON.stringify({ ok: true, mode, status, port }));
- return;
- }
-
- res.writeHead(404, { "content-type": "application/json" });
- res.end(JSON.stringify({ error: { message: "not found" } }));
-});
-
-server.listen(port);
From 748d318c9b99431ec365d3ef6f50664176c73b20 Mon Sep 17 00:00:00 2001
From: wangzhizhou <824219521@qq.com>
Date: Sun, 22 Nov 2026 18:23:00 +0800
Subject: [PATCH 4/6] =?UTF-8?q?chore:=20=E6=B8=85=E7=90=86=E6=97=A0?=
=?UTF-8?q?=E7=94=A8=E9=85=8D=E7=BD=AE=E9=A1=B9=EF=BC=8C=E5=90=88=E5=B9=B6?=
=?UTF-8?q?=E9=87=8D=E5=A4=8D=E5=BC=80=E5=85=B3?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- 删除代码里从未生效的配置:app.body_limit / app.trust_proxy / app.postgres_* / app.routing_strategy / app.redis_host,port / corsOrigin / securityHeadersEnabled
- 超时合并为一个 app.timeout_ms(原先网关 60s 会先于 LiteLLM 的 120s 超时,已修正)
- 开发配置只保留可用的 ollama chat 模型,云端厂商改为注释示例(避免 /v1/models 出现必然失败的模型)
- 生产示例/本地配置同步精简,移除空 api_key 的 provider
- 文档同步:config 表格、架构中的网关读取项
---
config/easyai.development.yaml | 46 +++++++++-------
config/easyai.production.example.yaml | 52 +++++++++---------
docs/architecture.md | 4 +-
docs/deployment.md | 2 +-
docs/yaml-secret-management.md | 2 +-
oneapi-gateway/src/config.ts | 54 +++++++------------
oneapi-gateway/src/index.ts | 6 +--
oneapi-gateway/src/proxy.ts | 2 +-
oneapi-gateway/test/auth.test.ts | 4 +-
oneapi-gateway/test/batch.api.test.ts | 4 +-
oneapi-gateway/test/config.validation.test.ts | 4 +-
oneapi-gateway/test/proxy.integration.test.ts | 6 +--
scripts/render-litellm-config.py | 20 +++----
13 files changed, 90 insertions(+), 116 deletions(-)
diff --git a/config/easyai.development.yaml b/config/easyai.development.yaml
index aaf389e..739370f 100644
--- a/config/easyai.development.yaml
+++ b/config/easyai.development.yaml
@@ -2,45 +2,51 @@ app:
env: "development"
port: 3003
log_level: "info"
- # LiteLLM Admin UI (keys / budgets / spend / logs), opened by the browser.
+ # 浏览器访问的地址:控制台(LiteLLM Admin UI)与聊天界面(Open WebUI)
console_url: "http://localhost:3005/ui"
- # 可选聊天界面(docker compose --profile chat up -d 启动 Open WebUI)
chat_url: "http://localhost:3006"
+ # 网关简单限流:每个 key 每分钟请求数
rate_limit_rpm: 120
- default_timeout_ms: 120000
+ # 模型请求超时(毫秒),网关会比它多等 5 秒
+ timeout_ms: 120000
+ # 以下三项交给 LiteLLM 执行
cache_enabled: true
cache_ttl_seconds: 60
num_retries: 2
secrets:
- # LiteLLM master key: console login password + internal admin key. Never hand this to API clients.
+ # 控制台登录密码 + 网关访问 LiteLLM 的内部主密钥,不要发给 API 客户端
master_key: "sk-dev-master"
- # Optional. Encrypts provider keys stored through the console. Defaults to a hash of master_key.
- # salt_key: "sk-change-me-and-keep-it-stable"
+ # 客户端调用用的 key(可多个)
api_keys:
- "dev-key"
+ # Batch worker 内部鉴权
internal_token: "dev-internal"
postgres_password: "oneapi"
+ # 可选:加密控制台里保存的厂商密钥,默认由 master_key 派生
+ # salt_key: "sk-keep-it-stable"
providers:
ollama:
api_base: "http://ollama:11434"
- openai:
- api_key: ""
- deepseek:
- api_base: "https://api.deepseek.com/v1"
- api_key: ""
models:
+ # 客户端请求时使用的模型名 -> 上游 provider + model
chat:
provider: ollama
model: qwen2.5:0.5b
- dsv4flash:
- provider: deepseek
- model: deepseek-v4-flash
- dsv4pro:
- provider: deepseek
- model: deepseek-v4-pro
- gpt:
- provider: openai
- model: gpt-5.5
+
+# 接入云端厂商:取消注释并填入 api_key,模型名可自定义
+# providers:
+# deepseek:
+# api_base: "https://api.deepseek.com/v1"
+# api_key: "sk-..."
+# openai:
+# api_key: "sk-..."
+# models:
+# deepseek-v4:
+# provider: deepseek
+# model: deepseek-v4-flash
+# gpt:
+# provider: openai
+# model: gpt-5.5
diff --git a/config/easyai.production.example.yaml b/config/easyai.production.example.yaml
index 51ddee0..93feb9f 100644
--- a/config/easyai.production.example.yaml
+++ b/config/easyai.production.example.yaml
@@ -2,15 +2,19 @@ app:
env: "production"
port: 3003
log_level: "info"
- # Browser-facing LiteLLM console URL, e.g. http://your-host:3005/ui
+ # 浏览器访问地址(改成实际域名/IP):控制台(LiteLLM Admin UI)与聊天界面(Open WebUI)
console_url: "http://localhost:3005/ui"
- # 可选:Open WebUI 地址(docker compose --profile chat up -d)
chat_url: "http://localhost:3006"
+ rate_limit_rpm: 120
+ timeout_ms: 120000
+ cache_enabled: true
+ cache_ttl_seconds: 60
+ num_retries: 2
secrets:
- # LiteLLM master key: console login password + internal admin key. Never hand this to API clients.
+ # 控制台登录密码 + 网关访问 LiteLLM 的内部主密钥,不要发给 API 客户端
master_key: "REPLACE_WITH_LITELLM_MASTER_KEY"
- # Keep this stable: it encrypts provider keys stored in the console database.
+ # 加密控制台保存的厂商密钥,一旦使用不要再改
salt_key: "REPLACE_WITH_STABLE_SALT_KEY"
api_keys:
- "REPLACE_WITH_CLIENT_API_KEY"
@@ -18,11 +22,6 @@ secrets:
postgres_password: "REPLACE_WITH_POSTGRES_PASSWORD"
providers:
- openai:
- api_key: "REPLACE_WITH_OPENAI_API_KEY"
- deepseek:
- api_base: "https://api.deepseek.com/v1"
- api_key: "REPLACE_WITH_DEEPSEEK_API_KEY"
ollama:
api_base: "http://ollama:11434"
@@ -30,17 +29,25 @@ models:
chat:
provider: ollama
model: qwen2.5:0.5b
- dsv4flash:
- provider: deepseek
- model: deepseek-v4-flash
- dsv4pro:
- provider: deepseek
- model: deepseek-v4-pro
- gpt:
- provider: openai
- model: gpt-5.5
-# 可选:内容护栏(由 LiteLLM 内置 litellm_content_filter 执行,无需外部依赖)
+# 接入云端厂商:取消注释并填入 api_key
+# providers:
+# deepseek:
+# api_base: "https://api.deepseek.com/v1"
+# api_key: "REPLACE_WITH_DEEPSEEK_API_KEY"
+# openai:
+# api_key: "REPLACE_WITH_OPENAI_API_KEY"
+# models:
+# deepseek-v4:
+# provider: deepseek
+# model: deepseek-v4-flash
+# # 可选:失败时自动切到别的模型别名
+# fallback: ["chat"]
+# gpt:
+# provider: openai
+# model: gpt-5.5
+
+# 可选:内容护栏(LiteLLM 内置 litellm_content_filter,无需外部依赖)
# guardrails:
# enabled: true
# blocked_keywords:
@@ -49,10 +56,3 @@ models:
# mask_pii:
# - "email"
# - "us_ssn"
-
-# 可选:把某个模型配置成失败时自动切换到备选模型
-# models:
-# chat:
-# provider: ollama
-# model: qwen2.5:0.5b
-# fallback: ["dsv4flash"]
diff --git a/docs/architecture.md b/docs/architecture.md
index e2bf35c..cd62a8c 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -2,7 +2,7 @@
## 1. 组件
-- `oneapi-gateway`:统一入口,提供鉴权、限流、`/v1/*` 透传、Batch API、首页与页面跳转(约 1,300 行)
+- `oneapi-gateway`:统一入口,提供鉴权、限流、`/v1/*` 透传、Batch API、首页与页面跳转(约 800 行)
- `litellm`:官方 LiteLLM Proxy 镜像,作为模型接入面,负责 100+ provider 协议适配、模型别名、重试/故障转移、Redis 缓存、内容过滤护栏与 `/docs`
- `batch-worker`:消费 Redis 队列,调用网关执行批任务,并写回 Postgres
- `redis`:限流、LiteLLM 响应缓存、Batch 队列
@@ -40,7 +40,7 @@
## 4. 配置边界
- 统一配置源:一份 YAML(容器内挂载为 `/app/config/easyai.yaml`)
-- 网关读取:`app.port`、`app.console_url`、`app.rate_limit_rpm`、`app.upstream_timeout_ms`、`secrets.api_keys`、`secrets.internal_token`、`secrets.master_key`、`secrets.postgres_password`
+- 网关读取:`app.env`、`app.port`、`app.log_level`、`app.console_url`、`app.chat_url`、`app.rate_limit_rpm`、`app.timeout_ms`、`secrets.api_keys`、`secrets.internal_token`、`secrets.master_key`、`secrets.postgres_password`
- LiteLLM 配置在启动时由 `scripts/render-litellm-config.py` 从同一份 YAML 生成:`providers.*`、`models.*`、`app.*`、`guardrails.*` → `model_list` / `litellm_settings` / `guardrails` / `router_settings`
- 说明:不存在第二份 LiteLLM 配置文件;模型别名、fallback、缓存开关、护栏关键词都只在这一份 YAML 里维护
diff --git a/docs/deployment.md b/docs/deployment.md
index d5fe842..dfc8bee 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -83,7 +83,7 @@ BASE_URL=http://localhost:3003 CONFIG_FILE=config/easyai.production.local.yaml .
| 段 | 内容 |
|---|---|
-| `app` | `port`、`log_level`、`console_url`、`chat_url`、`rate_limit_rpm`、`default_timeout_ms`、`cache_enabled`、`cache_ttl_seconds`、`num_retries` |
+| `app` | `port`、`log_level`、`console_url`、`chat_url`、`rate_limit_rpm`、`timeout_ms`、`cache_enabled`、`cache_ttl_seconds`、`num_retries` |
| `secrets` | `master_key`(控制台密码 + 内部主密钥)、`salt_key`(加密控制台保存的厂商 key)、`api_keys`、`internal_token`、`postgres_password` |
| `providers` | 各厂商 `api_base` / `api_key` / `api_version` |
| `models` | 对外模型别名 → `provider` + `model`,可加 `fallback: [其他别名]` |
diff --git a/docs/yaml-secret-management.md b/docs/yaml-secret-management.md
index 71c44e5..fc73439 100644
--- a/docs/yaml-secret-management.md
+++ b/docs/yaml-secret-management.md
@@ -33,7 +33,7 @@ docker compose -f docker-compose.yml -f docker-compose.local.yml exec -T ollama
- `secrets.api_keys`
- `secrets.internal_token`
- `secrets.postgres_password`
-- `providers..api_key`(如 OpenAI / DeepSeek)
+- `providers..api_key`(接入云端厂商时)
## 4. 运行时保护
diff --git a/oneapi-gateway/src/config.ts b/oneapi-gateway/src/config.ts
index 2acfd03..91ce1a5 100644
--- a/oneapi-gateway/src/config.ts
+++ b/oneapi-gateway/src/config.ts
@@ -4,10 +4,7 @@ import { load as loadYaml } from "js-yaml";
export type Config = {
appEnv: "development" | "staging" | "production" | "test";
port: number;
- bodyLimitBytes?: number;
logLevel: "fatal" | "error" | "warn" | "info" | "debug" | "trace";
- trustProxy: boolean | string;
- securityHeadersEnabled?: boolean;
/** Keys defined in YAML. LiteLLM virtual keys are also accepted and validated by LiteLLM. */
apiKeys: Set;
/** LiteLLM proxy base URL (model access plane). */
@@ -18,32 +15,25 @@ export type Config = {
consoleUrl?: string;
/** Public URL of the optional chat UI (Open WebUI). */
chatUrl?: string;
- upstreamTimeoutMs: number;
+ /** Provider request timeout. The gateway waits a bit longer than LiteLLM. */
+ timeoutMs: number;
rateLimitRpm: number;
- corsOrigin: string | string[];
internalToken?: string;
redisUrl: string;
databaseUrl: string;
};
-function parseBytes(value: unknown, defaultBytes: number): number {
- if (value === undefined || value === null || value === "") return defaultBytes;
- if (typeof value === "number") return value;
- const s = String(value).trim().toLowerCase();
- const m = s.match(/^(\d+(?:\.\d+)?)\s*(b|kb|kib|mb|mib)?$/);
- if (!m) return defaultBytes;
- const n = Number(m[1]);
- const unit = m[2] ?? "b";
- const multiplier = unit === "mb" || unit === "mib" ? 1024 * 1024 : unit === "kb" || unit === "kib" ? 1024 : 1;
- return Math.floor(n * multiplier);
-}
-
-function buildPostgresUrl(password: string, app: any): string {
- const host = String(app.postgres_host ?? "postgres");
- const port = Number(app.postgres_port ?? 5432);
- const user = String(app.postgres_user ?? "oneapi");
- const name = String(app.postgres_db ?? "oneapi");
- return `postgres://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${host}:${port}/${encodeURIComponent(name)}`;
+/** Matching docker-compose service names keep the config surface small. */
+const REDIS_URL = "redis://redis:6379";
+const POSTGRES_HOST = "postgres";
+const POSTGRES_PORT = 5432;
+const POSTGRES_USER = "oneapi";
+const POSTGRES_DB = "oneapi";
+
+function buildPostgresUrl(password: string): string {
+ const user = encodeURIComponent(POSTGRES_USER);
+ const pass = encodeURIComponent(password);
+ return `postgres://${user}:${pass}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}`;
}
function isPlaceholderSecret(value: unknown): boolean {
@@ -93,10 +83,7 @@ export function loadConfig(configPath = "/app/config/easyai.yaml"): Config {
const appEnv = app.env || "development";
const port = Number(app.port ?? 3003);
- const bodyLimitBytes = parseBytes(app.body_limit, 10 * 1024 * 1024);
const logLevel = app.log_level ?? "info";
- const trustProxy = typeof app.trust_proxy === "number" ? String(app.trust_proxy) : (app.trust_proxy ?? false);
- const securityHeadersEnabled = appEnv !== "development";
const apiKeysArr = Array.isArray(secrets.api_keys) ? secrets.api_keys : [];
const apiKeys = new Set(apiKeysArr.map((s: string) => String(s).trim()).filter(Boolean));
@@ -109,13 +96,12 @@ export function loadConfig(configPath = "/app/config/easyai.yaml"): Config {
const consoleUrl = app.console_url ? String(app.console_url) : undefined;
const chatUrl = app.chat_url ? String(app.chat_url) : undefined;
- const upstreamTimeoutMs = Number(app.upstream_timeout_ms ?? 60000);
+
+ const timeoutMs = Number(app.timeout_ms ?? 120000);
const rateLimitRpm = Number(app.rate_limit_rpm ?? 120);
- const corsOrigin = "*";
const internalToken = secrets.internal_token ? String(secrets.internal_token) : undefined;
- const redisUrl = "redis://redis:6379";
- const databaseUrl = buildPostgresUrl(String(secrets.postgres_password ?? "oneapi"), app);
+ const databaseUrl = buildPostgresUrl(String(secrets.postgres_password ?? "oneapi"));
if (appEnv === "production") {
assertNoPlaceholderSecrets({ apiKeys, internalToken, masterKey: litellmMasterKey, databaseUrl });
@@ -124,20 +110,16 @@ export function loadConfig(configPath = "/app/config/easyai.yaml"): Config {
return {
appEnv,
port,
- bodyLimitBytes,
logLevel,
- trustProxy,
- securityHeadersEnabled,
apiKeys,
litellmBaseUrl,
litellmMasterKey,
consoleUrl,
chatUrl,
- upstreamTimeoutMs,
+ timeoutMs,
rateLimitRpm,
- corsOrigin,
internalToken,
- redisUrl,
+ redisUrl: REDIS_URL,
databaseUrl,
};
}
diff --git a/oneapi-gateway/src/index.ts b/oneapi-gateway/src/index.ts
index 788e2dc..ad5b67a 100644
--- a/oneapi-gateway/src/index.ts
+++ b/oneapi-gateway/src/index.ts
@@ -14,16 +14,14 @@ const app = Fastify({
level: cfg.logLevel,
redact: ["req.headers.authorization", "req.headers.x-api-key", "req.headers.x-oneapi-internal-token"],
},
- bodyLimit: cfg.bodyLimitBytes ?? 10 * 1024 * 1024,
- trustProxy: cfg.trustProxy,
});
const redis = await createRedis(cfg.redisUrl);
const db = await createDb(cfg.databaseUrl);
-await app.register(cors, { origin: cfg.corsOrigin });
+await app.register(cors, { origin: "*" });
-if (cfg.securityHeadersEnabled === true) {
+if (cfg.appEnv !== "development") {
app.addHook("onRequest", async (_req, reply) => {
reply.header("X-Content-Type-Options", "nosniff");
reply.header("X-Frame-Options", "DENY");
diff --git a/oneapi-gateway/src/proxy.ts b/oneapi-gateway/src/proxy.ts
index 6d87277..f2bc8c9 100644
--- a/oneapi-gateway/src/proxy.ts
+++ b/oneapi-gateway/src/proxy.ts
@@ -77,7 +77,7 @@ export async function registerProxyRoutes(app: FastifyInstance, deps: ProxyDeps)
headers,
body: hasBody ? JSON.stringify(req.body) : undefined,
},
- deps.cfg.upstreamTimeoutMs,
+ deps.cfg.timeoutMs + 5000,
);
} catch (e: any) {
if (e?.name === "AbortError") {
diff --git a/oneapi-gateway/test/auth.test.ts b/oneapi-gateway/test/auth.test.ts
index d792cc3..b1db66d 100644
--- a/oneapi-gateway/test/auth.test.ts
+++ b/oneapi-gateway/test/auth.test.ts
@@ -8,13 +8,11 @@ function makeConfig(overrides: Partial = {}): Config {
appEnv: "test",
port: 0,
logLevel: "info",
- trustProxy: false,
apiKeys: new Set(["dev-key"]),
litellmBaseUrl: "http://litellm:4000",
litellmMasterKey: "sk-test-master",
- upstreamTimeoutMs: 1000,
+ timeoutMs: 1000,
rateLimitRpm: 120,
- corsOrigin: "*",
internalToken: "dev-internal",
redisUrl: "redis://fake",
databaseUrl: "postgres://fake",
diff --git a/oneapi-gateway/test/batch.api.test.ts b/oneapi-gateway/test/batch.api.test.ts
index 3b3d20b..aea0689 100644
--- a/oneapi-gateway/test/batch.api.test.ts
+++ b/oneapi-gateway/test/batch.api.test.ts
@@ -83,13 +83,11 @@ const baseCfg: Config = {
appEnv: "test",
port: 0,
logLevel: "info",
- trustProxy: false,
apiKeys: new Set(["dev-key"]),
litellmBaseUrl: "http://u",
litellmMasterKey: "sk-test-master",
- upstreamTimeoutMs: 1000,
+ timeoutMs: 1000,
rateLimitRpm: 120,
- corsOrigin: "*",
internalToken: "dev-internal",
redisUrl: "redis://x",
databaseUrl: "postgres://x",
diff --git a/oneapi-gateway/test/config.validation.test.ts b/oneapi-gateway/test/config.validation.test.ts
index e7e07b3..768bc58 100644
--- a/oneapi-gateway/test/config.validation.test.ts
+++ b/oneapi-gateway/test/config.validation.test.ts
@@ -119,7 +119,7 @@ test("loadConfig: reads app.console_url and gateway knobs from YAML", async () =
env: "development",
console_url: "http://localhost:3005/ui",
rate_limit_rpm: 7,
- upstream_timeout_ms: 1500,
+ timeout_ms: 1500,
litellm_base_url: "http://litellm:4000/",
},
secrets: {
@@ -132,7 +132,7 @@ test("loadConfig: reads app.console_url and gateway knobs from YAML", async () =
const cfg = loadConfig(tmpFile);
assert.equal(cfg.consoleUrl, "http://localhost:3005/ui");
assert.equal(cfg.rateLimitRpm, 7);
- assert.equal(cfg.upstreamTimeoutMs, 1500);
+ assert.equal(cfg.timeoutMs, 1500);
assert.equal(cfg.litellmBaseUrl, "http://litellm:4000");
},
);
diff --git a/oneapi-gateway/test/proxy.integration.test.ts b/oneapi-gateway/test/proxy.integration.test.ts
index b56a6e5..a24a2c6 100644
--- a/oneapi-gateway/test/proxy.integration.test.ts
+++ b/oneapi-gateway/test/proxy.integration.test.ts
@@ -37,13 +37,11 @@ function makeConfig(overrides: Partial = {}): Config {
appEnv: "test",
port: 0,
logLevel: "info",
- trustProxy: false,
apiKeys: new Set(["k1"]),
litellmBaseUrl: "http://127.0.0.1:1",
litellmMasterKey: "sk-test-master",
- upstreamTimeoutMs: 2000,
+ timeoutMs: 2000,
rateLimitRpm: 1000,
- corsOrigin: "*",
internalToken: undefined,
redisUrl: "redis://fake",
databaseUrl: "postgres://fake",
@@ -158,7 +156,7 @@ test("proxy: streams sse responses", async () => {
});
test("proxy: reports unreachable model plane as 502", async () => {
- const cfg = makeConfig({ litellmBaseUrl: "http://127.0.0.1:1", upstreamTimeoutMs: 500 });
+ const cfg = makeConfig({ litellmBaseUrl: "http://127.0.0.1:1", timeoutMs: 500 });
const { app, url: gwUrl } = await startGateway(cfg);
const res = await fetch(gwUrl + "/v1/chat/completions", {
diff --git a/scripts/render-litellm-config.py b/scripts/render-litellm-config.py
index 25d138f..4a369a4 100755
--- a/scripts/render-litellm-config.py
+++ b/scripts/render-litellm-config.py
@@ -19,8 +19,8 @@
import yaml
-DEFAULT_REDIS_HOST = "redis"
-DEFAULT_REDIS_PORT = 6379
+REDIS_HOST = "redis"
+REDIS_PORT = 6379
def load(path: str) -> Dict[str, Any]:
@@ -40,11 +40,7 @@ def database_url(cfg: Dict[str, Any]) -> str:
secrets = cfg.get("secrets") or {}
app_cfg = cfg.get("app") or {}
password = str(secrets.get("postgres_password") or "oneapi")
- host = str(app_cfg.get("postgres_host") or "postgres")
- port = int(app_cfg.get("postgres_port") or 5432)
- user = str(app_cfg.get("postgres_user") or "oneapi")
- name = str(app_cfg.get("postgres_db") or "oneapi")
- return f"postgresql://{user}:{password}@{host}:{port}/{name}"
+ return f"postgresql://oneapi:{password}@postgres:5432/oneapi"
def salt_key(cfg: Dict[str, Any]) -> str:
@@ -165,7 +161,7 @@ def render(cfg: Dict[str, Any]) -> Dict[str, Any]:
litellm_settings: Dict[str, Any] = {
"drop_params": True,
"num_retries": int(app_cfg.get("num_retries") or 2),
- "request_timeout": float(app_cfg.get("default_timeout_ms") or 120000) / 1000.0,
+ "request_timeout": float(app_cfg.get("timeout_ms") or 120000) / 1000.0,
}
cache_enabled = app_cfg.get("cache_enabled", True)
@@ -173,17 +169,15 @@ def render(cfg: Dict[str, Any]) -> Dict[str, Any]:
litellm_settings["cache"] = True
litellm_settings["cache_params"] = {
"type": "redis",
- "host": str(app_cfg.get("redis_host") or DEFAULT_REDIS_HOST),
- "port": int(app_cfg.get("redis_port") or DEFAULT_REDIS_PORT),
+ "host": REDIS_HOST,
+ "port": REDIS_PORT,
"ttl": int(app_cfg.get("cache_ttl_seconds") or 60),
}
out["litellm_settings"] = litellm_settings
- router_settings: Dict[str, Any] = {"routing_strategy": str(app_cfg.get("routing_strategy") or "simple-shuffle")}
fallbacks = render_fallbacks(cfg)
if fallbacks:
- router_settings["fallbacks"] = fallbacks
- out["router_settings"] = router_settings
+ out["router_settings"] = {"fallbacks": fallbacks}
out["general_settings"] = {"master_key": "os.environ/LITELLM_MASTER_KEY"}
return out
From 896a689c25858d480074065d304abeeaeb667396 Mon Sep 17 00:00:00 2001
From: wangzhizhou <824219521@qq.com>
Date: Sun, 22 Nov 2026 18:29:07 +0800
Subject: [PATCH 5/6] =?UTF-8?q?docs:=20=E5=90=8C=E6=AD=A5=E7=B2=BE?=
=?UTF-8?q?=E7=AE=80=E5=90=8E=E7=9A=84=E5=BD=A2=E6=80=81=E4=B8=8E=E9=85=8D?=
=?UTF-8?q?=E7=BD=AE=E9=A1=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- README:网关职责、快速启动步骤、升级 LiteLLM 的固定 digest 用法
- 架构:渲染产物说明(fallback 条件生成 router_settings、guardrails 可选)、自研行数更新
- 部署与运维:补充 timeout_ms 与网关 +5s 缓冲说明
- 开发:新增提交前最小检查清单
---
README.md | 13 ++++++++++---
docs/architecture.md | 15 +++++++++------
docs/deployment.md | 2 ++
docs/development.md | 16 ++++++++++++----
4 files changed, 33 insertions(+), 13 deletions(-)
diff --git a/README.md b/README.md
index ae91e1f..e20fa17 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@
[](https://github.com/EasyIndie/EasyAI/actions/workflows/ci.yml)
EasyAI 是一个可本地运行、免费自部署的统一 LLM 接入层:一份 YAML 配置,屏蔽不同厂商的协议差异。
-- OneAPI Gateway(统一 `/v1/*` 入口、鉴权、限流、Chat/Batch API、首页与会话页)
+- OneAPI Gateway(统一 `/v1/*` 入口、鉴权、限流、Batch API、首页导航,约 750 行)
- LiteLLM Proxy(官方镜像,模型接入面:provider 适配、别名、重试/故障转移、缓存、护栏、密钥/预算/用量控制台)
- Batch Worker(异步批处理消费)
- 控制台:LiteLLM Admin UI(支持中文)
@@ -14,8 +14,8 @@ EasyAI 是一个可本地运行、免费自部署的统一 LLM 接入层:一
```bash
docker compose up -d --build
-curl -sS http://localhost:3004/healthz
docker compose exec -T ollama ollama pull qwen2.5:0.5b
+curl -sS http://localhost:3004/healthz
```
可选:中文聊天界面(Open WebUI)
@@ -24,7 +24,7 @@ docker compose exec -T ollama ollama pull qwen2.5:0.5b
docker compose --profile chat up -d
```
-打开:`http://localhost:3004/`(首页)、`http://localhost:3005/ui`(控制台)、`http://localhost:3006`(聊天)。
+打开:`http://localhost:3004/`(首页)· `http://localhost:3005/ui`(控制台)· `http://localhost:3006`(聊天,可选)。
发起一次请求(默认开发 key: `dev-key`):
@@ -62,6 +62,13 @@ BASE_URL=http://localhost:3003 CONFIG_FILE=config/easyai.production.local.yaml .
- 聊天:`/chat` → Open WebUI(可选组件)
- `/dashboard` 会 302 到控制台
+## 升级 LiteLLM
+
+```bash
+LITELLM_IMAGE=ghcr.io/berriai/litellm@sha256: docker compose up -d litellm
+./scripts/smoke-compose.sh
+```
+
## 文档导航
- [用户手册](docs/user-manual.md)
diff --git a/docs/architecture.md b/docs/architecture.md
index cd62a8c..b66e47a 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -2,7 +2,7 @@
## 1. 组件
-- `oneapi-gateway`:统一入口,提供鉴权、限流、`/v1/*` 透传、Batch API、首页与页面跳转(约 800 行)
+- `oneapi-gateway`:统一入口,提供鉴权、限流、`/v1/*` 透传、Batch API、首页与页面跳转(约 750 行)
- `litellm`:官方 LiteLLM Proxy 镜像,作为模型接入面,负责 100+ provider 协议适配、模型别名、重试/故障转移、Redis 缓存、内容过滤护栏与 `/docs`
- `batch-worker`:消费 Redis 队列,调用网关执行批任务,并写回 Postgres
- `redis`:限流、LiteLLM 响应缓存、Batch 队列
@@ -41,7 +41,10 @@
- 统一配置源:一份 YAML(容器内挂载为 `/app/config/easyai.yaml`)
- 网关读取:`app.env`、`app.port`、`app.log_level`、`app.console_url`、`app.chat_url`、`app.rate_limit_rpm`、`app.timeout_ms`、`secrets.api_keys`、`secrets.internal_token`、`secrets.master_key`、`secrets.postgres_password`
-- LiteLLM 配置在启动时由 `scripts/render-litellm-config.py` 从同一份 YAML 生成:`providers.*`、`models.*`、`app.*`、`guardrails.*` → `model_list` / `litellm_settings` / `guardrails` / `router_settings`
+- LiteLLM 配置在启动时由 `scripts/render-litellm-config.py` 从同一份 YAML 生成:
+ - `providers.*` + `models.*` → `model_list`(有 `fallback` 时额外生成 `router_settings.fallbacks`)
+ - `app.cache_*` / `app.num_retries` / `app.timeout_ms` → `litellm_settings`
+ - `guardrails.*`(可选)→ `guardrails`(内置 `litellm_content_filter`,默认对所有请求生效)
- 说明:不存在第二份 LiteLLM 配置文件;模型别名、fallback、缓存开关、护栏关键词都只在这一份 YAML 里维护
## 5. 自研边界(重要)
@@ -50,11 +53,11 @@
| 保留 | 行数 | 理由 |
|---|---|---|
-| `scripts/render-litellm-config.py` | ~220 | 一份 YAML 的核心承诺 |
-| 网关(`index/proxy/auth/config/rate_limit`) | ~430 | 统一入口 + YAML key/虚拟 key 双轨 + RPM |
+| `scripts/render-litellm-config.py` | ~210 | 一份 YAML 的核心承诺 |
+| 网关(`index/proxy/auth/config/rate_limit/redis/crypto`) | ~430 | 统一入口 + YAML key/虚拟 key 双轨 + RPM |
| `batch-worker` + `batch.ts` | ~260 | 上游空白:给无原生 Batch 的模型做离线批跑(冻结,不扩展) |
-| `scripts/` + 中文文档 + smoke/CI | — | 真正的交付体验差异 |
-| 服务端渲染首页 `ui.ts` | ~120 | 入口导航 |
+| `scripts/` + 中文文档 + smoke/CI | ~950 | 真正的交付体验差异 |
+| 服务端渲染首页 `ui.ts` | ~95 | 入口导航 |
**不再自研**:provider 适配、路由/重试/故障转移、缓存、护栏、密钥/预算/用量后台、API 文档、指标、聊天界面、会话存储。
diff --git a/docs/deployment.md b/docs/deployment.md
index dfc8bee..3a527cd 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -89,6 +89,8 @@ BASE_URL=http://localhost:3003 CONFIG_FILE=config/easyai.production.local.yaml .
| `models` | 对外模型别名 → `provider` + `model`,可加 `fallback: [其他别名]` |
| `guardrails` | 可选:`blocked_keywords`、`mask_pii`(交给 LiteLLM 内置内容过滤) |
+`app.timeout_ms` 是模型请求超时;网关在转发时会多等 5 秒,避免网关先于 LiteLLM 超时。
+
生产安全开关:
- `app.env: production` 时,占位值(`dev-key`、`dev-internal`、`REPLACE_WITH_*`)会让网关直接启动失败
diff --git a/docs/development.md b/docs/development.md
index 2010166..f6fd55e 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -40,14 +40,22 @@ config/ 唯一的 YAML 配置
docs/ 中文文档
```
-## 4. 文档一致性校验
+## 4. 提交前最小检查
+
+```bash
+cd oneapi-gateway
+npm run build && npm test && npm run doc-audit
+cd ../batch-worker && npm run build
+```
+
+## 5. 文档一致性校验
```bash
cd oneapi-gateway
npm run doc-audit
```
-## 5. CI 对齐
+## 6. CI 对齐
仓库 CI 使用:`.github/workflows/ci.yml` -> `scripts/test-all.sh`。
@@ -63,13 +71,13 @@ bash scripts/test-all.sh
./scripts/smoke-compose.sh
```
-## 6. 安全基线(生产)
+## 7. 安全基线(生产)
- 生产配置从 `config/easyai.production.example.yaml` 复制到本地私有文件
- 必须替换 `REPLACE_WITH_*`、`dev-key`、`dev-internal` 等默认值
- 不要提交 `*.local.yaml`、`.env`、密钥文件
-## 7. 提交前密钥检查(必做)
+## 8. 提交前密钥检查(必做)
首次在本仓库启用 hooks:
From a61adb2bdbb9639102f8522beec109aa958bca63 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Sun, 22 Nov 2026 10:31:52 +0000
Subject: [PATCH 6/6] Bump fast-uri from 3.1.2 to 3.1.9 in /oneapi-gateway
Bumps [fast-uri](https://github.com/fastify/fast-uri) from 3.1.2 to 3.1.9.
- [Release notes](https://github.com/fastify/fast-uri/releases)
- [Commits](https://github.com/fastify/fast-uri/compare/v3.1.2...v3.1.9)
---
updated-dependencies:
- dependency-name: fast-uri
dependency-version: 3.1.9
dependency-type: indirect
...
Signed-off-by: dependabot[bot]
---
oneapi-gateway/package-lock.json | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/oneapi-gateway/package-lock.json b/oneapi-gateway/package-lock.json
index 72799b3..07fb8cf 100644
--- a/oneapi-gateway/package-lock.json
+++ b/oneapi-gateway/package-lock.json
@@ -1225,9 +1225,9 @@
}
},
"node_modules/fast-uri": {
- "version": "3.1.2",
- "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz",
- "integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==",
+ "version": "3.1.9",
+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz",
+ "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==",
"funding": [
{
"type": "github",