This commit is contained in:
2026-03-11 15:14:45 +08:00
parent 813005ab9c
commit 8379be1630
6 changed files with 45 additions and 12 deletions

View File

@@ -1,6 +1,7 @@
import { Result } from '@kevisual/query';
import { CNB } from '../../src/index.ts';
import { useKey } from '@kevisual/context';
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
export const getConfig = async (opts: { token?: string }) => {
const kevisualEnv = useKey('KEVISUAL_ENV')
const baseUrl = kevisualEnv === 'production' ? 'https://kevisual.cn/api/router' : 'https://kevisual.xiongxiao.me/api/router';
@@ -32,7 +33,14 @@ type CNBItem = {
runAt?: number
owner?: boolean
cnb: CNB
cnbAi: ReturnType<typeof createOpenAICompatible>
}
// const repo = useKey('CNB_REPO_SLUG_LOWERCASE') as string || 'kevision/kevision';
// export const cnbAi = createOpenAICompatible({
// baseURL: `https://api.cnb.cool/${repo}/-/ai/`,
// name: 'custom-cnb',
// apiKey: token,
// });
export class CNBManager {
cnbMap: Map<string, CNBItem> = new Map()
constructor() {
@@ -71,20 +79,24 @@ export class CNBManager {
* @returns CNB 实例
*/
async getContext(ctx: any) {
const item = await this.getCNBItem(ctx)
return item.cnb
}
async getCNBItem(ctx: any) {
const tokenUser = ctx?.state?.tokenUser
const username = tokenUser?.username
if (!username) {
ctx.throw(403, 'Unauthorized')
}
if (username === 'default') {
return this.getDefaultCNB().cnb
return this.getDefaultCNB()
}
const kevisualToken = ctx.query?.token;
const item = await this.getCNB({ username, kevisualToken });
if (!item) {
ctx.throw(400, '不存在的 CNB 配置项,请检查 登录 Token 是否正确,或添加 CNB 配置')
}
return item.cnb
return item;
}
addCNB(opts: Partial<CNBItem>) {
if (!opts.username || !opts.token) {
@@ -98,6 +110,12 @@ export class CNBManager {
const cnb = opts?.cnb || new CNB({ token: opts.token, cookie: opts.cookie });
opts.cnb = cnb;
opts.runAt = Date.now()
const repoSlug = useKey('CNB_REPO_SLUG_LOWERCASE') as string || 'kevision/kevision';
opts.cnbAi = createOpenAICompatible({
baseURL: `https://api.cnb.cool/${repoSlug}/-/ai/`,
name: `custom-cnb-${opts.username}`,
apiKey: opts.token,
})
this.cnbMap.set(opts.username, opts as CNBItem)
return opts as CNBItem
}