Add an AIGen-only generate API for external tools.
Cursor and similar clients can enqueue Studio 2 stills with the same steps and CFG the bench uses, through session or AIGEN_API_KEY. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
import { filterLoraStackForUse } from '~/utils/loras'
|
||||
import { validateRequest } from '~/shared/studio2/contracts.mjs'
|
||||
import { defaultLibraryFolderId, isStudio2ImageEngine, studio2EngineDefaults } from '~/shared/studio2/engine-defaults.mjs'
|
||||
import { resolveRequestSize } from '../../utils/studio2/size'
|
||||
import { parsePostedLoraStack, assertImageV2LoraStack } from '../../utils/loras'
|
||||
import { saveRecord, readRecord } from '../../utils/studio2/store'
|
||||
import { addStudioJob, kickStudioQueue, type StudioJobPayload } from '../../utils/studioQueue'
|
||||
import { isXaigenStudio } from '~/utils/videoModels'
|
||||
import { assertAigenApiAccess } from '~/server/utils/aigenApi'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const { owner, catalog } = assertAigenApiAccess(event)
|
||||
const rawBody = await readBody(event).catch(() => ({}))
|
||||
const body = rawBody && typeof rawBody === 'object' ? rawBody as Record<string, unknown> : {}
|
||||
|
||||
const prompt = String(body.prompt || '').trim()
|
||||
if (!prompt) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'A prompt is required' })
|
||||
}
|
||||
|
||||
const engine = String(body.engine || 'flux').trim().toLowerCase() || 'flux'
|
||||
if (!isStudio2ImageEngine(engine)) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'engine must be flux, krea, qwen21, or moss' })
|
||||
}
|
||||
|
||||
const mode = String(body.mode || 'generate').trim().toLowerCase() || 'generate'
|
||||
if (mode !== 'generate') {
|
||||
throw createError({ statusCode: 400, statusMessage: 'mode must be generate' })
|
||||
}
|
||||
|
||||
const defaults = studio2EngineDefaults(engine)
|
||||
const steps = body.steps == null || body.steps === ''
|
||||
? defaults.steps
|
||||
: Number(body.steps)
|
||||
const cfg = body.cfg == null || body.cfg === ''
|
||||
? defaults.cfg
|
||||
: Number(body.cfg)
|
||||
if (!Number.isFinite(steps) || !Number.isInteger(steps)) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'steps must be an integer' })
|
||||
}
|
||||
if (!Number.isFinite(cfg)) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'cfg must be a number' })
|
||||
}
|
||||
|
||||
const aspect = String(body.aspect || defaults.aspect || 'auto').trim() || defaults.aspect
|
||||
const folderId = defaultLibraryFolderId(catalog, body.folderId == null ? '' : String(body.folderId))
|
||||
if (!folderId) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'Create a library folder before generating' })
|
||||
}
|
||||
|
||||
const seedRaw = body.seed
|
||||
const seedSet = seedRaw != null && String(seedRaw) !== ''
|
||||
const seed = seedSet ? Number(seedRaw) : null
|
||||
if (seedSet && !Number.isFinite(seed)) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'seed must be a number' })
|
||||
}
|
||||
|
||||
const xaigen = isXaigenStudio()
|
||||
const requestRaw = {
|
||||
mode: 'generate',
|
||||
engine,
|
||||
folderId,
|
||||
promptSections: { action: prompt },
|
||||
settings: {
|
||||
aspect,
|
||||
steps,
|
||||
cfg,
|
||||
seed,
|
||||
seedMode: seedSet ? 'locked' : 'random',
|
||||
loraStack: []
|
||||
}
|
||||
}
|
||||
|
||||
let request: any
|
||||
try {
|
||||
request = validateRequest(requestRaw, xaigen)
|
||||
} catch (e: any) {
|
||||
throw createError({ statusCode: e.statusCode || 400, statusMessage: e.message })
|
||||
}
|
||||
|
||||
request.settings.loraStack = parsePostedLoraStack(request.settings.loraStack, 'image')
|
||||
request.settings.loraStack = filterLoraStackForUse(request.settings.loraStack, request.engine, xaigen)
|
||||
if (request.engine !== 'qwen21') assertImageV2LoraStack(request.settings.loraStack, request.engine)
|
||||
assertFolderAccess(event, request.folderId)
|
||||
try {
|
||||
await resolveRequestSize(owner, request)
|
||||
} catch (e: any) {
|
||||
const message = e?.statusMessage || e?.message || 'Could not resolve size'
|
||||
throw createError({
|
||||
statusCode: e?.statusCode || 400,
|
||||
statusMessage: message
|
||||
})
|
||||
}
|
||||
|
||||
const id = crypto.randomUUID()
|
||||
const record = {
|
||||
id,
|
||||
owner,
|
||||
request,
|
||||
state: 'waiting',
|
||||
queuedAt: Date.now(),
|
||||
familyId: crypto.randomUUID(),
|
||||
outputs: [],
|
||||
purgeResult: 'Not yet saved'
|
||||
}
|
||||
saveRecord(record)
|
||||
void (async () => {
|
||||
try {
|
||||
const row = await addStudioJob({
|
||||
ownerKey: owner,
|
||||
kind: 'edit',
|
||||
familyId: record.familyId,
|
||||
payload: {
|
||||
...request.settings,
|
||||
engine: request.engine,
|
||||
studio2Id: id,
|
||||
studio2Request: structuredClone(request),
|
||||
prompt: request.compiledPrompt,
|
||||
folderId: request.folderId,
|
||||
extensions: [],
|
||||
referenceStillIds: [],
|
||||
useIdentityRefs: false,
|
||||
queueAutoRun: true
|
||||
} as StudioJobPayload
|
||||
})
|
||||
saveRecord({ ...readRecord(owner, id), queueId: row.id })
|
||||
} catch { /* poll / resume will pick up waiting studio2 records */ }
|
||||
kickStudioQueue()
|
||||
})()
|
||||
|
||||
return {
|
||||
id,
|
||||
engine: request.engine,
|
||||
steps: request.settings.steps,
|
||||
cfg: request.settings.cfg,
|
||||
aspect: request.settings.aspect,
|
||||
folderId: request.folderId,
|
||||
status: 'waiting' as const
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import { jobView } from '~/shared/studio2/queue-view.mjs'
|
||||
import { getJob } from '../../../utils/jobs'
|
||||
import { readRecord } from '../../../utils/studio2/store'
|
||||
import { listStudioJobs } from '../../../utils/studioQueue'
|
||||
import { assertAigenApiAccess } from '~/server/utils/aigenApi'
|
||||
|
||||
export default defineEventHandler((event) => {
|
||||
const { owner } = assertAigenApiAccess(event)
|
||||
const id = String(getRouterParam(event, 'id') || '')
|
||||
let record: any
|
||||
try {
|
||||
record = readRecord(owner, id)
|
||||
} catch (e: any) {
|
||||
throw createError({
|
||||
statusCode: e?.statusCode || 404,
|
||||
statusMessage: e?.statusMessage || 'Job not found'
|
||||
})
|
||||
}
|
||||
|
||||
const queue = listStudioJobs(owner).find(row => row.id === record.queueId)
|
||||
const live = record.liveId ? getJob(record.liveId) : null
|
||||
const view = jobView(record, queue, live)
|
||||
const still = (record.outputs || []).find((item: any) => item?.id && item.kind !== 'clip' && item.kind !== 'track')
|
||||
|| (record.outputs || []).find((item: any) => item?.id)
|
||||
const stillId = still?.id ? String(still.id) : undefined
|
||||
|
||||
return {
|
||||
id: record.id,
|
||||
state: view.state,
|
||||
engine: record.request?.engine || '',
|
||||
steps: record.request?.settings?.steps,
|
||||
cfg: record.request?.settings?.cfg,
|
||||
...(view.error ? { error: view.error } : {}),
|
||||
...(stillId ? { stillId, stillUrl: `/api/library/stills/${stillId}` } : {})
|
||||
}
|
||||
})
|
||||
@@ -1,3 +1,6 @@
|
||||
import { aigenApiPathAllowed, aigenBearerAuthorized } from '~/server/utils/aigenApiAuth'
|
||||
import { isXaigenStudio } from '~/utils/videoModels'
|
||||
|
||||
export default defineEventHandler((event) => {
|
||||
if (!authEnabled()) return
|
||||
const path = getRequestURL(event).pathname
|
||||
@@ -15,6 +18,10 @@ export default defineEventHandler((event) => {
|
||||
) {
|
||||
return
|
||||
}
|
||||
const method = String(event.method || getMethod(event) || 'GET').toUpperCase()
|
||||
if (!isXaigenStudio() && aigenApiPathAllowed(path, method) && aigenBearerAuthorized(event)) {
|
||||
return
|
||||
}
|
||||
const user = getSessionUser(event)
|
||||
if (user) return
|
||||
if (path.startsWith('/api/')) {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { H3Event } from 'h3'
|
||||
import { assertLibraryOwner } from '~/server/utils/library'
|
||||
import {
|
||||
aigenBearerAuthorized,
|
||||
aigenInstanceOwnerKey,
|
||||
assertAigenFeature
|
||||
} from '~/server/utils/aigenApiAuth'
|
||||
|
||||
export {
|
||||
aigenApiKeyConfigured,
|
||||
aigenApiPathAllowed,
|
||||
aigenBearerAuthorized,
|
||||
aigenInstanceOwnerKey,
|
||||
assertAigenFeature
|
||||
} from '~/server/utils/aigenApiAuth'
|
||||
export { defaultLibraryFolderId as defaultAigenFolderId } from '~/shared/studio2/engine-defaults.mjs'
|
||||
|
||||
/**
|
||||
* Session (assertLibraryOwner) or Authorization: Bearer <AIGEN_API_KEY>.
|
||||
* Bearer runs as the instance library owner. xAIGen is 404.
|
||||
*/
|
||||
export function assertAigenApiAccess(event: H3Event) {
|
||||
assertAigenFeature()
|
||||
if (aigenBearerAuthorized(event)) {
|
||||
// libraryOwnerKey already maps this bearer to aigenInstanceOwnerKey()
|
||||
const { owner, catalog } = assertLibraryOwner(event)
|
||||
return { owner, catalog, auth: 'bearer' as const, instanceOwner: aigenInstanceOwnerKey() }
|
||||
}
|
||||
try {
|
||||
const { owner, catalog } = assertLibraryOwner(event)
|
||||
return { owner, catalog, auth: 'session' as const }
|
||||
} catch (e: any) {
|
||||
if (Number(e?.statusCode) === 401) {
|
||||
throw createError({ statusCode: 401, statusMessage: 'Authentication required' })
|
||||
}
|
||||
throw e
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { createHash, timingSafeEqual } from 'node:crypto'
|
||||
import type { H3Event } from 'h3'
|
||||
import { isXaigenStudio } from '~/utils/videoModels'
|
||||
import { passwordAuthEnabled, privateInstanceId } from '~/server/utils/localAuth'
|
||||
|
||||
function configuredApiKey() {
|
||||
const config = useRuntimeConfig()
|
||||
return String((config as { aigenApiKey?: string }).aigenApiKey || process.env.AIGEN_API_KEY || '').trim()
|
||||
}
|
||||
|
||||
function safeEqual(left: string, right: string) {
|
||||
const a = Buffer.from(left)
|
||||
const b = Buffer.from(right)
|
||||
if (a.length !== b.length) return false
|
||||
try {
|
||||
return timingSafeEqual(a, b)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** Owner key for bearer calls — same catalog as a no-session / password instance. */
|
||||
export function aigenInstanceOwnerKey() {
|
||||
if (passwordAuthEnabled()) return privateInstanceId()
|
||||
return createHash('sha256').update('local').digest('hex').slice(0, 24)
|
||||
}
|
||||
|
||||
export function aigenApiKeyConfigured() {
|
||||
return Boolean(configuredApiKey())
|
||||
}
|
||||
|
||||
export function aigenBearerAuthorized(event: H3Event) {
|
||||
if (isXaigenStudio()) return false
|
||||
const expected = configuredApiKey()
|
||||
if (!expected) return false
|
||||
const header = String(getHeader(event, 'authorization') || '')
|
||||
const match = header.match(/^Bearer\s+(.+)$/i)
|
||||
if (!match) return false
|
||||
return safeEqual(match[1].trim(), expected)
|
||||
}
|
||||
|
||||
export function aigenApiPathAllowed(path: string, method: string) {
|
||||
if (path === '/api/aigen' || path.startsWith('/api/aigen/')) return true
|
||||
if (method === 'GET' && (path === '/api/library/stills' || path.startsWith('/api/library/stills/'))) return true
|
||||
return false
|
||||
}
|
||||
|
||||
export function assertAigenFeature() {
|
||||
if (isXaigenStudio()) {
|
||||
throw createError({ statusCode: 404, statusMessage: 'Not found' })
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
} from '~/utils/keepPrompts'
|
||||
import { familyBaseName, nextClipPartName, clipPartLabel } from '~/utils/libraryBrowse'
|
||||
import { musicExtension } from '~/utils/music'
|
||||
import { aigenBearerAuthorized, aigenInstanceOwnerKey } from '~/server/utils/aigenApiAuth'
|
||||
|
||||
export { familyBaseName, nextClipPartName, clipPartLabel }
|
||||
|
||||
@@ -197,6 +198,8 @@ export function libraryRoot() {
|
||||
|
||||
export function libraryOwnerKey(event: H3Event) {
|
||||
if (passwordAuthEnabled()) return privateInstanceId()
|
||||
// AIGen API key: same catalog as the unauthenticated local owner. Never invent a second tree.
|
||||
if (aigenBearerAuthorized(event)) return aigenInstanceOwnerKey()
|
||||
const user = getSessionUser(event)
|
||||
const raw = user?.sub || user?.email || (!authEnabled() ? 'local' : '')
|
||||
if (!raw) {
|
||||
|
||||
Reference in New Issue
Block a user