-
Notifications
You must be signed in to change notification settings - Fork 0
[codex] Auto provision AIProxy key #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| import { NextRequest, NextResponse } from 'next/server' | ||
| import { provisionUserAiProxyApiKey } from '@/lib/aiproxy/api-key-provisioning' | ||
| import { getSessionFromReq } from '@/lib/session/server' | ||
|
|
||
| export const runtime = 'nodejs' | ||
| export const dynamic = 'force-dynamic' | ||
|
|
||
| function getFailureStatus(reason: string): number { | ||
| if (reason === 'missing_kubeconfig') { | ||
| return 400 | ||
| } | ||
|
|
||
| if (reason === 'request_failed') { | ||
| return 502 | ||
| } | ||
|
|
||
| return 500 | ||
| } | ||
|
|
||
| export async function POST(req: NextRequest) { | ||
| try { | ||
| const session = await getSessionFromReq(req) | ||
|
|
||
| if (!session?.user?.id) { | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) | ||
| } | ||
|
|
||
| const body = (await req.json().catch(() => ({}))) as { kubeconfig?: unknown } | ||
| const result = await provisionUserAiProxyApiKey({ | ||
| kubeconfig: typeof body.kubeconfig === 'string' ? body.kubeconfig : null, | ||
| userId: session.user.id, | ||
| }) | ||
|
|
||
| if (result.ok) { | ||
| return NextResponse.json({ success: true }) | ||
| } | ||
|
|
||
| return NextResponse.json( | ||
| { | ||
| diagnostic: result.diagnostic, | ||
| error: 'Failed to provision AIProxy configuration', | ||
| reason: result.reason, | ||
| }, | ||
| { status: getFailureStatus(result.reason) }, | ||
| ) | ||
| } catch { | ||
| console.error('Failed to provision AIProxy configuration') | ||
| return NextResponse.json({ error: 'Failed to provision AIProxy configuration' }, { status: 500 }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| import 'server-only' | ||
|
|
||
| import { and, eq } from 'drizzle-orm' | ||
| import { AIPROXY_MODEL_BASE_URL } from '@/lib/aiproxy/constants' | ||
| import { getOrCreateAiProxyToken, type AiProxyTokenValidationIssue } from '@/lib/aiproxy/token-management' | ||
| import { encrypt } from '@/lib/crypto' | ||
| import { db } from '@/lib/db/client' | ||
| import { keys } from '@/lib/db/schema' | ||
| import { generateId } from '@/lib/utils/id' | ||
|
|
||
| export type AiProxyApiKeyProvisioningResult = | ||
| | { | ||
| mode: 'created' | 'existing' | ||
| ok: true | ||
| } | ||
| | { | ||
| diagnostic?: AiProxyTokenValidationIssue | ||
| ok: false | ||
| reason: 'missing_kubeconfig' | 'request_failed' | 'unexpected_response' | 'unusable_token' | ||
| } | ||
|
|
||
| async function findExistingAiProxyKey(userId: string) { | ||
| const [existing] = await db | ||
| .select({ id: keys.id }) | ||
| .from(keys) | ||
| .where(and(eq(keys.userId, userId), eq(keys.provider, 'aiproxy'))) | ||
| .limit(1) | ||
|
|
||
| return existing ?? null | ||
| } | ||
|
|
||
| export async function provisionUserAiProxyApiKey(input: { | ||
| kubeconfig?: string | null | ||
| userId: string | ||
| }): Promise<AiProxyApiKeyProvisioningResult> { | ||
| const existing = await findExistingAiProxyKey(input.userId) | ||
|
|
||
| if (existing) { | ||
| return { | ||
| mode: 'existing', | ||
| ok: true, | ||
| } | ||
| } | ||
|
|
||
| const kubeconfig = input.kubeconfig?.trim() | ||
|
|
||
| if (!kubeconfig) { | ||
| return { | ||
| ok: false, | ||
| reason: 'missing_kubeconfig', | ||
| } | ||
| } | ||
|
|
||
| const tokenResult = await getOrCreateAiProxyToken(kubeconfig) | ||
|
|
||
| if (!tokenResult.ok) { | ||
| return { | ||
| diagnostic: tokenResult.diagnostic, | ||
| ok: false, | ||
| reason: tokenResult.reason, | ||
| } | ||
| } | ||
|
|
||
| const insertResult = await db | ||
| .insert(keys) | ||
| .values({ | ||
| baseUrl: AIPROXY_MODEL_BASE_URL, | ||
| id: generateId(21), | ||
| provider: 'aiproxy', | ||
| userId: input.userId, | ||
| value: encrypt(tokenResult.token.key), | ||
| }) | ||
| .onConflictDoNothing({ | ||
| target: [keys.userId, keys.provider], | ||
| }) | ||
| .returning({ id: keys.id }) | ||
|
|
||
| if (insertResult.length > 0) { | ||
| return { | ||
| mode: 'created', | ||
| ok: true, | ||
| } | ||
| } | ||
|
|
||
| const conflictingExisting = await findExistingAiProxyKey(input.userId) | ||
|
|
||
| if (conflictingExisting) { | ||
| return { | ||
| mode: 'existing', | ||
| ok: true, | ||
| } | ||
| } | ||
|
|
||
| return { | ||
| ok: false, | ||
| reason: 'request_failed', | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| 'use client' | ||
|
|
||
| let aiProxyProvisioningTask: Promise<boolean> | null = null | ||
| let aiProxyKubeconfig: string | null = null | ||
| let aiProxyKubeconfigTask: Promise<string | null> | null = null | ||
|
|
||
| export function registerAiProxyKubeconfig(kubeconfig: string): void { | ||
| const normalizedKubeconfig = kubeconfig.trim() | ||
|
|
||
| if (normalizedKubeconfig) { | ||
| aiProxyKubeconfig = normalizedKubeconfig | ||
| } | ||
| } | ||
|
|
||
| export function registerAiProxyKubeconfigTask(task: Promise<string | null | undefined>): void { | ||
| aiProxyKubeconfigTask = task | ||
| .then((kubeconfig) => { | ||
| const normalizedKubeconfig = kubeconfig?.trim() || null | ||
|
|
||
| if (normalizedKubeconfig) { | ||
| aiProxyKubeconfig = normalizedKubeconfig | ||
| } | ||
|
|
||
| return normalizedKubeconfig | ||
| }) | ||
| .catch(() => null) | ||
| } | ||
|
|
||
| export function getAiProxyProvisioningTask(runProvisioning: () => Promise<boolean>): Promise<boolean> { | ||
| if (!aiProxyProvisioningTask) { | ||
| aiProxyProvisioningTask = runProvisioning() | ||
| .catch(() => false) | ||
| .finally(() => { | ||
| aiProxyProvisioningTask = null | ||
| }) | ||
| } | ||
|
|
||
| return aiProxyProvisioningTask | ||
| } | ||
|
|
||
| async function resolveAiProxyKubeconfig(): Promise<string | null> { | ||
| if (aiProxyKubeconfig) { | ||
| return aiProxyKubeconfig | ||
| } | ||
|
|
||
| if (!aiProxyKubeconfigTask) { | ||
| return null | ||
| } | ||
|
|
||
| return await aiProxyKubeconfigTask | ||
| } | ||
|
|
||
| async function requestAiProxyProvisioning(kubeconfig: string | null): Promise<boolean> { | ||
| const response = await fetch('/api/aiproxy/provision', { | ||
| body: JSON.stringify(kubeconfig ? { kubeconfig } : {}), | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| method: 'POST', | ||
| }) | ||
|
|
||
| if (!response.ok) { | ||
| return false | ||
| } | ||
|
|
||
| const body = (await response.json().catch(() => null)) as { success?: unknown } | null | ||
| return body?.success === true | ||
| } | ||
|
|
||
| export async function ensureAiProxyProvisioned(): Promise<boolean> { | ||
| const kubeconfig = await resolveAiProxyKubeconfig() | ||
| return await getAiProxyProvisioningTask(() => requestAiProxyProvisioning(kubeconfig)) | ||
| } | ||
|
|
||
| export function resetAiProxyProvisioningTaskForTests(): void { | ||
| aiProxyProvisioningTask = null | ||
| aiProxyKubeconfig = null | ||
| aiProxyKubeconfigTask = null | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| export const AIPROXY_AUTO_TOKEN_NAME = 'shiprepo' | ||
| export const AIPROXY_MODEL_BASE_URL = 'https://aiproxy.usw-1.sealos.io/v1' | ||
| export const AIPROXY_TOKEN_MANAGEMENT_BASE_URL = 'https://aiproxy-web.usw-1.sealos.io/api/v2alpha' |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This new early-return blocks task creation whenever
ensureAiProxyProvisioned()fails, even though task execution can still succeed via the existing AI Gateway fallback path (resolveCodexGatewayFromApiKeysusesAI_GATEWAY_API_KEYwhen no AIProxy key is present). In environments where Sealos session/kubeconfig is unavailable (or temporarily fails), users now get a hard client-side stop instead of creating a valid task, so provisioning should be conditional rather than mandatory.Useful? React with 👍 / 👎.