🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(openapi): text, JSON, image, video, speech and transcription generation API (#23267)
Arvin Xu737d68659b5c
diff --git a/apps/server/src/services/aiGeneration/index.test.ts b/apps/server/src/services/aiGeneration/index.test.tsindex 046e53dff70..517b9db7ecb 100644--- a/apps/server/src/services/aiGeneration/index.test.ts+++ b/apps/server/src/services/aiGeneration/index.test.ts@@ -186,3 +186,84 @@ describe('AiGenerationService.decide', () => {expect(result).toBe(response);});});++describe('AiGenerationService.generateText', () => {+ const chat = vi.fn();+ const initSpy = vi.spyOn(ModelRuntimeModule, 'initModelRuntimeFromDB');++ /** A runtime whose stream calls the given callbacks once it is drained. */+ const streamWith = (emit: (callback: any) => void) =>+ chat.mockImplementation(+ async (_payload: unknown, options: { callback: any }) =>+ new Response(+ new ReadableStream({+ start(controller) {+ controller.enqueue(new TextEncoder().encode('data: "x"\n\n'));+ emit(options.callback);+ controller.close();+ },+ }),+ ),+ );++ beforeEach(() => {+ chat.mockReset();+ initSpy.mockReset();+ initSpy.mockResolvedValue({ chat } as any);+ });++ it('streams one completion and returns the text with reasoning kept apart', async () => {+ streamWith((callback) =>+ callback.onFinal({+ finishReason: 'stop',+ text: 'Pegboard',+ thinking: 'One word is enough.',+ usage: { totalTokens: 9 },+ }),+ );++ const ai = new AiGenerationService({} as any, 'user-1', 'ws-1');+ const result = await ai.generateText(+ {+ maxTokens: 20,+ messages: [{ content: 'one word?', role: 'user' }],+ model: 'deepseek-flash',+ provider: 'lobehub',+ temperature: 0,+ },+ { metadata: { trigger: RequestTrigger.Api } },+ );++ expect(initSpy).toHaveBeenCalledWith({}, 'user-1', 'lobehub', 'ws-1');+ expect(chat.mock.calls[0][0]).toEqual({+ max_tokens: 20,+ messages: [{ content: 'one word?', role: 'user' }],+ model: 'deepseek-flash',+ stream: true,+ temperature: 0,+ });+ expect(chat.mock.calls[0][1].metadata).toEqual({ trigger: RequestTrigger.Api });+ expect(result).toEqual({+ finishReason: 'stop',+ reasoning: 'One word is enough.',+ text: 'Pegboard',+ usage: { totalTokens: 9 },+ });+ });++ it('throws the stream error instead of returning partial text', async () => {+ const failure = { errorType: 'ProviderBizError' };+ streamWith((callback) => {+ callback.onError(failure);+ callback.onFinal({ text: 'partial' });+ });++ const ai = new AiGenerationService({} as any, 'user-1');+ await expect(+ ai.generateText(+ { messages: [{ content: 'hi', role: 'user' }], model: 'm', provider: 'p' },+ { metadata: { trigger: RequestTrigger.Api } },+ ),+ ).rejects.toBe(failure);+ });+});diff --git a/apps/server/src/services/aiGeneration/index.ts b/apps/server/src/services/aiGeneration/index.tsindex e178c837654..16bcde90b06 100644--- a/apps/server/src/services/aiGeneration/index.ts+++ b/apps/server/src/services/aiGeneration/index.ts@@ -1,12 +1,14 @@import type {ChatCompletionTool,+ ChatStreamPayload,DecisionPayload,DecisionQuestions,DecisionResponse,GenerateObjectPayload,GenerateObjectSchema,+ OnFinishData,} from '@lobechat/model-runtime';-import type { OpenAIChatMessage, RequestTrigger } from '@lobechat/types';+import type { ModelUsage, OpenAIChatMessage, RequestTrigger } from '@lobechat/types';import type { LobeChatDatabase } from '@/database/type';import { initModelRuntimeForRequest } from '@/server/modules/AgentRuntime/llmRelay/oneShot';@@ -21,6 +23,22 @@ export interface AiGenerationObjectInput {tools?: ChatCompletionTool[];}+export interface AiGenerationTextInput {+ maxTokens?: number;+ messages: OpenAIChatMessage[];+ model: string;+ provider: string;+ temperature?: number;+}++export interface AiGenerationTextResult {+ finishReason?: string;+ /** The model's reasoning, kept apart from `text` (reasoning models only). */+ reasoning?: string;+ text: string;+ usage?: ModelUsage;+}+export interface AiGenerationDecisionInput<Q extends DecisionQuestions = DecisionQuestions,> extends DecisionPayload<Q> {@@ -94,6 +112,60 @@ export class AiGenerationService {)) as T;}+ /**+ * One plain-text completion: the answer text, with any reasoning, usage and+ * finish reason reported separately (nothing is spliced into `text`).+ *+ * Runs on the server only, like {@link decide}: the stream is consumed here+ * and `onFinal` carries the assembled result, so providers that only stream+ * behave the same as those that do not.+ */+ async generateText(+ input: AiGenerationTextInput,+ options: AiGenerationObjectOptions,+ ): Promise<AiGenerationTextResult> {+ const runtime = await initModelRuntimeFromDB(+ this.db,+ this.userId,+ input.provider,+ this.workspaceId,+ );+ const payload: ChatStreamPayload = {+ max_tokens: input.maxTokens,+ messages: input.messages as ChatStreamPayload['messages'],+ model: input.model,+ stream: true,+ temperature: input.temperature ?? 1,+ };++ let final: OnFinishData | undefined;+ let streamError: unknown;+ const response = await runtime.chat(payload, {+ callback: {+ onError: (error) => {+ streamError = error;+ },+ onFinal: (data) => {+ final = data;+ },+ },+ metadata: options.metadata,+ signal: options.signal,+ });+ // Drain the stream so the callbacks (and billing / tracing hooks) run.+ await response.body?.pipeTo(new WritableStream());++ if (streamError ?? final?.error) throw streamError ?? final!.error;+ if (!final) throw new Error('The model stream ended without a final result');++ return {+ finishReason: final.finishReason,+ reasoning: final.thinking || final.reasoning?.content || undefined,+ text: final.text,+ usage: final.usage,+ };+ }+/*** Asks typed questions about one state (`ModelRuntime.decide`): natively for decision models,* emulated through `generateObject` for chat models.diff --git a/locales/en-US/auth.json b/locales/en-US/auth.jsonindex b9a7bec1f04..be6842c0989 100644--- a/locales/en-US/auth.json+++ b/locales/en-US/auth.json@@ -68,6 +68,7 @@"apikey.scopes.groups.agent": "Agents","apikey.scopes.groups.chat": "Chat","apikey.scopes.groups.file": "Files",+ "apikey.scopes.groups.generation": "Generation","apikey.scopes.groups.knowledge": "Knowledge","apikey.scopes.groups.mcp": "MCP servers","apikey.scopes.groups.model": "Models",diff --git a/locales/en-US/oauth.json b/locales/en-US/oauth.jsonindex f5ef8bffbcc..6cf5b445275 100644--- a/locales/en-US/oauth.json+++ b/locales/en-US/oauth.json@@ -37,6 +37,8 @@"consent.scope.acceptance-review": "Comment on this acceptance and accept or send it back from its preview page","consent.scope.acceptance-review-site": "Comment on this site’s acceptance from the site itself, for 8 hours","consent.scope.email": "Access your email address",+ "consent.scope.generation-read": "View your generated images, videos and audio",+ "consent.scope.generation-write": "Generate images, videos and audio and delete the results, using your quota","consent.scope.offline_access": "Allow the client to access your data","consent.scope.openid": "Authenticate using your LobeHub account","consent.scope.profile": "Access your basic profile information (name, avatar, etc.)",diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.jsonindex 83c4c855bd9..e409ace48ab 100644--- a/locales/zh-CN/auth.json+++ b/locales/zh-CN/auth.json@@ -68,6 +68,7 @@"apikey.scopes.groups.agent": "助手","apikey.scopes.groups.chat": "会话","apikey.scopes.groups.file": "文件",+ "apikey.scopes.groups.generation": "生成","apikey.scopes.groups.knowledge": "知识库","apikey.scopes.groups.mcp": "MCP 服务器","apikey.scopes.groups.model": "模型",diff --git a/locales/zh-CN/oauth.json b/locales/zh-CN/oauth.jsonindex 47036c0a91c..4b2aea6fca5 100644--- a/locales/zh-CN/oauth.json+++ b/locales/zh-CN/oauth.json@@ -37,6 +37,8 @@"consent.scope.acceptance-review": "在预览页上评论这张验收单,并通过或打回","consent.scope.acceptance-review-site": "在站点上直接评论该站点的验收,有效期 8 小时","consent.scope.email": "访问你的电子邮件地址",+ "consent.scope.generation-read": "查看你生成的图片、视频和音频",+ "consent.scope.generation-write": "生成图片、视频和音频并删除生成结果,消耗你的额度","consent.scope.offline_access": "允许客户端访问你的数据","consent.scope.openid": "使用你的 LobeHub 账户进行身份验证","consent.scope.profile": "访问你的基本资料信息(名称、头像等)",diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex cef5d7bafeb..c470eff0204 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -20,6 +20,8 @@ export const API_KEY_FULL_ACCESS_SCOPE = '*';/*** The selectable scope catalog. `model:invoke` is its own tier because it is* the one that burns money (chat/completions, image, video, music, asr).+ * On the public REST API, text / JSON / image / video generation, speech and+ * transcription spend credits under `generation:write` instead.** Deliberately absent (a restricted key can never obtain them):* - `api_key:*` — keys must not mint keys (self-provisioning)@@ -49,6 +51,17 @@ export const API_KEY_SCOPES = ['file:write','knowledge:read','knowledge:write',+ /**+ * Text, JSON (structured output), image and video generation, text-to-speech+ * and transcription on the public REST API (`/api/v1/text`, `/api/v1/objects`,+ * `/api/v1/images`, `/api/v1/videos`, `/api/v1/generations`, `/api/v1/audio`).+ * `generation:write` starts paid generations and deletes generated assets;+ * `generation:read` reads their status and results. Text / JSON generation and+ * speech also accept keys issued with `model:invoke`. The tRPC generation+ * namespaces keep requiring `model:invoke`.+ */+ 'generation:read',+ 'generation:write','mcp:read','mcp:write','usage:read',diff --git a/packages/database/src/models/__tests__/generation.queryWithBatch.test.ts b/packages/database/src/models/__tests__/generation.queryWithBatch.test.tsnew file mode 100644index 00000000000..181bdaf1c71--- /dev/null+++ b/packages/database/src/models/__tests__/generation.queryWithBatch.test.ts@@ -0,0 +1,165 @@+// @vitest-environment node+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import {+ asyncTasks,+ generationBatches,+ generations,+ generationTopics,+ users,+ workspaceMembers,+ workspaces,+} from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import type { GenerationModel as GenerationModelType } from '../generation';++const serverDB: LobeChatDatabase = await getTestDB();++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(function () {+ return {};+ }),+}));++const userId = 'gen-query-user';+const otherUserId = 'gen-query-other';+const workspaceId = 'gen-query-ws';+let GenerationModel: typeof GenerationModelType;++// The server-db suite runs with `isolate: false`; load a fresh copy bound to this+// file's FileService mock and leave no mocked module behind (see generation.music.test.ts).+beforeAll(async () => {+ vi.resetModules();+ ({ GenerationModel } = await import('../generation'));+});++afterAll(() => {+ vi.doUnmock('@/server/services/file');+ vi.resetModules();+});++/** One topic of `type` with one batch holding `count` generations, oldest first. */+const seed = async (+ owner: string,+ type: 'image' | 'video',+ count: number,+ options: { minuteOffset?: number; workspaceId?: string } = {},+) => {+ const scope = { userId: owner, workspaceId: options.workspaceId ?? null };+ const [topic] = await serverDB+ .insert(generationTopics)+ .values({ ...scope, title: `${type} topic`, type })+ .returning();+ const [batch] = await serverDB+ .insert(generationBatches)+ .values({+ ...scope,+ generationTopicId: topic.id,+ model: `${type}-model`,+ prompt: `a ${type}`,+ provider: 'provider',+ })+ .returning();++ const ids: string[] = [];+ for (let i = 0; i < count; i++) {+ const [task] = await serverDB+ .insert(asyncTasks)+ .values({ ...scope, status: 'pending', type })+ .returning();+ const [row] = await serverDB+ .insert(generations)+ .values({+ ...scope,+ asyncTaskId: task.id,+ createdAt: new Date(Date.UTC(2026, 0, 1, 0, (options.minuteOffset ?? 0) + i)),+ generationBatchId: batch.id,+ })+ .returning();+ ids.push(row.id);+ }+ return { batch, ids, topic };+};++beforeEach(async () => {+ await serverDB.delete(generations);+ await serverDB.delete(generationBatches);+ await serverDB.delete(generationTopics);+ await serverDB.delete(asyncTasks);+ await serverDB.delete(workspaceMembers);+ await serverDB.delete(workspaces);+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'Query', primaryOwnerId: userId, slug: 'gen-query' });+});++describe('GenerationModel.queryWithBatch', () => {+ it("pages the caller's generations newest first with their batch and topic kind", async () => {+ const images = await seed(userId, 'image', 2);+ const videos = await seed(userId, 'video', 1, { minuteOffset: 10 });+ await seed(otherUserId, 'image', 3, { minuteOffset: 20 });+ const model = new GenerationModel(serverDB, userId);++ const first = await model.queryWithBatch({ limit: 2, offset: 0 });+ expect(first.total).toBe(3);+ expect(first.items.map((item) => item.id)).toEqual([videos.ids[0], images.ids[1]]);+ expect(first.items[0]).toMatchObject({+ asyncTask: { status: 'pending' },+ batch: {+ generationTopicId: videos.topic.id,+ id: videos.batch.id,+ model: 'video-model',+ prompt: 'a video',+ provider: 'provider',+ topic: { type: 'video' },+ },+ });++ const second = await model.queryWithBatch({ limit: 2, offset: 2 });+ expect(second.items.map((item) => item.id)).toEqual([images.ids[0]]);+ });++ it('narrows to one kind', async () => {+ await seed(userId, 'image', 2);+ const videos = await seed(userId, 'video', 1);+ const model = new GenerationModel(serverDB, userId);++ const result = await model.queryWithBatch({ limit: 20, offset: 0, type: 'video' });+ expect(result).toMatchObject({ total: 1 });+ expect(result.items.map((item) => item.id)).toEqual(videos.ids);+ });++ it('keeps personal and workspace generations apart', async () => {+ const personal = await seed(userId, 'image', 1);+ const shared = await seed(userId, 'image', 1, { workspaceId });++ const inPersonal = await new GenerationModel(serverDB, userId).queryWithBatch({+ limit: 20,+ offset: 0,+ });+ const inWorkspace = await new GenerationModel(serverDB, userId, workspaceId).queryWithBatch({+ limit: 20,+ offset: 0,+ });++ expect(inPersonal.items.map((item) => item.id)).toEqual(personal.ids);+ expect(inWorkspace.items.map((item) => item.id)).toEqual(shared.ids);+ });+});++describe('GenerationModel.findByIdsWithBatch', () => {+ it('returns the visible rows in the order asked, skipping others', async () => {+ const mine = await seed(userId, 'image', 2);+ const theirs = await seed(otherUserId, 'image', 1);+ const model = new GenerationModel(serverDB, userId);++ const rows = await model.findByIdsWithBatch([mine.ids[1], theirs.ids[0], mine.ids[0]]);++ expect(rows.map((row) => row.id)).toEqual([mine.ids[1], mine.ids[0]]);+ expect(rows[0].batch.topic).toEqual({ type: 'image' });+ expect(await model.findByIdsWithBatch([])).toEqual([]);+ });+});diff --git a/packages/database/src/models/generation.ts b/packages/database/src/models/generation.tsindex f94df8acfad..9a409159203 100644--- a/packages/database/src/models/generation.ts+++ b/packages/database/src/models/generation.ts@@ -10,12 +10,17 @@ import type {} from '@lobechat/types';import { FileSource } from '@lobechat/types';import debug from 'debug';-import { and, eq, exists } from 'drizzle-orm';+import { and, count, desc, eq, exists, inArray } from 'drizzle-orm';import { FileService } from '@/server/services/file';import type { NewFile } from '../schemas';-import type { GenerationItem, GenerationWithAsyncTask, NewGeneration } from '../schemas/generation';+import type {+ GenerationBatchItem,+ GenerationItem,+ GenerationWithAsyncTask,+ NewGeneration,+} from '../schemas/generation';import { generationBatches, generations, generationTopics } from '../schemas/generation';import type { LobeChatDatabase, Transaction } from '../type';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';@@ -24,6 +29,20 @@ import { FileModel } from './file';// Create debug loggerconst log = debug('lobe-image:generation-model');+export type GenerationKind = 'image' | 'music' | 'video';++/** A generation with its async task and the batch (and topic kind) it belongs to. */+export type GenerationWithBatch = GenerationWithAsyncTask & {+ batch: Pick<GenerationBatchItem, 'generationTopicId' | 'id' | 'model' | 'prompt' | 'provider'> & {+ topic: { type: string } | null;+ };+};++const BATCH_RELATION = {+ columns: { generationTopicId: true, id: true, model: true, prompt: true, provider: true },+ with: { topic: { columns: { type: true } } },+} as const;+export class GenerationModel {private db: LobeChatDatabase;private userId: string;@@ -180,6 +199,66 @@ export class GenerationModel {});}+ /** The visible generations among `ids`, in the order of `ids`. */+ async findByIdsWithBatch(ids: string[]): Promise<GenerationWithBatch[]> {+ if (ids.length === 0) return [];++ const rows = (await this.db.query.generations.findMany({+ where: and(inArray(generations.id, ids), this.ownership()),+ with: { asyncTask: true, batch: BATCH_RELATION },+ })) as GenerationWithBatch[];+ const byId = new Map(rows.map((row) => [row.id, row]));+ return ids.flatMap((id) => byId.get(id) ?? []);+ }++ /**+ * The caller's generations, newest first, optionally narrowed to one kind+ * (the kind of the topic they were generated in).+ */+ async queryWithBatch({+ limit,+ offset,+ type,+ }: {+ limit: number;+ offset: number;+ type?: GenerationKind;+ }): Promise<{ items: GenerationWithBatch[]; total: number }> {+ const where = type+ ? and(+ this.ownership(),+ exists(+ this.db+ .select({ id: generationBatches.id })+ .from(generationBatches)+ .innerJoin(+ generationTopics,+ eq(generationTopics.id, generationBatches.generationTopicId),+ )+ .where(+ and(+ eq(generationBatches.id, generations.generationBatchId),+ eq(generationTopics.type, type),+ ),+ ),+ ),+ )+ : this.ownership();++ const [items, [{ total }]] = await Promise.all([+ this.db.query.generations.findMany({+ limit,+ offset,+ orderBy: [desc(generations.createdAt), desc(generations.id)],+ where,+ with: { asyncTask: true, batch: BATCH_RELATION },+ }),+ this.db.select({ total: count() }).from(generations).where(where),+ ]);++ return { items: items as GenerationWithBatch[], total };+ }+async findByAsyncTaskId(asyncTaskId: string) {log('Finding generation by asyncTaskId: %s', asyncTaskId);diff --git a/packages/locales/src/default/auth.ts b/packages/locales/src/default/auth.tsindex 1430389999a..d1204453dd7 100644--- a/packages/locales/src/default/auth.ts+++ b/packages/locales/src/default/auth.ts@@ -74,6 +74,7 @@ export default {'apikey.scopes.groups.agent': 'Agents','apikey.scopes.groups.chat': 'Chat','apikey.scopes.groups.file': 'Files',+ 'apikey.scopes.groups.generation': 'Generation','apikey.scopes.groups.knowledge': 'Knowledge','apikey.scopes.groups.mcp': 'MCP servers','apikey.scopes.groups.model': 'Models',diff --git a/packages/locales/src/default/oauth.ts b/packages/locales/src/default/oauth.tsindex a3713f91138..3b7a7a6010d 100644--- a/packages/locales/src/default/oauth.ts+++ b/packages/locales/src/default/oauth.ts@@ -34,6 +34,9 @@ export default {'consent.scope.acceptance-review':'Comment on this acceptance and accept or send it back from its preview page','consent.scope.email': 'Access your email address',+ 'consent.scope.generation-read': 'View your generated images, videos and audio',+ 'consent.scope.generation-write':+ 'Generate images, videos and audio and delete the results, using your quota','consent.scope.offline_access': 'Allow the client to access your data','consent.scope.openid': 'Authenticate using your LobeHub account','consent.scope.profile': 'Access your basic profile information (name, avatar, etc.)',diff --git a/packages/openapi/openapi.yml b/packages/openapi/openapi.ymlindex d2db51e5700..ba055fc01a5 100644--- a/packages/openapi/openapi.yml+++ b/packages/openapi/openapi.yml@@ -751,6 +751,8 @@ components:- file:write- knowledge:read- knowledge:write+ - generation:read+ - generation:write- mcp:read- mcp:write- usage:read@@ -817,6 +819,8 @@ components:- file:write- knowledge:read- knowledge:write+ - generation:read+ - generation:write- mcp:read- mcp:write- usage:read@@ -841,6 +845,15 @@ components:- updatedAt- keyadditionalProperties: false+ Transcription:+ type: object+ properties:+ text:+ type: string+ description: The transcript.+ required:+ - text+ additionalProperties: falseChatResponse:type: objectproperties:@@ -9728,6 +9741,127 @@ components:- spent- usageByTypeadditionalProperties: false+ Generation:+ type: object+ properties:+ asset:+ anyOf:+ - $ref: "#/components/schemas/GenerationAsset"+ - type: "null"+ description: The output; `null` until it succeeded.+ batchId:+ type: string+ description: The request (batch) this generation belongs to.+ createdAt:+ type: string+ description: ISO 8601 timestamp.+ error:+ anyOf:+ - $ref: "#/components/schemas/GenerationError"+ - type: "null"+ description: Why it failed; `null` unless `error`.+ fileId:+ description: Library file the output was saved as, once it succeeded.+ type:+ - string+ - "null"+ id:+ type: string+ model:+ type: string+ prompt:+ type: string+ provider:+ type: string+ seed:+ type:+ - number+ - "null"+ status:+ type: string+ enum:+ - pending+ - processing+ - success+ - error+ description: "`pending` → `processing` → `success` | `error`. The last two are+ final."+ topicId:+ type: string+ description: The generation topic the request was added to.+ type:+ type: string+ enum:+ - image+ - video+ - music+ required:+ - asset+ - batchId+ - createdAt+ - error+ - fileId+ - id+ - model+ - prompt+ - provider+ - seed+ - status+ - topicId+ - type+ additionalProperties: false+ GenerationAsset:+ type: object+ properties:+ coverUrl:+ description: Video cover image URL.+ type:+ - string+ - "null"+ duration:+ description: Video length in seconds.+ type:+ - number+ - "null"+ height:+ type:+ - number+ - "null"+ thumbnailUrl:+ description: Resized preview URL.+ type:+ - string+ - "null"+ url:+ description: Full-size asset URL.+ type:+ - string+ - "null"+ width:+ type:+ - number+ - "null"+ required:+ - coverUrl+ - duration+ - height+ - thumbnailUrl+ - url+ - width+ additionalProperties: false+ GenerationError:+ type: object+ properties:+ message:+ type: string+ description: Human-readable failure reason.+ name:+ type: string+ description: Error type, for example `ServerError` or `Timeout`.+ required:+ - message+ - name+ additionalProperties: falsesecuritySchemes:bearerAuth:bearerFormat: API Key (sk-lh-...) or OIDC JWT@@ -13368,6 +13502,8 @@ paths:- file:write- knowledge:read- knowledge:write+ - generation:read+ - generation:write- mcp:read- mcp:write- usage:read@@ -13834,13 +13970,80 @@ paths:call `audio.speech.create`. `model` takes `provider/model` (for example`lobehub/speech-2.8-hd`) or a bare model id; the optional `provider` and`params` (emotion, pitch, volume, sampleRate) are LobeHub extensions.- Returns the audio bytes; usage is reported in `X-LobeHub-*` headers.- Synthesis errors use OpenAI's `{ error: { message, type, code, param }- }` body; authentication and permission errors use the platform- `ApiError` envelope.+ Returns the audio bytes; usage is reported in `X-LobeHub-*` headers. API+ keys need the `generation:write` scope (keys issued with `model:invoke`+ are also accepted). Synthesis errors use OpenAI's `{ error: { message,+ type, code, param } }` body; authentication and permission errors use+ the platform `ApiError` envelope.- **API key scopes:** `model:invoke`.+ **API key scopes:** `generation:write`.+ requestBody:+ content:+ application/json:+ schema:+ type: object+ properties:+ input:+ type: string+ minLength: 1+ maxLength: 4096+ instructions:+ type: string+ model:+ type: string+ minLength: 1+ params:+ type: object+ properties:+ emotion:+ type: string+ minLength: 1+ pitch:+ type: number+ sampleRate:+ type: integer+ exclusiveMinimum: 0+ maximum: 9007199254740991+ volume:+ type: number+ additionalProperties: false+ provider:+ type: string+ minLength: 1+ response_format:+ type: string+ enum:+ - mp3+ - opus+ - aac+ - flac+ - wav+ - pcm+ speed:+ type: number+ minimum: 0.25+ maximum: 4+ stream_format:+ type: string+ enum:+ - audio+ - sse+ voice:+ anyOf:+ - type: string+ minLength: 1+ - type: object+ properties:+ id:+ type: string+ minLength: 1+ required:+ - id+ required:+ - input+ - model+ required: trueresponses:"200":content:@@ -14084,38 +14287,72 @@ paths:tags:- audiox-required-scopes:- - model:invoke+ - generation:writeparameters:- $ref: "#/components/parameters/WorkspaceId"- $ref: "#/components/parameters/IdempotencyKey"- /api/v1/chat:+ /api/v1/audio/transcriptions:post:- operationId: chat.create- summary: Run a non-streaming chat completion+ operationId: audio.createTranscription+ description: >-+ OpenAI-compatible speech-to-text: upload the audio as+ multipart/form-data and get `{ text }` back, so an OpenAI SDK pointed at+ `/api/v1` can call `audio.transcriptions.create`. Send the clip as+ `file` (up to 3 MB), or the id of an uploaded file as `fileId` (the key+ then also needs `file:read`). `provider` (default `openai`) is a LobeHub+ extension. Billing follows the provider configuration, like the in-app+ voice input. The transcript is always returned as JSON `{ text }`,+ whatever `response_format` asks of the provider.+++ **API key scopes:** `generation:write`.+ requestBody:+ content:+ multipart/form-data:+ schema:+ properties:+ file:+ description: The audio clip.+ format: binary+ type: string+ fileId:+ description: An uploaded audio file, instead of `file`.+ type: string+ language:+ description: ISO-639-1 language code, e.g. `en`.+ type: string+ model:+ description: Transcription model, e.g. `whisper-1`.+ type: string+ prompt:+ description: Text to guide the model's style.+ type: string+ provider:+ description: Provider id; defaults to `openai`.+ type: string+ response_format:+ enum:+ - json+ - text+ - srt+ - verbose_json+ - vtt+ type: string+ required:+ - model+ type: object+ required: true+ summary: Create a transcriptiontags:- - chat+ - audioresponses:"200":content:application/json:schema:- type: object- properties:- data:- $ref: "#/components/schemas/ChatResponse"- message:- type: string- success:- type: boolean- const: true- timestamp:- type: string- format: date-time- required:- - data- - success- - timestamp- additionalProperties: false+ $ref: "#/components/schemas/Transcription"+ example:+ text: Remind me to water the plants at six.description: Successful responseheaders:X-Request-Id:@@ -14173,6 +14410,36 @@ paths:$ref: "#/components/headers/RateLimitRemaining"X-RateLimit-Reset:$ref: "#/components/headers/RateLimitReset"+ "404":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Resource not found+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "413":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Payload too large+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset""429":content:application/json:@@ -14205,85 +14472,30 @@ paths:$ref: "#/components/headers/RateLimitRemaining"X-RateLimit-Reset:$ref: "#/components/headers/RateLimitReset"+ "502":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Upstream error+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"x-required-scopes:- - model:invoke- requestBody:- required: true- content:- application/json:- schema:- type: object- properties:- frequency_penalty:- type: number- minimum: -2- maximum: 2- max_tokens:- anyOf:- - type: integer- minimum: 1- maximum: 1000000- - type: "null"- messages:- minItems: 1- maxItems: 1000- type: array- items:- type: object- properties:- content:- type: string- minLength: 1- maxLength: 1000000- role:- type: string- enum:- - user- - assistant- - system- required:- - content- - role- model:- anyOf:- - type: string- minLength: 1- maxLength: 150- - type: "null"- presence_penalty:- type: number- minimum: -2- maximum: 2- provider:- anyOf:- - type: string- minLength: 1- maxLength: 64- - type: "null"- stream:- type:- - boolean- - "null"- temperature:- anyOf:- - type: number- minimum: 0- maximum: 2- - type: "null"- top_p:- type: number- minimum: 0- maximum: 1- required:- - messages+ - generation:writeparameters:- $ref: "#/components/parameters/WorkspaceId"- $ref: "#/components/parameters/IdempotencyKey"- description: "**API key scopes:** `model:invoke`."- /api/v1/chat/translate:+ /api/v1/chat:post:- operationId: chat.createTranslate- summary: Translate text+ operationId: chat.create+ summary: Run a non-streaming chat completiontags:- chatresponses:@@ -14294,7 +14506,199 @@ paths:type: objectproperties:data:- $ref: "#/components/schemas/ChatTranslateResponse"+ $ref: "#/components/schemas/ChatResponse"+ message:+ type: string+ success:+ type: boolean+ const: true+ timestamp:+ type: string+ format: date-time+ required:+ - data+ - success+ - timestamp+ additionalProperties: false+ description: Successful response+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ Idempotent-Replayed:+ $ref: "#/components/headers/IdempotentReplayed"+ "400":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Invalid request+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "401":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Authentication required+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "403":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Insufficient permission+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "429":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Rate limit exceeded+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ Retry-After:+ $ref: "#/components/headers/RetryAfter"+ "500":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Internal server error+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ x-required-scopes:+ - model:invoke+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ frequency_penalty:+ type: number+ minimum: -2+ maximum: 2+ max_tokens:+ anyOf:+ - type: integer+ minimum: 1+ maximum: 1000000+ - type: "null"+ messages:+ minItems: 1+ maxItems: 1000+ type: array+ items:+ type: object+ properties:+ content:+ type: string+ minLength: 1+ maxLength: 1000000+ role:+ type: string+ enum:+ - user+ - assistant+ - system+ required:+ - content+ - role+ model:+ anyOf:+ - type: string+ minLength: 1+ maxLength: 150+ - type: "null"+ presence_penalty:+ type: number+ minimum: -2+ maximum: 2+ provider:+ anyOf:+ - type: string+ minLength: 1+ maxLength: 64+ - type: "null"+ stream:+ type:+ - boolean+ - "null"+ temperature:+ anyOf:+ - type: number+ minimum: 0+ maximum: 2+ - type: "null"+ top_p:+ type: number+ minimum: 0+ maximum: 1+ required:+ - messages+ parameters:+ - $ref: "#/components/parameters/WorkspaceId"+ - $ref: "#/components/parameters/IdempotencyKey"+ description: "**API key scopes:** `model:invoke`."+ /api/v1/chat/translate:+ post:+ operationId: chat.createTranslate+ summary: Translate text+ tags:+ - chat+ responses:+ "200":+ content:+ application/json:+ schema:+ type: object+ properties:+ data:+ $ref: "#/components/schemas/ChatTranslateResponse"message:type: stringsuccess:@@ -41093,3 +41497,1727 @@ paths:parameters:- $ref: "#/components/parameters/WorkspaceId"description: "**API key scopes:** `usage:read`."+ /api/v1/generations:+ get:+ operationId: generations.list+ description: >-+ Lists the image, video and music generations the caller can see, newest+ first. Filter by `type`; page with `cursor` / `limit`.+++ **API key scopes:** `generation:read`.+ summary: List generations+ tags:+ - generations+ responses:+ "200":+ content:+ application/json:+ schema:+ type: object+ properties:+ data:+ type: object+ properties:+ items:+ type: array+ items:+ $ref: "#/components/schemas/Generation"+ hasMore:+ $ref: "#/components/schemas/PageHasMore"+ nextCursor:+ $ref: "#/components/schemas/PageNextCursor"+ total:+ $ref: "#/components/schemas/PageTotal"+ required:+ - items+ - hasMore+ - nextCursor+ - total+ additionalProperties: false+ message:+ type: string+ success:+ type: boolean+ const: true+ timestamp:+ type: string+ format: date-time+ required:+ - data+ - success+ - timestamp+ additionalProperties: false+ example:+ data:+ hasMore: false+ items:+ - asset:+ coverUrl: null+ duration: null+ height: 1024+ thumbnailUrl: https://files.lobehub.com/generations/thumb_2xN8kq.webp+ url: https://files.lobehub.com/generations/2xN8kq.png+ width: 1024+ batchId: gb_q7PzJ2mXc4Ld+ createdAt: 2026-01-15T08:30:00.000Z+ error: null+ fileId: file_8HsW1nVb3QkE+ id: gen_3KdLx9TzQw7v+ model: gpt-image-1+ prompt: A lighthouse on a cliff at dawn, watercolor+ provider: openai+ seed: 42+ status: success+ topicId: gt_Vb5nR2kLp8Ws+ type: image+ nextCursor: null+ total: 1+ success: true+ timestamp: 2026-01-01T00:00:00.000Z+ description: Successful response+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "400":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Invalid request+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "401":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Authentication required+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "403":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Insufficient permission+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "429":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Rate limit exceeded+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ Retry-After:+ $ref: "#/components/headers/RetryAfter"+ "500":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Internal server error+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ x-required-scopes:+ - generation:read+ parameters:+ - in: query+ name: cursor+ schema:+ type: string+ minLength: 1+ maxLength: 512+ description: Opaque cursor from the previous page's `nextCursor`. Omit for the+ first page.+ - in: query+ name: limit+ schema:+ type: integer+ minimum: 1+ maximum: 100+ description: Page size, 1–100. Defaults to 20.+ - in: query+ name: type+ schema:+ type: string+ enum:+ - image+ - video+ - music+ description: Only generations of this kind.+ - $ref: "#/components/parameters/WorkspaceId"+ /api/v1/generations/{id}:+ get:+ operationId: generations.get+ description: >-+ Reports one generation: its `status` (`pending`, `processing`, `success`+ or `error`), the asset URLs once it succeeded, or the failure reason.+ Poll until the status is `success` or `error` — the SDK does this in+ `generations.wait(id)`.+++ **API key scopes:** `generation:read`.+ summary: Get a generation+ tags:+ - generations+ responses:+ "200":+ content:+ application/json:+ schema:+ type: object+ properties:+ data:+ $ref: "#/components/schemas/Generation"+ message:+ type: string+ success:+ type: boolean+ const: true+ timestamp:+ type: string+ format: date-time+ required:+ - data+ - success+ - timestamp+ additionalProperties: false+ example:+ data:+ asset:+ coverUrl: null+ duration: null+ height: 1024+ thumbnailUrl: https://files.lobehub.com/generations/thumb_2xN8kq.webp+ url: https://files.lobehub.com/generations/2xN8kq.png+ width: 1024+ batchId: gb_q7PzJ2mXc4Ld+ createdAt: 2026-01-15T08:30:00.000Z+ error: null+ fileId: file_8HsW1nVb3QkE+ id: gen_3KdLx9TzQw7v+ model: gpt-image-1+ prompt: A lighthouse on a cliff at dawn, watercolor+ provider: openai+ seed: 42+ status: success+ topicId: gt_Vb5nR2kLp8Ws+ type: image+ success: true+ timestamp: 2026-01-01T00:00:00.000Z+ description: Successful response+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "400":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Invalid request+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "401":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Authentication required+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "403":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Insufficient permission+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "404":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Resource not found+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "429":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Rate limit exceeded+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ Retry-After:+ $ref: "#/components/headers/RetryAfter"+ "500":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Internal server error+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ x-required-scopes:+ - generation:read+ parameters:+ - in: path+ name: id+ schema:+ type: string+ minLength: 1+ required: true+ - $ref: "#/components/parameters/WorkspaceId"+ delete:+ operationId: generations.delete+ description: >-+ Deletes a generation record and its thumbnail. The library file it was+ saved as is kept. In a workspace only the creator or a workspace owner+ may delete it.+++ **API key scopes:** `generation:write`.+ summary: Delete a generation+ tags:+ - generations+ responses:+ "200":+ content:+ application/json:+ schema:+ type: object+ properties:+ data:+ $ref: "#/components/schemas/DeletedResource"+ message:+ type: string+ success:+ type: boolean+ const: true+ timestamp:+ type: string+ format: date-time+ required:+ - data+ - success+ - timestamp+ additionalProperties: false+ example:+ data:+ deleted: true+ id: gen_3KdLx9TzQw7v+ success: true+ timestamp: 2026-01-01T00:00:00.000Z+ description: Successful response+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "400":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Invalid request+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "401":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Authentication required+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "403":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Insufficient permission+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "404":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Resource not found+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "429":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Rate limit exceeded+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ Retry-After:+ $ref: "#/components/headers/RetryAfter"+ "500":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Internal server error+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ x-required-scopes:+ - generation:write+ parameters:+ - in: path+ name: id+ schema:+ type: string+ minLength: 1+ required: true+ - $ref: "#/components/parameters/WorkspaceId"+ /api/v1/images/generations:+ post:+ operationId: images.generate+ description: >-+ Generates `n` images from a prompt with an image model (the account's+ default when `model` is omitted). Billing and quota follow the Image+ page. By default the request waits up to `waitTimeoutSeconds` and+ returns the finished images with their URLs; any still running come back+ with their current status — poll `GET /generations/{id}` or call+ `generations.wait(id)` in the SDK. With `wait: false` it answers as soon+ as the work is queued. Each request is added to `topicId`, or to a new+ generation topic. A request the plan or budget refuses (insufficient+ credits, plan limit) is recorded as generations that already failed:+ they come back with `status: 'error'` and the reason in `error`, as on+ the Image page.+++ **API key scopes:** `generation:write`.+ summary: Generate images+ tags:+ - images+ responses:+ "200":+ content:+ application/json:+ schema:+ type: object+ properties:+ data:+ type: object+ properties:+ batchId:+ type: string+ generations:+ type: array+ items:+ $ref: "#/components/schemas/Generation"+ topicId:+ type: string+ required:+ - batchId+ - generations+ - topicId+ additionalProperties: false+ message:+ type: string+ success:+ type: boolean+ const: true+ timestamp:+ type: string+ format: date-time+ required:+ - data+ - success+ - timestamp+ additionalProperties: false+ example:+ data:+ batchId: gb_q7PzJ2mXc4Ld+ generations:+ - asset:+ coverUrl: null+ duration: null+ height: 1024+ thumbnailUrl: https://files.lobehub.com/generations/thumb_2xN8kq.webp+ url: https://files.lobehub.com/generations/2xN8kq.png+ width: 1024+ batchId: gb_q7PzJ2mXc4Ld+ createdAt: 2026-01-15T08:30:00.000Z+ error: null+ fileId: file_8HsW1nVb3QkE+ id: gen_3KdLx9TzQw7v+ model: gpt-image-1+ prompt: A lighthouse on a cliff at dawn, watercolor+ provider: openai+ seed: 42+ status: success+ topicId: gt_Vb5nR2kLp8Ws+ type: image+ topicId: gt_Vb5nR2kLp8Ws+ success: true+ timestamp: 2026-01-01T00:00:00.000Z+ description: Successful response+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ Idempotent-Replayed:+ $ref: "#/components/headers/IdempotentReplayed"+ "400":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Invalid request+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "401":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Authentication required+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "403":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Insufficient permission+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "404":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Resource not found+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "429":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Rate limit exceeded+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ Retry-After:+ $ref: "#/components/headers/RetryAfter"+ "500":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Internal server error+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ x-required-scopes:+ - generation:write+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ cfg:+ description: Guidance scale, for models that accept one.+ type: number+ height:+ description: Image height in pixels.+ type: integer+ exclusiveMinimum: 0+ maximum: 9007199254740991+ imageUrls:+ description: Reference images (URLs) for image-to-image models.+ maxItems: 10+ type: array+ items:+ type: string+ format: uri+ model:+ description: Image model id. Omit to use the account's default image model.+ type: string+ minLength: 1+ n:+ default: 1+ description: Number of images to generate, 1–8. Defaults to 1.+ type: integer+ minimum: 1+ maximum: 8+ params:+ type: object+ propertyNames:+ type: string+ additionalProperties:+ anyOf:+ - type: string+ - type: number+ - type: boolean+ - type: array+ items:+ type: string+ - type: "null"+ description: Model-specific parameters beyond the named fields (for example+ `quality` or `size`). Parameters the model does not declare+ are rejected with 400.+ prompt:+ type: string+ minLength: 1+ maxLength: 10000+ description: What to generate.+ provider:+ description: Provider id. Omit to use the first enabled provider serving+ `model`.+ type: string+ minLength: 1+ seed:+ description: Seed; omit for a random one per image.+ anyOf:+ - type: integer+ minimum: -9007199254740991+ maximum: 9007199254740991+ - type: "null"+ steps:+ description: Sampling steps.+ type: integer+ exclusiveMinimum: 0+ maximum: 9007199254740991+ topicId:+ type: string+ minLength: 1+ description: Generation topic to add this request to. Omit to start a new topic,+ as `lh generate` does.+ wait:+ default: true+ description: Wait for the images before answering (up to `waitTimeoutSeconds`).+ Generations still running at the deadline come back with+ their current status; poll `GET /generations/{id}` for the+ rest. Set `false` to answer as soon as the work is queued.+ type: boolean+ waitTimeoutSeconds:+ default: 60+ description: How long `wait` may hold the request, 1–120 seconds. Defaults to+ 60.+ type: integer+ minimum: 1+ maximum: 120+ width:+ description: Image width in pixels.+ type: integer+ exclusiveMinimum: 0+ maximum: 9007199254740991+ required:+ - prompt+ additionalProperties: false+ example:+ model: gpt-image-1+ n: 1+ prompt: A lighthouse on a cliff at dawn, watercolor+ provider: openai+ parameters:+ - $ref: "#/components/parameters/WorkspaceId"+ - $ref: "#/components/parameters/IdempotencyKey"+ /api/v1/videos/generations:+ post:+ operationId: videos.generate+ description: >-+ Starts a video generation and answers 202 with the generation id while+ it runs; videos take minutes. Poll `GET /generations/{id}` until the+ status is `success` or `error`, or call `generations.wait(id)` in the+ SDK. Billing and quota follow the Video page. Each request is added to+ `topicId`, or to a new generation topic. A request the plan or budget+ refuses (insufficient credits, plan limit) is recorded as a generation+ that already failed: it comes back with the status `error` and the+ reason in the `error` field.+++ **API key scopes:** `generation:write`.+ summary: Generate a video+ tags:+ - videos+ responses:+ "202":+ content:+ application/json:+ schema:+ type: object+ properties:+ data:+ type: object+ properties:+ batchId:+ type: string+ generations:+ type: array+ items:+ $ref: "#/components/schemas/Generation"+ topicId:+ type: string+ required:+ - batchId+ - generations+ - topicId+ additionalProperties: false+ message:+ type: string+ success:+ type: boolean+ const: true+ timestamp:+ type: string+ format: date-time+ required:+ - data+ - success+ - timestamp+ additionalProperties: false+ example:+ data:+ batchId: gb_q7PzJ2mXc4Ld+ generations:+ - asset: null+ batchId: gb_q7PzJ2mXc4Ld+ createdAt: 2026-01-15T08:30:00.000Z+ error: null+ fileId: null+ id: gen_3KdLx9TzQw7v+ model: seedance-1-0-pro+ prompt: Waves rolling onto a beach at sunset, slow pan+ provider: volcengine+ seed: 42+ status: pending+ topicId: gt_Vb5nR2kLp8Ws+ type: video+ topicId: gt_Vb5nR2kLp8Ws+ success: true+ timestamp: 2026-01-01T00:00:00.000Z+ description: Successful response+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ Idempotent-Replayed:+ $ref: "#/components/headers/IdempotentReplayed"+ "400":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Invalid request+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "401":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Authentication required+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "403":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Insufficient permission+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "404":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Resource not found+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "429":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Rate limit exceeded+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ Retry-After:+ $ref: "#/components/headers/RetryAfter"+ "500":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Internal server error+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ x-required-scopes:+ - generation:write+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ aspectRatio:+ description: Aspect ratio, for example `16:9`.+ type: string+ minLength: 1+ cameraFixed:+ description: Keep the camera still, where supported.+ type: boolean+ duration:+ description: Video length in seconds.+ type: number+ exclusiveMinimum: 0+ endImageUrl:+ description: Last frame (URL), where supported.+ anyOf:+ - type: string+ format: uri+ - type: "null"+ generateAudio:+ description: Generate a soundtrack, where supported.+ type: boolean+ imageUrl:+ description: First frame (URL) for image-to-video.+ anyOf:+ - type: string+ format: uri+ - type: "null"+ model:+ type: string+ minLength: 1+ description: Video model id.+ params:+ type: object+ propertyNames:+ type: string+ additionalProperties:+ anyOf:+ - type: string+ - type: number+ - type: boolean+ - type: array+ items:+ type: string+ - type: "null"+ description: Model-specific parameters beyond the named fields (for example+ `quality` or `size`). Parameters the model does not declare+ are rejected with 400.+ previousGenerationId:+ description: A video generation to edit, for models that support conversational+ editing.+ type: string+ minLength: 1+ prompt:+ type: string+ minLength: 1+ maxLength: 10000+ description: What to generate.+ provider:+ type: string+ minLength: 1+ description: Provider id serving `model`.+ resolution:+ description: Output resolution, for example `720p`.+ type: string+ minLength: 1+ seed:+ description: Seed; omit for a random one.+ anyOf:+ - type: integer+ minimum: -9007199254740991+ maximum: 9007199254740991+ - type: "null"+ topicId:+ type: string+ minLength: 1+ description: Generation topic to add this request to. Omit to start a new topic,+ as `lh generate` does.+ required:+ - model+ - prompt+ - provider+ additionalProperties: false+ example:+ aspectRatio: 16:9+ duration: 5+ model: seedance-1-0-pro+ prompt: Waves rolling onto a beach at sunset, slow pan+ provider: volcengine+ parameters:+ - $ref: "#/components/parameters/WorkspaceId"+ - $ref: "#/components/parameters/IdempotencyKey"+ /api/v1/text/generations:+ post:+ operationId: text.generate+ description: >-+ Generates text with an LLM in a single completion — no tools, nothing+ stored as a conversation. Pass `prompt` (and optionally `system`), or a+ `messages` list. `model` + `provider` pick the model; omit both for the+ platform's default chat model. The answer is in `text`; a reasoning+ model's reasoning comes back separately in `reasoning`, never spliced+ into `text`. Provider failures answer 502 `upstream_error` with the+ provider's reason; budget and quota refusals keep their own status (402+ / 429).+++ **API key scopes:** `generation:write`.+ summary: Generate text+ tags:+ - text+ responses:+ "200":+ content:+ application/json:+ schema:+ type: object+ properties:+ data:+ type: object+ properties:+ finishReason:+ description: Why the model stopped, as the provider reports it (`stop`,+ `length`, …).+ type:+ - string+ - "null"+ model:+ type: string+ provider:+ type: string+ reasoning:+ description: Reasoning of a reasoning model, kept out of `text`; `null`+ otherwise.+ type:+ - string+ - "null"+ text:+ type: string+ description: The generated text.+ usage:+ anyOf:+ - type: object+ properties:+ inputTokens:+ anyOf:+ - type: integer+ minimum: -9007199254740991+ maximum: 9007199254740991+ - type: "null"+ outputTokens:+ anyOf:+ - type: integer+ minimum: -9007199254740991+ maximum: 9007199254740991+ - type: "null"+ reasoningTokens:+ anyOf:+ - type: integer+ minimum: -9007199254740991+ maximum: 9007199254740991+ - type: "null"+ totalTokens:+ anyOf:+ - type: integer+ minimum: -9007199254740991+ maximum: 9007199254740991+ - type: "null"+ required:+ - inputTokens+ - outputTokens+ - reasoningTokens+ - totalTokens+ - type: "null"+ required:+ - finishReason+ - model+ - provider+ - reasoning+ - text+ - usage+ message:+ type: string+ success:+ type: boolean+ const: true+ timestamp:+ type: string+ format: date-time+ required:+ - data+ - success+ - timestamp+ additionalProperties: false+ example:+ data:+ finishReason: stop+ model: deepseek-flash+ provider: lobehub+ reasoning: null+ text: Hanging hand tools, organising cables and storing small parts bins.+ usage:+ inputTokens: 24+ outputTokens: 14+ reasoningTokens: null+ totalTokens: 38+ success: true+ timestamp: 2026-01-01T00:00:00.000Z+ description: Successful response+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ Idempotent-Replayed:+ $ref: "#/components/headers/IdempotentReplayed"+ "400":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Invalid request+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "401":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Authentication required+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "402":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Payment required+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "403":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Insufficient permission+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "422":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Unprocessable content+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "429":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Rate limit exceeded+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ Retry-After:+ $ref: "#/components/headers/RetryAfter"+ "500":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Internal server error+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "502":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Upstream error+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ x-required-scopes:+ - generation:write+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ maxTokens:+ description: Maximum output tokens.+ type: integer+ exclusiveMinimum: 0+ maximum: 9007199254740991+ messages:+ description: Conversation to complete. Use instead of, or after, `system` ++ `prompt`.+ minItems: 1+ maxItems: 200+ type: array+ items:+ type: object+ properties:+ content:+ type: string+ description: Plain-text message content.+ role:+ type: string+ enum:+ - system+ - user+ - assistant+ required:+ - content+ - role+ additionalProperties: false+ model:+ description: Model id. Omit to use the platform's default chat model.+ type: string+ minLength: 1+ prompt:+ description: User prompt; appended after `messages` when both are given.+ type: string+ minLength: 1+ provider:+ description: Provider id (for example `lobehub`, `openai`). Omit with `model`+ for the default.+ type: string+ minLength: 1+ system:+ description: System prompt, placed first.+ type: string+ minLength: 1+ temperature:+ description: Sampling temperature, 0–2.+ type: number+ minimum: 0+ maximum: 2+ additionalProperties: false+ example:+ model: deepseek-flash+ prompt: Name three uses for a pegboard in a home workshop.+ provider: lobehub+ system: Answer in one short sentence.+ parameters:+ - $ref: "#/components/parameters/WorkspaceId"+ - $ref: "#/components/parameters/IdempotencyKey"+ /api/v1/objects/generations:+ post:+ operationId: objects.generate+ description: >-+ Generates a JSON object that matches `schema` (structured output, single+ completion) — the same path `lh generate json` uses. The root of+ `schema` must be `type: "object"`; `strict: true` asks providers that+ support it to enforce the schema exactly (every property required,+ `additionalProperties: false`). `model` + `provider` pick the model;+ omit both for the platform's default. A reply that is not a JSON object+ for the schema answers 422 `unprocessable_entity`; provider failures+ answer 502 `upstream_error`.+++ **API key scopes:** `generation:write`.+ summary: Generate a JSON object+ tags:+ - objects+ responses:+ "200":+ content:+ application/json:+ schema:+ type: object+ properties:+ data:+ type: object+ properties:+ model:+ type: string+ object:+ type: object+ propertyNames:+ type: string+ additionalProperties: {}+ description: The generated object, valid for the requested schema.+ provider:+ type: string+ required:+ - model+ - object+ - provider+ message:+ type: string+ success:+ type: boolean+ const: true+ timestamp:+ type: string+ format: date-time+ required:+ - data+ - success+ - timestamp+ additionalProperties: false+ example:+ data:+ model: deepseek-flash+ object:+ name: Peg hook+ steps:+ - Sketch the side profile+ - Extrude 40 mm+ - Fillet+ provider: lobehub+ success: true+ timestamp: 2026-01-01T00:00:00.000Z+ description: Successful response+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ Idempotent-Replayed:+ $ref: "#/components/headers/IdempotentReplayed"+ "400":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Invalid request+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "401":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Authentication required+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "402":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Payment required+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "403":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Insufficient permission+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "422":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Unprocessable content+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "429":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Rate limit exceeded+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ Retry-After:+ $ref: "#/components/headers/RetryAfter"+ "500":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Internal server error+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ "502":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Upstream error+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset"+ x-required-scopes:+ - generation:write+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ messages:+ description: Conversation to complete. Use instead of, or after, `system` ++ `prompt`.+ minItems: 1+ maxItems: 200+ type: array+ items:+ type: object+ properties:+ content:+ type: string+ description: Plain-text message content.+ role:+ type: string+ enum:+ - system+ - user+ - assistant+ required:+ - content+ - role+ additionalProperties: false+ model:+ description: Model id. Omit to use the platform's default chat model.+ type: string+ minLength: 1+ prompt:+ description: User prompt; appended after `messages` when both are given.+ type: string+ minLength: 1+ provider:+ description: Provider id (for example `lobehub`, `openai`). Omit with `model`+ for the default.+ type: string+ minLength: 1+ system:+ description: System prompt, placed first.+ type: string+ minLength: 1+ schema:+ type: object+ properties:+ $defs:+ type: object+ propertyNames:+ type: string+ additionalProperties: {}+ additionalProperties:+ type: boolean+ description:+ type: string+ properties:+ type: object+ propertyNames:+ type: string+ additionalProperties: {}+ required:+ type: array+ items:+ type: string+ title:+ type: string+ type:+ type: string+ const: object+ required:+ - properties+ - type+ additionalProperties: false+ description: 'A JSON Schema with `type: "object"` at the root. Supported root+ keywords: `properties`, `required`, `additionalProperties`,+ `$defs`, `title`, `description`; others (such as `allOf`)+ are rejected rather than silently dropped.'+ schemaDescription:+ description: What the object is, sent with the schema.+ type: string+ schemaName:+ default: response+ description: Name sent with the schema. Defaults to `response`.+ type: string+ pattern: ^[\w-]{1,64}$+ strict:+ description: Ask the provider to enforce the schema strictly (every property+ required, no extras).+ type: boolean+ required:+ - schema+ additionalProperties: false+ example:+ model: deepseek-flash+ prompt: A pegboard headphone hanger, 3D printed in PETG.+ provider: lobehub+ schema:+ additionalProperties: false+ properties:+ name:+ type: string+ steps:+ items:+ type: string+ type: array+ required:+ - name+ - steps+ type: object+ schemaName: concept+ strict: true+ system: Propose one product concept with its CAD modelling steps.+ parameters:+ - $ref: "#/components/parameters/WorkspaceId"+ - $ref: "#/components/parameters/IdempotencyKey"diff --git a/packages/openapi/src/controllers/audio.controller.ts b/packages/openapi/src/controllers/audio.controller.tsindex 28d2685205d..873b59b42cd 100644--- a/packages/openapi/src/controllers/audio.controller.ts+++ b/packages/openapi/src/controllers/audio.controller.ts@@ -1,6 +1,8 @@import type { Context } from 'hono';import { HTTPException } from 'hono/http-exception';+import { hasApiKeyScope, isFullAccessApiKey } from '@/const/apiKeyScope';+import { asrRouter } from '@/server/routers/lambda/asr';import {INLINE_TTS_AUDIO_FORMATS,resolveTTSModelRef,@@ -10,8 +12,41 @@ import {} from '@/server/services/tts';import { BaseController, TRPC_CODE_TO_STATUS } from '../common/base.controller';+import { ApiException, detailsFromZodIssues } from '../common/errors';import type { SpeechRequest } from '../types/audio.type';import { SpeechRequestSchema } from '../types/audio.type';+import {+ MAX_TRANSCRIPTION_UPLOAD_BYTES,+ TranscriptionFieldsSchema,+} from '../types/generation.type';++/**+ * A provider failure (bad key, quota, upstream outage) reaches us as a tRPC+ * INTERNAL_SERVER_ERROR without a message, its model-runtime payload+ * (`{ errorType, error }`) in `cause`. Answer 502 with the provider's reason+ * instead of an empty 500.+ */+const toTranscriptionProviderError = (error: unknown): unknown => {+ if (!(error instanceof Error) || error.name !== 'TRPCError') return error;+ const cause = (error as Error & { cause?: unknown }).cause as+ { error?: { message?: unknown }; errorType?: unknown; message?: unknown } | undefined;+ if (typeof cause?.errorType !== 'string') return error;++ const reason =+ (typeof cause.error?.message === 'string' && cause.error.message) ||+ (typeof cause.message === 'string' && cause.message) ||+ cause.errorType;+ return new ApiException(+ 502,+ 'upstream_error',+ `Transcription provider error (${cause.errorType}): ${reason}`,+ );+};++const validationError = (message: string, path: string) =>+ new ApiException(400, 'validation_error', `Invalid request: ${path} ${message}`, [+ { message, path },+ ]);type OpenAIErrorType =| 'authentication_error'@@ -116,6 +151,86 @@ export class AudioController extends BaseController {}}+ /**+ * POST /api/v1/audio/transcriptions+ * multipart/form-data: `file` (or `fileId`), `model`, optional `provider`,+ * `language`, `prompt`, `response_format`. Answers `{ text }`.+ */+ async handleTranscription(c: Context): Promise<Response> {+ try {+ const form = await c.req.parseBody().catch(() => {+ throw validationError('must be multipart/form-data', 'body');+ });+ const { file, ...rest } = form;+ const fields = TranscriptionFieldsSchema.safeParse(+ Object.fromEntries(+ Object.entries(rest).filter(([, value]) => typeof value === 'string' && value !== ''),+ ),+ );+ if (!fields.success) {+ const details = detailsFromZodIssues('body', fields.error.issues);+ throw new ApiException(+ 400,+ 'validation_error',+ `Invalid request: ${details[0]?.path} ${details[0]?.message}`,+ details,+ );+ }++ const upload = file instanceof File ? file : undefined;+ if (Boolean(upload) === Boolean(fields.data.fileId)) {+ throw validationError('provide exactly one of `file` or `fileId`', 'body.file');+ }+ if (upload && upload.size === 0) throw validationError('is empty', 'body.file');+ if (upload && upload.size > MAX_TRANSCRIPTION_UPLOAD_BYTES) {+ throw new ApiException(+ 413,+ 'payload_too_large',+ `Audio uploads are limited to ${MAX_TRANSCRIPTION_UPLOAD_BYTES / 1024 / 1024} MB; upload the file to /files and pass fileId instead`,+ );+ }++ // Transcribing a stored file reads it: a restricted key needs `file:read` too.+ // `asr.transcribe` has the same rule, but it reads the key's scopes from its+ // context, and the caller below leaves them out — passing them would also+ // re-apply the tRPC `asr` namespace rule (`model:invoke`) on top of the+ // `generation:write` scope this route already checked.+ const scopes = c.get('apiKeyScopes') as string[] | null | undefined;+ if (+ fields.data.fileId &&+ c.get('authType') === 'apikey' &&+ !isFullAccessApiKey(scopes) &&+ !hasApiKeyScope(scopes, 'file:read')+ ) {+ throw new HTTPException(403, {+ message: "insufficient_scope: this API key is missing required scope 'file:read'",+ });+ }++ const { fileId, language, model, prompt, provider, response_format } = fields.data;+ const result = await asrRouter+ .createCaller({ userId: this.getUserId(c)!, workspaceId: this.getWorkspaceId(c) })+ .transcribe({+ ...(upload+ ? {+ audioBase64: Buffer.from(await upload.arrayBuffer()).toString('base64'),+ fileName: upload.name || 'audio',+ mimeType: upload.type || undefined,+ }+ : { fileId }),+ language,+ model,+ prompt,+ ...(provider ? { provider } : {}),+ responseFormat: response_format,+ });++ return c.json({ text: result.text });+ } catch (error) {+ return this.handleError(c, toTranscriptionProviderError(error));+ }+ }+private handleSpeechError(c: Context, error: unknown): Response {if (error instanceof TTSRequestError) {return this.openAIError(c, 400, error.message, undefined, error.reason);diff --git a/packages/openapi/src/controllers/generation.controller.ts b/packages/openapi/src/controllers/generation.controller.tsnew file mode 100644index 00000000000..423cf18161e--- /dev/null+++ b/packages/openapi/src/controllers/generation.controller.ts@@ -0,0 +1,114 @@+import type { Context } from 'hono';++import { BaseController } from '../common/base.controller';+import { GenerationRestService } from '../services/generation.service';+import { TextGenerationRestService } from '../services/text-generation.service';+import type {+ CreateImageGenerationRequest,+ CreateVideoGenerationRequest,+ GenerationIdParam,+ GenerationListQuery,+} from '../types/generation.type';+import type { ObjectGenerationRequest, TextGenerationRequest } from '../types/text-generation.type';++/**+ * Text, JSON, image and video generation controller.+ * Handles HTTP concerns only — generation rules live in the shared image / video procedures.+ */+export class GenerationController extends BaseController {+ private async service(c: Context) {+ return new GenerationRestService(+ await this.getDatabase(),+ this.getUserId(c),+ this.getWorkspaceId(c),+ );+ }++ private async textService(c: Context) {+ return new TextGenerationRestService(+ await this.getDatabase(),+ this.getUserId(c),+ this.getWorkspaceId(c),+ );+ }++ /** POST /api/v1/text/generations */+ async generateText(c: Context): Promise<Response> {+ try {+ const body = await this.getBody<TextGenerationRequest>(c);+ const service = await this.textService(c);+ return this.success(c, await service.generateText(body), 'Text generated');+ } catch (error) {+ return this.handleError(c, error);+ }+ }++ /** POST /api/v1/objects/generations */+ async generateObject(c: Context): Promise<Response> {+ try {+ const body = await this.getBody<ObjectGenerationRequest>(c);+ const service = await this.textService(c);+ return this.success(c, await service.generateObject(body), 'Object generated');+ } catch (error) {+ return this.handleError(c, error);+ }+ }++ /** POST /api/v1/images/generations */+ async createImages(c: Context): Promise<Response> {+ try {+ const body = await this.getBody<CreateImageGenerationRequest>(c);+ const service = await this.service(c);+ return this.success(c, await service.createImages(body), 'Image generation started');+ } catch (error) {+ return this.handleError(c, error);+ }+ }++ /** POST /api/v1/videos/generations */+ async createVideo(c: Context): Promise<Response> {+ try {+ const body = await this.getBody<CreateVideoGenerationRequest>(c);+ const service = await this.service(c);+ return this.success(c, await service.createVideo(body), 'Video generation started', 202);+ } catch (error) {+ return this.handleError(c, error);+ }+ }++ /** GET /api/v1/generations */+ async listGenerations(c: Context): Promise<Response> {+ try {+ const query = this.getQuery<GenerationListQuery>(c);+ const service = await this.service(c);+ return this.list(c, 'items', await service.listGenerations(query), {+ message: 'Generations retrieved successfully',+ pagination: query,+ });+ } catch (error) {+ return this.handleError(c, error);+ }+ }++ /** GET /api/v1/generations/:id */+ async getGeneration(c: Context): Promise<Response> {+ try {+ const { id } = this.getParams<GenerationIdParam>(c);+ const service = await this.service(c);+ return this.success(c, await service.getGeneration(id), 'Generation retrieved');+ } catch (error) {+ return this.handleError(c, error);+ }+ }++ /** DELETE /api/v1/generations/:id */+ async deleteGeneration(c: Context): Promise<Response> {+ try {+ const { id } = this.getParams<GenerationIdParam>(c);+ const service = await this.service(c);+ return this.success(c, await service.deleteGeneration(id), 'Generation deleted');+ } catch (error) {+ return this.handleError(c, error);+ }+ }+}diff --git a/packages/openapi/src/controllers/index.ts b/packages/openapi/src/controllers/index.tsindex 36bc370def9..a38992da95f 100644--- a/packages/openapi/src/controllers/index.ts+++ b/packages/openapi/src/controllers/index.ts@@ -5,6 +5,7 @@ export * from './chat.controller';export * from './chat-group.controller';export * from './eval.controller';export * from './file.controller';+export * from './generation.controller';export * from './mcp-server.controller';export * from './message.controller';export * from './message-translation.controller';diff --git a/packages/openapi/src/middleware/permission-check.ts b/packages/openapi/src/middleware/permission-check.tsindex 77f48f9cca2..bbc9935921e 100644--- a/packages/openapi/src/middleware/permission-check.ts+++ b/packages/openapi/src/middleware/permission-check.ts@@ -31,6 +31,13 @@ export interface PermissionCheckOptions {*/errorMessage?: string;+ /**+ * Scopes a route accepted before `apiKeyScope` was introduced. A restricted+ * key holding one of them still passes, so keys issued earlier keep working;+ * the spec documents only `apiKeyScope`. Requires `apiKeyScope`.+ */+ legacyApiKeyScopes?: ApiKeyScope[];+/*** Logic operator when checking multiple permissions* - 'AND': User must have ALL specified permissions@@ -72,11 +79,13 @@ const assertApiKeyScopesAllow = (permissionCodes: string[],operator: 'AND' | 'OR',apiKeyScope?: ApiKeyScope,+ legacyApiKeyScopes: ApiKeyScope[] = [],) => {if (c.get('authType') !== 'apikey') return;const scopes = c.get('apiKeyScopes') as string[] | null | undefined;if (isFullAccessApiKey(scopes)) return;+ if (apiKeyScope && legacyApiKeyScopes.some((scope) => hasApiKeyScope(scopes, scope))) return;const requiredScopes = apiKeyScope? [apiKeyScope]@@ -222,7 +231,13 @@ const requirePermission = (options: PermissionCheckOptions) => {}// RBAC passed — now narrow by the API key's capability scopes- assertApiKeyScopesAllow(c, permissionCodes, operator, options.apiKeyScope);+ assertApiKeyScopesAllow(+ c,+ permissionCodes,+ operator,+ options.apiKeyScope,+ options.legacyApiKeyScopes,+ );log('Permission check passed for user %s', userId);@@ -300,10 +315,12 @@ export const requireAnyPermissionWithApiKeyScope = (permissionCodes: string[],apiKeyScope: ApiKeyScope,errorMessage?: string,+ { legacyApiKeyScopes }: Pick<PermissionCheckOptions, 'legacyApiKeyScopes'> = {},) => {return requirePermission({apiKeyScope,errorMessage,+ legacyApiKeyScopes,operator: 'OR',permissions: permissionCodes,});diff --git a/packages/openapi/src/routes/audio.route.test.ts b/packages/openapi/src/routes/audio.route.test.tsindex 8831bcd2d7f..ece188f07e4 100644--- a/packages/openapi/src/routes/audio.route.test.ts+++ b/packages/openapi/src/routes/audio.route.test.ts@@ -41,21 +41,29 @@ const requestAs = (apiKeyScopes: string[], allowRbac = true) => {};describe('POST /audio/speech access', () => {- it('accepts a key holding model:invoke', async () => {- const res = await requestAs(['model:invoke']);+ it('accepts a key holding generation:write', async () => {+ const res = await requestAs(['generation:write']);expect(res.status).toBe(200);expect(res.headers.get('Content-Type')).toBe('audio/mpeg');});- it('rejects a key without model:invoke', async () => {- const res = await requestAs(['chat:read']);+ it('keeps accepting keys issued with model:invoke before generation:write existed', async () => {+ const res = await requestAs(['model:invoke']);- expect(res.status).toBe(403);+ expect(res.status).toBe(200);+ });++ it('rejects a key without a generation scope', async () => {+ for (const scopes of [['chat:read'], ['generation:read']]) {+ const res = await requestAs(scopes);++ expect(res.status).toBe(403);+ }});it('rejects an issuer without the model invoke permission, whatever the key scope', async () => {- const res = await requestAs(['model:invoke'], false);+ const res = await requestAs(['generation:write'], false);expect(res.status).toBe(403);});diff --git a/packages/openapi/src/routes/audio.route.ts b/packages/openapi/src/routes/audio.route.tsindex 9cea8d26302..dc821409f48 100644--- a/packages/openapi/src/routes/audio.route.ts+++ b/packages/openapi/src/routes/audio.route.ts@@ -1,13 +1,19 @@import { Hono } from 'hono';import type { DescribeRouteOptions } from 'hono-openapi';-import { describeRoute } from 'hono-openapi';+import { describeRoute, resolver } from 'hono-openapi';import { getAllScopePermissions } from '@/utils/rbac';-import { errorResponse } from '../common/openapi';+import { errorResponse, routeDoc } from '../common/openapi';import { AudioController } from '../controllers/audio.controller';import { requireAuth } from '../middleware/auth';-import { requireAnyPermission } from '../middleware/permission-check';+import { requireAnyPermissionWithApiKeyScope } from '../middleware/permission-check';+import { SpeechRequestSchema } from '../types/audio.type';+import {+ MAX_TRANSCRIPTION_UPLOAD_BYTES,+ TRANSCRIPTION_FORMATS,+ TranscriptionSchema,+} from '../types/generation.type';type RouteResponse = NonNullable<DescribeRouteOptions['responses']>[string];@@ -39,8 +45,19 @@ const openAIError = (description: string): RouteResponse => ({const app = new Hono();// The success body is the audio bytes, not JSON, which `routeDoc` (JSON-only)// cannot express — so this route declares its responses with `describeRoute`.-// Synthesis spends model credits: API keys need `model:invoke`, members the invoke permission.-const requireModelInvoke = requireAnyPermission(getAllScopePermissions('AI_MODEL_INVOKE'));+// Synthesis and transcription spend model credits: members need the invoke+// permission, API keys `generation:write`. Speech shipped gated by+// `model:invoke`, so keys issued with that scope keep working there.+const requireSpeechGeneration = requireAnyPermissionWithApiKeyScope(+ getAllScopePermissions('AI_MODEL_INVOKE'),+ 'generation:write',+ 'You do not have permission to synthesize speech',+ { legacyApiKeyScopes: ['model:invoke'] },+);+const requireTranscriptionGeneration = requireAnyPermissionWithApiKeyScope(+ getAllScopePermissions('AI_MODEL_INVOKE'),+ 'generation:write',+);app.post('/speech',@@ -50,8 +67,15 @@ app.post('`model` takes `provider/model` (for example `lobehub/speech-2.8-hd`) or a bare model id; ' +'the optional `provider` and `params` (emotion, pitch, volume, sampleRate) are LobeHub extensions. ' +'Returns the audio bytes; usage is reported in `X-LobeHub-*` headers. ' ++ 'API keys need the `generation:write` scope (keys issued with `model:invoke` are also accepted). ' +"Synthesis errors use OpenAI's `{ error: { message, type, code, param } }` body; " +'authentication and permission errors use the platform `ApiError` envelope.',+ // The handler validates the body itself (to answer OpenAI-shaped errors),+ // so the schema is declared here rather than through `zValidator`.+ requestBody: {+ content: { 'application/json': { schema: resolver(SpeechRequestSchema) as never } },+ required: true,+ },responses: {200: {content: {@@ -74,8 +98,49 @@ app.post(tags: ['audio'],}),requireAuth,- requireModelInvoke,+ requireSpeechGeneration,async (c) => new AudioController().handleSpeech(c),);+app.post(+ '/transcriptions',+ routeDoc({+ data: TranscriptionSchema,+ description:+ 'OpenAI-compatible speech-to-text: upload the audio as multipart/form-data and get `{ text }` back, so an OpenAI SDK pointed at `/api/v1` can call `audio.transcriptions.create`. ' ++ `Send the clip as \`file\` (up to ${MAX_TRANSCRIPTION_UPLOAD_BYTES / 1024 / 1024} MB), or the id of an uploaded file as \`fileId\` (the key then also needs \`file:read\`). ` ++ '`provider` (default `openai`) is a LobeHub extension. Billing follows the provider configuration, like the in-app voice input. ' ++ 'The transcript is always returned as JSON `{ text }`, whatever `response_format` asks of the provider.',+ envelope: false,+ errors: [400, 404, 413, 502],+ operationId: 'audio.createTranscription',+ requestBody: {+ content: {+ 'multipart/form-data': {+ schema: {+ properties: {+ file: { description: 'The audio clip.', format: 'binary', type: 'string' },+ fileId: { description: 'An uploaded audio file, instead of `file`.', type: 'string' },+ language: { description: 'ISO-639-1 language code, e.g. `en`.', type: 'string' },+ model: { description: 'Transcription model, e.g. `whisper-1`.', type: 'string' },+ prompt: { description: "Text to guide the model's style.", type: 'string' },+ provider: { description: 'Provider id; defaults to `openai`.', type: 'string' },+ response_format: { enum: [...TRANSCRIPTION_FORMATS], type: 'string' },+ },+ required: ['model'],+ type: 'object',+ },+ },+ },+ required: true,+ },+ responseExample: { text: 'Remind me to water the plants at six.' },+ summary: 'Create a transcription',+ tags: ['audio'],+ }),+ requireAuth,+ requireTranscriptionGeneration,+ async (c) => new AudioController().handleTranscription(c),+);+export default app;diff --git a/packages/openapi/src/routes/audio.transcriptions.route.test.ts b/packages/openapi/src/routes/audio.transcriptions.route.test.tsnew file mode 100644index 00000000000..c2c5ccac75e--- /dev/null+++ b/packages/openapi/src/routes/audio.transcriptions.route.test.ts@@ -0,0 +1,274 @@+// @vitest-environment node+import { Hono } from 'hono';+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * `POST /api/v1/audio/transcriptions` over real HTTP: the real route behind the+ * `app.ts` auth and workspace middlewares, real permission/scope gates and+ * controller, on PGlite with real `api_keys` rows. Only the shared+ * `asr.transcribe` procedure (the paid provider call) is faked.+ */+Object.assign(process.env, { NODE_ENV: process.env.NODE_ENV ?? 'test' });+process.env.KEY_VAULTS_SECRET ??= Buffer.alloc(32, 7).toString('base64');++const holder = vi.hoisted(() => ({+ calls: [] as { ctx: any; input: any }[],+ serverDB: undefined as unknown,+ transcribe: undefined as undefined | ((input: any) => Promise<{ text: string }>),+}));++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: async () => holder.serverDB,+}));+vi.mock('@/server/routers/lambda/asr', () => ({+ asrRouter: {+ createCaller: (ctx: any) => ({+ transcribe: async (input: any) => {+ holder.calls.push({ ctx, input });+ return holder.transcribe ? holder.transcribe(input) : { text: 'hello world' };+ },+ }),+ },+}));++const { getTestDB } = await import('@/database/core/getTestDB');+const { apiKeys, users, workspaceMembers, workspaces } = await import('@/database/schemas');+const { hashApiKey } = await import('@lobechat/utils/server');+const { TRPCError } = await import('@trpc/server');+const { HTTPException } = await import('hono/http-exception');+const { errorInitFromException, renderApiError } = await import('../common/errors');+const { userAuthMiddleware } = await import('../middleware/auth');+const { workspaceAuthMiddleware } = await import('../middleware/workspace');+const { MAX_TRANSCRIPTION_UPLOAD_BYTES, TranscriptionSchema } =+ await import('../types/generation.type');+const AudioRoutes = (await import('./audio.route')).default;++const serverDB = await getTestDB();+holder.serverDB = serverDB;++const app = new Hono().basePath('/api/v1');+app.onError((error, c) =>+ error instanceof HTTPException+ ? renderApiError(c, errorInitFromException(error))+ : renderApiError(c, { message: error.message, status: 500 }),+);+app.use('*', userAuthMiddleware);+app.use('*', workspaceAuthMiddleware);+app.route('/audio', AudioRoutes);++const OWNER = 'r6-asr-owner';+const STRANGER = 'r6-asr-stranger';+const WORKSPACE = 'r6-asr-ws';+const OTHER_WORKSPACE = 'r6-asr-other-ws';++const KEYS = {+ fileReader: 'sk-lh-r6asrfilereader1',+ modelInvoke: 'sk-lh-r6asrmodelinvok1',+ read: 'sk-lh-r6asrgenread0001',+ workspace: 'sk-lh-r6asrworkspace01',+ write: 'sk-lh-r6asrgenwrite001',+} as const;++const clip = (bytes = 16, type = 'audio/mpeg') =>+ new File([new Uint8Array(bytes).fill(1)], 'clip.mp3', { type });++const transcribe = (+ fields: Record<string, string | File>,+ init: { key?: string; workspaceId?: string } = {},+) => {+ const form = new FormData();+ for (const [name, value] of Object.entries(fields)) form.append(name, value);+ return app.request('/api/v1/audio/transcriptions', {+ body: form,+ headers: {+ ...(init.key ? { authorization: `Bearer ${init.key}` } : {}),+ ...(init.workspaceId ? { 'x-workspace-id': init.workspaceId } : {}),+ },+ method: 'POST',+ });+};++const json = async (res: Response) => (await res.json()) as any;++beforeEach(async () => {+ holder.calls.length = 0;+ holder.transcribe = undefined;+ await serverDB.delete(apiKeys);+ await serverDB.delete(workspaceMembers);+ await serverDB.delete(workspaces);+ await serverDB.delete(users);++ await serverDB.insert(users).values([{ id: OWNER }, { id: STRANGER }]);+ await serverDB.insert(workspaces).values([+ { id: WORKSPACE, name: 'R6 asr', primaryOwnerId: OWNER, slug: 'r6-asr' },+ { id: OTHER_WORKSPACE, name: 'R6 other', primaryOwnerId: STRANGER, slug: 'r6-asr-other' },+ ]);+ await serverDB.insert(workspaceMembers).values([+ { role: 'owner', userId: OWNER, workspaceId: WORKSPACE },+ { role: 'owner', userId: STRANGER, workspaceId: OTHER_WORKSPACE },+ ]);+ const key = (value: string, scopes: string[], workspaceId?: string) => ({+ key: value,+ keyHash: hashApiKey(value),+ name: value,+ scopes,+ userId: OWNER,+ workspaceId: workspaceId ?? null,+ });+ await serverDB+ .insert(apiKeys)+ .values([+ key(KEYS.write, ['generation:write']),+ key(KEYS.read, ['generation:read']),+ key(KEYS.modelInvoke, ['model:invoke']),+ key(KEYS.fileReader, ['generation:write', 'file:read']),+ key(KEYS.workspace, ['generation:write'], WORKSPACE),+ ]);+});++describe('authentication and API-key scopes', () => {+ it('answers 401 without credentials', async () => {+ const res = await transcribe({ file: clip(), model: 'whisper-1' });++ expect(res.status).toBe(401);+ expect((await json(res)).code).toBe('unauthorized');+ });++ it('needs generation:write, not just read or the legacy model:invoke', async () => {+ for (const key of [KEYS.read, KEYS.modelInvoke]) {+ const res = await transcribe({ file: clip(), model: 'whisper-1' }, { key });++ expect(res.status).toBe(403);+ expect((await json(res)).code).toBe('insufficient_scope');+ }+ expect(holder.calls).toEqual([]);+ });++ it('needs file:read as well to transcribe a stored file', async () => {+ const refused = await transcribe({ fileId: 'file_1', model: 'whisper-1' }, { key: KEYS.write });+ expect(refused.status).toBe(403);+ expect((await json(refused)).code).toBe('insufficient_scope');++ const allowed = await transcribe(+ { fileId: 'file_1', model: 'whisper-1' },+ { key: KEYS.fileReader },+ );+ expect(allowed.status).toBe(200);+ expect(holder.calls[0].input).toMatchObject({ fileId: 'file_1', model: 'whisper-1' });+ });+});++describe('request validation', () => {+ it('rejects missing or conflicting audio and bad fields', async () => {+ const cases: Record<string, string | File>[] = [+ { model: 'whisper-1' },+ { file: clip(), fileId: 'file_1', model: 'whisper-1' },+ { file: clip() },+ { file: clip(), model: 'whisper-1', response_format: 'mp3' },+ { file: clip(), model: 'whisper-1', unknown: 'x' },+ { file: clip(0), model: 'whisper-1' },+ ];++ for (const fields of cases) {+ const res = await transcribe(fields, { key: KEYS.write });+ expect(res.status).toBe(400);+ expect((await json(res)).code).toBe('validation_error');+ }+ expect(holder.calls).toEqual([]);+ });++ it('answers 413 for a clip over the inline limit', async () => {+ const res = await transcribe(+ { file: clip(MAX_TRANSCRIPTION_UPLOAD_BYTES + 1), model: 'whisper-1' },+ { key: KEYS.write },+ );++ expect(res.status).toBe(413);+ expect((await json(res)).code).toBe('payload_too_large');+ });+});++describe('transcription', () => {+ it('hands the clip to the shared procedure and answers { text }', async () => {+ const res = await transcribe(+ {+ file: clip(32, 'audio/mp4'),+ language: 'en',+ model: 'whisper-1',+ prompt: 'plants',+ provider: 'openai',+ },+ { key: KEYS.write },+ );++ expect(res.status).toBe(200);+ expect(TranscriptionSchema.parse(await json(res))).toEqual({ text: 'hello world' });+ expect(holder.calls).toEqual([+ {+ ctx: { userId: OWNER, workspaceId: undefined },+ input: {+ audioBase64: Buffer.from(new Uint8Array(32).fill(1)).toString('base64'),+ fileName: 'clip.mp3',+ language: 'en',+ mimeType: 'audio/mp4',+ model: 'whisper-1',+ prompt: 'plants',+ provider: 'openai',+ responseFormat: undefined,+ },+ },+ ]);+ });++ it("maps the procedure's refusals to HTTP errors", async () => {+ holder.transcribe = async () => {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'File not found' });+ };++ const res = await transcribe(+ { fileId: 'file_other', model: 'whisper-1' },+ {+ key: KEYS.fileReader,+ },+ );+ expect(res.status).toBe(404);+ expect((await json(res)).message).toBe('File not found');+ });+});++describe('provider failures', () => {+ it('answers 502 with the provider reason instead of an empty 500', async () => {+ holder.transcribe = async () => {+ throw new TRPCError({+ cause: {+ error: { message: 'Incorrect API key provided' },+ errorType: 'InvalidProviderAPIKey',+ } as unknown as Error,+ code: 'INTERNAL_SERVER_ERROR',+ });+ };++ const res = await transcribe({ file: clip(), model: 'whisper-1' }, { key: KEYS.write });++ expect(res.status).toBe(502);+ expect(await json(res)).toMatchObject({+ code: 'upstream_error',+ message: 'Transcription provider error (InvalidProviderAPIKey): Incorrect API key provided',+ });+ });+});++describe('workspace isolation', () => {+ it('transcribes inside the key workspace and refuses another workspace', async () => {+ const ok = await transcribe({ file: clip(), model: 'whisper-1' }, { key: KEYS.workspace });+ expect(ok.status).toBe(200);+ expect(holder.calls[0].ctx).toEqual({ userId: OWNER, workspaceId: WORKSPACE });++ const other = await transcribe(+ { file: clip(), model: 'whisper-1' },+ { key: KEYS.workspace, workspaceId: OTHER_WORKSPACE },+ );+ expect(other.status).toBe(403);+ expect((await json(other)).code).toBe('workspace_mismatch');+ });+});diff --git a/packages/openapi/src/routes/generation.examples.ts b/packages/openapi/src/routes/generation.examples.tsnew file mode 100644index 00000000000..436449b6171--- /dev/null+++ b/packages/openapi/src/routes/generation.examples.ts@@ -0,0 +1,25 @@+import type { GenerationPayload } from '../types/generation.type';++/** Example generation published in the spec for the generation routes. */+export const GENERATION_EXAMPLE = {+ asset: {+ coverUrl: null,+ duration: null,+ height: 1024,+ thumbnailUrl: 'https://files.lobehub.com/generations/thumb_2xN8kq.webp',+ url: 'https://files.lobehub.com/generations/2xN8kq.png',+ width: 1024,+ },+ batchId: 'gb_q7PzJ2mXc4Ld',+ createdAt: '2026-01-15T08:30:00.000Z',+ error: null,+ fileId: 'file_8HsW1nVb3QkE',+ id: 'gen_3KdLx9TzQw7v',+ model: 'gpt-image-1',+ prompt: 'A lighthouse on a cliff at dawn, watercolor',+ provider: 'openai',+ seed: 42,+ status: 'success',+ topicId: 'gt_Vb5nR2kLp8Ws',+ type: 'image',+} satisfies GenerationPayload;diff --git a/packages/openapi/src/routes/generations.route.test.ts b/packages/openapi/src/routes/generations.route.test.tsnew file mode 100644index 00000000000..b76d54ba8e7--- /dev/null+++ b/packages/openapi/src/routes/generations.route.test.ts@@ -0,0 +1,585 @@+// @vitest-environment node+import { Hono } from 'hono';+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * `/api/v1/images/generations`, `/api/v1/videos/generations` and+ * `/api/v1/generations` over real HTTP: real routes behind the `app.ts` auth+ * and workspace middlewares, real permission/scope gates, controller, REST+ * service, generation model and the shared `generationTopic` / `generation`+ * procedures, on PGlite. API keys are real `api_keys` rows.+ *+ * Only the paid model calls are faked: `image.createImage` / `video.createVideo`+ * write the batch, async task and generation rows the real procedures write,+ * without reaching a provider. Storage URLs come from a fake FileService.+ */+Object.assign(process.env, { NODE_ENV: process.env.NODE_ENV ?? 'test' });+process.env.KEY_VAULTS_SECRET ??= Buffer.alloc(32, 7).toString('base64');++const holder = vi.hoisted(() => ({+ createCalls: [] as { ctx: any; input: any; kind: 'image' | 'video' }[],+ serverDB: undefined as unknown,+}));++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: async () => holder.serverDB,+}));++vi.mock('@/server/services/file', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ FileService: class {+ deleteFile = async () => {};+ deleteFiles = async () => {};+ getFileAccessUrl = async ({ url }: { url: string }) => `https://cdn.test/${url}`;+ getFullFileUrl = async (key: string) => `https://cdn.test/${key}`;+ getKeyFromFullUrl = async (url: string) => url;+ },+}));++/**+ * Writes what the real create procedures write. Prompts containing "instant"+ * finish at once; "broke" is refused by the budget check, which (like the cloud+ * `chargeBeforeGenerate`) records generations that already failed; "reject" is+ * refused outright, as an unsupported parameter is.+ */+const fakeCreate = async (kind: 'image' | 'video', ctx: any, input: any) => {+ holder.createCalls.push({ ctx, input, kind });+ if (String(input.params.prompt).includes('reject')) {+ const { TRPCError } = await import('@trpc/server');+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Unsupported parameters for model' });+ }+ const { asyncTasks, generationBatches, generations } = await import('@/database/schemas');+ const db = holder.serverDB as any;+ const owner = { userId: ctx.userId, workspaceId: ctx.workspaceId ?? null };+ const [batch] = await db+ .insert(generationBatches)+ .values({+ ...owner,+ config: input.params,+ generationTopicId: input.generationTopicId,+ model: input.model ?? 'default-image-model',+ prompt: input.params.prompt,+ provider: input.provider ?? 'default-provider',+ })+ .returning();++ const instant = String(input.params.prompt).includes('instant');+ const broke = String(input.params.prompt).includes('broke');+ const created = [];+ for (let i = 0; i < (input.imageNum ?? 1); i++) {+ const [task] = await db+ .insert(asyncTasks)+ .values({+ ...owner,+ ...(broke+ ? {+ error: { body: { detail: 'Not enough credits' }, name: 'InsufficientBudget' },+ status: 'error',+ }+ : { status: instant ? 'success' : 'pending' }),+ type: kind,+ })+ .returning();+ const [generation] = await db+ .insert(generations)+ .values({+ ...owner,+ asset: instant+ ? { height: 512, thumbnailUrl: `thumb-${i}.webp`, url: `image-${i}.png`, width: 512 }+ : null,+ asyncTaskId: task.id,+ generationBatchId: batch.id,+ seed: 7 + i,+ })+ .returning();+ created.push({ ...generation, asyncTaskId: task.id });+ }+ return { data: { batch, generations: created }, success: true };+};++vi.mock('@/server/routers/lambda/image', () => ({+ imageRouter: {+ createCaller: (ctx: any) => ({ createImage: (input: any) => fakeCreate('image', ctx, input) }),+ },+}));+vi.mock('@/server/routers/lambda/video', () => ({+ videoRouter: {+ createCaller: (ctx: any) => ({ createVideo: (input: any) => fakeCreate('video', ctx, input) }),+ },+}));++const { getTestDB } = await import('@/database/core/getTestDB');+const {+ apiKeys,+ asyncTasks,+ generationBatches,+ generations,+ generationTopics,+ users,+ workspaceMembers,+ workspaces,+} = await import('@/database/schemas');+const { eq } = await import('drizzle-orm');+const { hashApiKey } = await import('@lobechat/utils/server');+const { HTTPException } = await import('hono/http-exception');+const { errorInitFromException, renderApiError } = await import('../common/errors');+const { userAuthMiddleware } = await import('../middleware/auth');+const { workspaceAuthMiddleware } = await import('../middleware/workspace');+const { GenerationBatchCreatedSchema, GenerationListResponseSchema, GenerationSchema } =+ await import('../types/generation.type');+const { DeletedResourceSchema } = await import('../types/common.type');+const GenerationRoutes = (await import('./generations.route')).default;+const ImageRoutes = (await import('./images.route')).default;+const VideoRoutes = (await import('./videos.route')).default;++const serverDB = await getTestDB();+holder.serverDB = serverDB;++const app = new Hono().basePath('/api/v1');+// The same error rendering `app.ts` installs, so middleware refusals carry their code.+app.onError((error, c) =>+ error instanceof HTTPException+ ? renderApiError(c, errorInitFromException(error))+ : renderApiError(c, { message: error.message, status: 500 }),+);+app.use('*', userAuthMiddleware);+app.use('*', workspaceAuthMiddleware);+app.route('/generations', GenerationRoutes);+app.route('/images', ImageRoutes);+app.route('/videos', VideoRoutes);++const OWNER = 'r6-gen-owner';+const STRANGER = 'r6-gen-stranger';+const WORKSPACE = 'r6-gen-ws';+const OTHER_WORKSPACE = 'r6-gen-other-ws';++const KEYS = {+ chatOnly: 'sk-lh-r6genchatonly001',+ ownerRead: 'sk-lh-r6genownerread01',+ ownerWrite: 'sk-lh-r6genownerwrite1',+ stranger: 'sk-lh-r6genstranger001',+ workspace: 'sk-lh-r6genworkspace01',+} as const;++const call = (+ path: string,+ init: { body?: unknown; key?: string; method?: string; workspaceId?: string } = {},+) =>+ app.request(`/api/v1${path}`, {+ body: init.body === undefined ? undefined : JSON.stringify(init.body),+ headers: {+ ...(init.key ? { authorization: `Bearer ${init.key}` } : {}),+ ...(init.workspaceId ? { 'x-workspace-id': init.workspaceId } : {}),+ 'content-type': 'application/json',+ },+ method: init.method ?? 'GET',+ });++const json = async (res: Response) => (await res.json()) as any;++const generateImages = async (body: Record<string, unknown>, key: string = KEYS.ownerWrite) => {+ const res = await call('/images/generations', { body, key, method: 'POST' });+ expect(res.status).toBe(200);+ return GenerationBatchCreatedSchema.parse((await json(res)).data);+};++beforeEach(async () => {+ holder.createCalls.length = 0;+ await serverDB.delete(generations);+ await serverDB.delete(generationBatches);+ await serverDB.delete(generationTopics);+ await serverDB.delete(asyncTasks);+ await serverDB.delete(apiKeys);+ await serverDB.delete(workspaceMembers);+ await serverDB.delete(workspaces);+ await serverDB.delete(users);++ await serverDB.insert(users).values([{ id: OWNER }, { id: STRANGER }]);+ await serverDB.insert(workspaces).values([+ { id: WORKSPACE, name: 'R6 generations', primaryOwnerId: OWNER, slug: 'r6-gen' },+ { id: OTHER_WORKSPACE, name: 'R6 other', primaryOwnerId: STRANGER, slug: 'r6-other' },+ ]);+ await serverDB.insert(workspaceMembers).values([+ { role: 'owner', userId: OWNER, workspaceId: WORKSPACE },+ { role: 'owner', userId: STRANGER, workspaceId: OTHER_WORKSPACE },+ ]);+ const key = (value: string, userId: string, scopes: string[], workspaceId?: string) => ({+ key: value,+ keyHash: hashApiKey(value),+ name: value,+ scopes,+ userId,+ workspaceId: workspaceId ?? null,+ });+ await serverDB+ .insert(apiKeys)+ .values([+ key(KEYS.ownerWrite, OWNER, ['generation:write']),+ key(KEYS.ownerRead, OWNER, ['generation:read']),+ key(KEYS.chatOnly, OWNER, ['chat:write', 'model:invoke']),+ key(KEYS.stranger, STRANGER, ['generation:write']),+ key(KEYS.workspace, OWNER, ['generation:write'], WORKSPACE),+ ]);+});++describe('authentication and API-key scopes', () => {+ it('answers 401 without credentials on every endpoint', async () => {+ const responses = await Promise.all([+ call('/generations'),+ call('/generations/gen_x'),+ call('/generations/gen_x', { method: 'DELETE' }),+ call('/images/generations', { body: { prompt: 'a cat' }, method: 'POST' }),+ call('/videos/generations', {+ body: { model: 'm', prompt: 'a cat', provider: 'p' },+ method: 'POST',+ }),+ ]);++ for (const res of responses) {+ expect(res.status).toBe(401);+ expect((await json(res)).code).toBe('unauthorized');+ }+ });++ it('refuses a key without a generation scope, even one holding model:invoke', async () => {+ const responses = await Promise.all([+ call('/generations', { key: KEYS.chatOnly }),+ call('/generations/gen_x', { key: KEYS.chatOnly }),+ call('/images/generations', {+ body: { prompt: 'a cat' },+ key: KEYS.chatOnly,+ method: 'POST',+ }),+ ]);++ for (const res of responses) {+ expect(res.status).toBe(403);+ expect((await json(res)).code).toBe('insufficient_scope');+ }+ expect(holder.createCalls).toEqual([]);+ });++ it('lets a generation:read key read but not generate or delete', async () => {+ const { generations: created } = await generateImages({ prompt: 'instant fox' });++ expect((await call('/generations', { key: KEYS.ownerRead })).status).toBe(200);+ expect((await call(`/generations/${created[0].id}`, { key: KEYS.ownerRead })).status).toBe(200);++ const refused = await Promise.all([+ call('/images/generations', { body: { prompt: 'x' }, key: KEYS.ownerRead, method: 'POST' }),+ call('/videos/generations', {+ body: { model: 'm', prompt: 'x', provider: 'p' },+ key: KEYS.ownerRead,+ method: 'POST',+ }),+ call(`/generations/${created[0].id}`, { key: KEYS.ownerRead, method: 'DELETE' }),+ ]);+ for (const res of refused) {+ expect(res.status).toBe(403);+ expect((await json(res)).code).toBe('insufficient_scope');+ }+ });+});++describe('request validation', () => {+ it('rejects bad image requests before anything is generated', async () => {+ const bodies = [+ {},+ { prompt: ' ' },+ { n: 9, prompt: 'a cat' },+ { prompt: 'a cat', waitTimeoutSeconds: 600 },+ { imageUrls: ['not a url'], prompt: 'a cat' },+ { prompt: 'a cat', unknownField: true },+ ];++ for (const body of bodies) {+ const res = await call('/images/generations', {+ body,+ key: KEYS.ownerWrite,+ method: 'POST',+ });+ expect(res.status).toBe(400);+ expect((await json(res)).code).toBe('validation_error');+ }+ expect(holder.createCalls).toEqual([]);+ });++ it('requires a video model and provider', async () => {+ for (const body of [{ prompt: 'waves' }, { model: 'm', prompt: 'waves' }, { provider: 'p' }]) {+ const res = await call('/videos/generations', {+ body,+ key: KEYS.ownerWrite,+ method: 'POST',+ });+ expect(res.status).toBe(400);+ expect((await json(res)).code).toBe('validation_error');+ }+ expect(holder.createCalls).toEqual([]);+ });++ it('validates list paging and filters', async () => {+ for (const query of ['limit=0', 'limit=101', 'type=audio', 'cursor=bogus']) {+ const res = await call(`/generations?${query}`, { key: KEYS.ownerRead });+ expect(res.status).toBe(400);+ expect((await json(res)).code).toBe('validation_error');+ }+ });++ it('refuses a topic of another kind', async () => {+ const video = await call('/videos/generations', {+ body: { model: 'seedance', prompt: 'waves', provider: 'volcengine' },+ key: KEYS.ownerWrite,+ method: 'POST',+ });+ const { topicId } = (await json(video)).data;++ const res = await call('/images/generations', {+ body: { prompt: 'a cat', topicId },+ key: KEYS.ownerWrite,+ method: 'POST',+ });+ expect(res.status).toBe(400);+ expect((await json(res)).details).toEqual([+ { message: 'Expected a image topic', path: 'body.topicId' },+ ]);+ });+});++describe('image generation', () => {+ it('waits for the images and returns them with their URLs', async () => {+ const created = await generateImages({+ model: 'gpt-image-1',+ n: 2,+ params: { quality: 'high' },+ prompt: 'instant lighthouse at dawn',+ provider: 'openai',+ width: 1024,+ });++ expect(created.generations).toHaveLength(2);+ expect(created.generations[0]).toMatchObject({+ asset: {+ height: 512,+ thumbnailUrl: 'https://cdn.test/thumb-0.webp',+ url: 'https://cdn.test/image-0.png',+ width: 512,+ },+ batchId: created.batchId,+ error: null,+ model: 'gpt-image-1',+ prompt: 'instant lighthouse at dawn',+ provider: 'openai',+ status: 'success',+ topicId: created.topicId,+ type: 'image',+ });++ // The shared procedure got the REST fields in its own shape.+ const [{ ctx, input }] = holder.createCalls;+ expect(ctx).toEqual({+ spendOrigin: { trigger: 'api' },+ userId: OWNER,+ workspaceId: undefined,+ });+ expect(input).toEqual({+ generationTopicId: created.topicId,+ imageNum: 2,+ model: 'gpt-image-1',+ params: { prompt: 'instant lighthouse at dawn', quality: 'high', width: 1024 },+ provider: 'openai',+ });++ // A new topic named after the prompt holds the request, as on the Image page.+ const [topic] = await serverDB+ .select()+ .from(generationTopics)+ .where(eq(generationTopics.id, created.topicId));+ expect(topic).toMatchObject({+ title: 'instant lighthouse at dawn',+ type: 'image',+ userId: OWNER,+ });+ });++ it('answers with pending generations when not waiting, then reports them by id', async () => {+ const created = await generateImages({ prompt: 'slow watercolor', wait: false });+ const [generation] = created.generations;+ expect(generation).toMatchObject({ asset: null, status: 'pending', type: 'image' });++ const res = await call(`/generations/${generation.id}`, { key: KEYS.ownerRead });+ expect(res.status).toBe(200);+ expect(GenerationSchema.parse((await json(res)).data)).toEqual(generation);+ });++ it('reports a budget refusal as failed generations, not an HTTP error', async () => {+ const created = await generateImages({ n: 2, prompt: 'broke cat' });++ expect(created.generations).toHaveLength(2);+ for (const generation of created.generations) {+ expect(generation).toMatchObject({+ asset: null,+ error: { message: 'Not enough credits', name: 'InsufficientBudget' },+ status: 'error',+ });+ }+ });++ it('removes the topic it created when the request is refused', async () => {+ const res = await call('/images/generations', {+ body: { prompt: 'reject this' },+ key: KEYS.ownerWrite,+ method: 'POST',+ });++ expect(res.status).toBe(400);+ expect((await json(res)).message).toBe('Unsupported parameters for model');+ expect(await serverDB.select().from(generationTopics)).toEqual([]);++ // A caller's own topic stays.+ const { topicId } = await generateImages({ prompt: 'instant keep' });+ const again = await call('/images/generations', {+ body: { prompt: 'reject again', topicId },+ key: KEYS.ownerWrite,+ method: 'POST',+ });+ expect(again.status).toBe(400);+ expect((await serverDB.select().from(generationTopics)).map((topic) => topic.id)).toEqual([+ topicId,+ ]);+ });++ it('adds a request to an existing topic of the caller', async () => {+ const first = await generateImages({ prompt: 'instant one' });+ const second = await generateImages({ prompt: 'instant two', topicId: first.topicId });++ expect(second.topicId).toBe(first.topicId);+ expect(await serverDB.select().from(generationTopics)).toHaveLength(1);+ });+});++describe('video generation', () => {+ it('answers 202 with the pending generation id', async () => {+ const res = await call('/videos/generations', {+ body: {+ aspectRatio: '16:9',+ duration: 5,+ model: 'seedance-1-0-pro',+ prompt: 'waves at sunset',+ provider: 'volcengine',+ },+ key: KEYS.ownerWrite,+ method: 'POST',+ });++ expect(res.status).toBe(202);+ const created = GenerationBatchCreatedSchema.parse((await json(res)).data);+ expect(created.generations).toEqual([+ expect.objectContaining({ asset: null, status: 'pending', type: 'video' }),+ ]);+ expect(holder.createCalls[0].input.params).toEqual({+ aspectRatio: '16:9',+ duration: 5,+ prompt: 'waves at sunset',+ });++ const status = await call(`/generations/${created.generations[0].id}`, {+ key: KEYS.ownerRead,+ });+ expect((await json(status)).data).toMatchObject({ status: 'pending', type: 'video' });+ });+});++describe('listing and deleting', () => {+ it('pages newest first and filters by kind', async () => {+ await generateImages({ n: 3, prompt: 'instant set' });+ await call('/videos/generations', {+ body: { model: 'm', prompt: 'a video', provider: 'p' },+ key: KEYS.ownerWrite,+ method: 'POST',+ });++ const first = GenerationListResponseSchema.parse(+ (await json(await call('/generations?limit=3', { key: KEYS.ownerRead }))).data,+ );+ expect(first.total).toBe(4);+ expect(first.items).toHaveLength(3);+ expect(first.hasMore).toBe(true);++ const rest = GenerationListResponseSchema.parse(+ (+ await json(+ await call(`/generations?limit=3&cursor=${first.nextCursor}`, { key: KEYS.ownerRead }),+ )+ ).data,+ );+ expect(rest).toMatchObject({ hasMore: false, nextCursor: null, total: 4 });+ expect(rest.items).toHaveLength(1);++ const videos = GenerationListResponseSchema.parse(+ (await json(await call('/generations?type=video', { key: KEYS.ownerRead }))).data,+ );+ expect(videos.items.map((item) => item.type)).toEqual(['video']);+ });++ it('deletes a generation, then answers 404 for it', async () => {+ const { generations: created } = await generateImages({ prompt: 'instant gone' });+ const { id } = created[0];++ const res = await call(`/generations/${id}`, { key: KEYS.ownerWrite, method: 'DELETE' });+ expect(res.status).toBe(200);+ expect(DeletedResourceSchema.parse((await json(res)).data)).toEqual({ deleted: true, id });++ expect((await call(`/generations/${id}`, { key: KEYS.ownerRead })).status).toBe(404);+ expect(+ (await call(`/generations/${id}`, { key: KEYS.ownerWrite, method: 'DELETE' })).status,+ ).toBe(404);+ });+});++describe('ownership and workspace isolation', () => {+ it("hides another user's generations and topics", async () => {+ const created = await generateImages({ prompt: 'instant private' });+ const { id } = created.generations[0];++ const get = await call(`/generations/${id}`, { key: KEYS.stranger });+ const del = await call(`/generations/${id}`, { key: KEYS.stranger, method: 'DELETE' });+ const topic = await call('/images/generations', {+ body: { prompt: 'a cat', topicId: created.topicId },+ key: KEYS.stranger,+ method: 'POST',+ });+ for (const res of [get, del, topic]) {+ expect(res.status).toBe(404);+ expect((await json(res)).code).toBe('not_found');+ }++ const list = (await json(await call('/generations', { key: KEYS.stranger }))).data;+ expect(list).toMatchObject({ items: [], total: 0 });+ expect(await serverDB.select().from(generations)).toHaveLength(1);+ });++ it('keeps workspace and personal generations apart', async () => {+ const shared = await generateImages({ prompt: 'instant team' }, KEYS.workspace);+ expect(holder.createCalls[0].ctx).toMatchObject({ userId: OWNER, workspaceId: WORKSPACE });+ const { id } = shared.generations[0];++ // The same user's personal key cannot see the workspace row, and vice versa.+ expect((await call(`/generations/${id}`, { key: KEYS.ownerWrite })).status).toBe(404);+ const personalList = (await json(await call('/generations', { key: KEYS.ownerWrite }))).data;+ expect(personalList.total).toBe(0);++ const workspaceList = (await json(await call('/generations', { key: KEYS.workspace }))).data;+ expect(workspaceList.items.map((item: any) => item.id)).toEqual([id]);+ expect((await call(`/generations/${id}`, { key: KEYS.workspace })).status).toBe(200);+ });++ it('refuses a workspace key on another workspace', async () => {+ const res = await call('/generations', {+ key: KEYS.workspace,+ workspaceId: OTHER_WORKSPACE,+ });++ expect(res.status).toBe(403);+ expect((await json(res)).code).toBe('workspace_mismatch');+ });+});diff --git a/packages/openapi/src/routes/generations.route.ts b/packages/openapi/src/routes/generations.route.tsnew file mode 100644index 00000000000..04630229860--- /dev/null+++ b/packages/openapi/src/routes/generations.route.ts@@ -0,0 +1,96 @@+import { Hono } from 'hono';++import { getAllScopePermissions } from '@/utils/rbac';++import { routeDoc } from '../common/openapi';+import { zValidator } from '../common/validator';+import { GenerationController } from '../controllers/generation.controller';+import { requireAuth } from '../middleware/auth';+import {+ requireAnyPermissionWithApiKeyScope,+ requireApiKeyScope,+} from '../middleware/permission-check';+import { DeletedResourceSchema } from '../types/common.type';+import {+ GenerationIdParamSchema,+ GenerationListQuerySchema,+ GenerationListResponseSchema,+ GenerationSchema,+} from '../types/generation.type';+import { GENERATION_EXAMPLE } from './generation.examples';++/**+ * Generation routes: the status, results and removal of image / video+ * generations started through `POST /images/generations` and+ * `POST /videos/generations` (or the Image / Video pages).+ *+ * Reads need the `generation:read` API-key scope; a generation the caller+ * cannot see — another user's, another workspace's, a private topic of a+ * teammate — is a 404. Deleting needs `generation:write` plus the file-delete+ * permission, and only the creator or a workspace owner may remove a row.+ */+const GenerationRoutes = new Hono();++const TAGS = ['generations'];++const generationRead = requireApiKeyScope('generation:read');+const generationDelete = requireAnyPermissionWithApiKeyScope(+ getAllScopePermissions('FILE_DELETE'),+ 'generation:write',+ 'You do not have permission to delete generations',+);++/** GET /api/v1/generations */+GenerationRoutes.get(+ '/',+ routeDoc({+ data: GenerationListResponseSchema,+ description:+ 'Lists the image, video and music generations the caller can see, newest first. Filter by `type`; page with `cursor` / `limit`.',+ responseExample: { hasMore: false, items: [GENERATION_EXAMPLE], nextCursor: null, total: 1 },+ summary: 'List generations',+ tags: TAGS,+ }),+ requireAuth,+ generationRead,+ zValidator('query', GenerationListQuerySchema),+ async (c) => new GenerationController().listGenerations(c),+);++/** GET /api/v1/generations/:id */+GenerationRoutes.get(+ '/:id',+ routeDoc({+ data: GenerationSchema,+ description:+ 'Reports one generation: its `status` (`pending`, `processing`, `success` or `error`), the asset URLs once it succeeded, or the failure reason. Poll until the status is `success` or `error` — the SDK does this in `generations.wait(id)`.',+ errors: [404],+ responseExample: GENERATION_EXAMPLE,+ summary: 'Get a generation',+ tags: TAGS,+ }),+ requireAuth,+ generationRead,+ zValidator('param', GenerationIdParamSchema),+ async (c) => new GenerationController().getGeneration(c),+);++/** DELETE /api/v1/generations/:id */+GenerationRoutes.delete(+ '/:id',+ routeDoc({+ data: DeletedResourceSchema,+ description:+ 'Deletes a generation record and its thumbnail. The library file it was saved as is kept. In a workspace only the creator or a workspace owner may delete it.',+ errors: [404],+ responseExample: { deleted: true, id: GENERATION_EXAMPLE.id },+ summary: 'Delete a generation',+ tags: TAGS,+ }),+ requireAuth,+ generationDelete,+ zValidator('param', GenerationIdParamSchema),+ async (c) => new GenerationController().deleteGeneration(c),+);++export default GenerationRoutes;diff --git a/packages/openapi/src/routes/images.route.ts b/packages/openapi/src/routes/images.route.tsnew file mode 100644index 00000000000..3acb1bc3ce6--- /dev/null+++ b/packages/openapi/src/routes/images.route.ts@@ -0,0 +1,58 @@+import { Hono } from 'hono';++import { getAllScopePermissions } from '@/utils/rbac';++import { example } from '../common/examples';+import { routeDoc } from '../common/openapi';+import { zValidator } from '../common/validator';+import { GenerationController } from '../controllers/generation.controller';+import { requireAuth } from '../middleware/auth';+import { requireAnyPermissionWithApiKeyScope } from '../middleware/permission-check';+import {+ CreateImageGenerationRequestSchema,+ GenerationBatchCreatedSchema,+} from '../types/generation.type';+import { GENERATION_EXAMPLE } from './generation.examples';++/**+ * Image generation. Generating spends model credits, so the caller needs the+ * model-invoke permission and API keys the `generation:write` scope.+ */+const ImageRoutes = new Hono();++const generationWrite = requireAnyPermissionWithApiKeyScope(+ getAllScopePermissions('AI_MODEL_INVOKE'),+ 'generation:write',+ 'You do not have permission to generate images',+);++/** POST /api/v1/images/generations */+ImageRoutes.post(+ '/generations',+ routeDoc({+ data: GenerationBatchCreatedSchema,+ description:+ "Generates `n` images from a prompt with an image model (the account's default when `model` is omitted). Billing and quota follow the Image page. By default the request waits up to `waitTimeoutSeconds` and returns the finished images with their URLs; any still running come back with their current status — poll `GET /generations/{id}` or call `generations.wait(id)` in the SDK. With `wait: false` it answers as soon as the work is queued. Each request is added to `topicId`, or to a new generation topic. A request the plan or budget refuses (insufficient credits, plan limit) is recorded as generations that already failed: they come back with `status: 'error'` and the reason in `error`, as on the Image page.",+ errors: [400, 404],+ operationId: 'images.generate',+ requestExample: example(CreateImageGenerationRequestSchema, {+ model: 'gpt-image-1',+ n: 1,+ prompt: 'A lighthouse on a cliff at dawn, watercolor',+ provider: 'openai',+ }),+ responseExample: {+ batchId: GENERATION_EXAMPLE.batchId,+ generations: [GENERATION_EXAMPLE],+ topicId: GENERATION_EXAMPLE.topicId,+ },+ summary: 'Generate images',+ tags: ['images'],+ }),+ requireAuth,+ generationWrite,+ zValidator('json', CreateImageGenerationRequestSchema),+ async (c) => new GenerationController().createImages(c),+);++export default ImageRoutes;diff --git a/packages/openapi/src/routes/index.ts b/packages/openapi/src/routes/index.tsindex a3d1f0ac41d..166b3002496 100644--- a/packages/openapi/src/routes/index.ts+++ b/packages/openapi/src/routes/index.ts@@ -8,8 +8,10 @@ import ChatGroupsRoutes from './chat-groups.route';import DocumentsRoutes from './documents.route';import EvalRoutes from './eval.route';import FileRoutes from './files.route';+import GenerationsRoutes from './generations.route';import GoalsRoutes from './goals.route';import ImRoutes from './im.route';+import ImagesRoutes from './images.route';import KnowledgeBasesRoutes from './knowledge-bases.route';import McpServersRoutes from './mcp-servers.route';import MemoriesRoutes from './memories.route';@@ -17,6 +19,7 @@ import MessageTranslationsRoutes from './message-translations.route';import MessagesRoutes from './messages.route';import ModelsRoutes from './models.route';import NotificationsRoutes from './notifications.route';+import ObjectsRoutes from './objects.route';import OpenAIRoutes from './openai.route';import PermissionsRoutes from './permissions.route';import { PluginsRoutes } from './plugins.route';@@ -26,9 +29,11 @@ import ResponsesRoutes from './responses.route';import RolesRoutes from './roles.route';import AgentSignalsRoutes from './signals.route';import TasksRoutes from './tasks.route';+import TextRoutes from './text.route';import TopicsRoutes from './topics.route';import UsageRoutes from './usage.route';import UsersRoutes from './users.route';+import VideosRoutes from './videos.route';export default {'agent-groups': AgentGroupsRoutes,@@ -62,4 +67,9 @@ export default {'topics': TopicsRoutes,'users': UsersRoutes,'usage': UsageRoutes,+ 'generations': GenerationsRoutes,+ 'images': ImagesRoutes,+ 'videos': VideosRoutes,+ 'text': TextRoutes,+ 'objects': ObjectsRoutes,};diff --git a/packages/openapi/src/routes/objects.route.ts b/packages/openapi/src/routes/objects.route.tsnew file mode 100644index 00000000000..78e6ff7d680--- /dev/null+++ b/packages/openapi/src/routes/objects.route.ts@@ -0,0 +1,69 @@+import { Hono } from 'hono';++import { getAllScopePermissions } from '@/utils/rbac';++import { example } from '../common/examples';+import { routeDoc } from '../common/openapi';+import { zValidator } from '../common/validator';+import { GenerationController } from '../controllers/generation.controller';+import { requireAuth } from '../middleware/auth';+import { requireAnyPermissionWithApiKeyScope } from '../middleware/permission-check';+import {+ ObjectGenerationRequestSchema,+ ObjectGenerationSchema,+} from '../types/text-generation.type';++/**+ * Structured output (`lh generate json`): the model answers with an object that+ * matches a JSON Schema. Same permissions as text generation.+ */+const ObjectRoutes = new Hono();++const generationWrite = requireAnyPermissionWithApiKeyScope(+ getAllScopePermissions('AI_MODEL_INVOKE'),+ 'generation:write',+ 'You do not have permission to generate objects',+ { legacyApiKeyScopes: ['model:invoke'] },+);++/** POST /api/v1/objects/generations */+ObjectRoutes.post(+ '/generations',+ routeDoc({+ data: ObjectGenerationSchema,+ description:+ 'Generates a JSON object that matches `schema` (structured output, single completion) — the same path `lh generate json` uses. The root of `schema` must be `type: "object"`; `strict: true` asks providers that support it to enforce the schema exactly (every property required, `additionalProperties: false`). `model` + `provider` pick the model; omit both for the platform\'s default. A reply that is not a JSON object for the schema answers 422 `unprocessable_entity`; provider failures answer 502 `upstream_error`.',+ errors: [400, 402, 422, 429, 502],+ operationId: 'objects.generate',+ requestExample: example(ObjectGenerationRequestSchema, {+ model: 'deepseek-flash',+ prompt: 'A pegboard headphone hanger, 3D printed in PETG.',+ provider: 'lobehub',+ schema: {+ additionalProperties: false,+ properties: {+ name: { type: 'string' },+ steps: { items: { type: 'string' }, type: 'array' },+ },+ required: ['name', 'steps'],+ type: 'object',+ },+ schemaName: 'concept',+ strict: true,+ system: 'Propose one product concept with its CAD modelling steps.',+ }),+ responseExample: {+ model: 'deepseek-flash',+ object: { name: 'Peg hook', steps: ['Sketch the side profile', 'Extrude 40 mm', 'Fillet'] },+ provider: 'lobehub',+ },+ summary: 'Generate a JSON object',+ tags: ['objects'],+ }),+ requireAuth,+ generationWrite,+ zValidator('json', ObjectGenerationRequestSchema),+ async (c) => new GenerationController().generateObject(c),+);++export default ObjectRoutes;diff --git a/packages/openapi/src/routes/text-generation.route.test.ts b/packages/openapi/src/routes/text-generation.route.test.tsnew file mode 100644index 00000000000..0a222d1925b--- /dev/null+++ b/packages/openapi/src/routes/text-generation.route.test.ts@@ -0,0 +1,326 @@+// @vitest-environment node+import { Hono } from 'hono';+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * `POST /api/v1/text/generations` and `POST /api/v1/objects/generations` over+ * real HTTP: the real routes behind the `app.ts` auth and workspace+ * middlewares, real permission/scope gates and controller, on PGlite with real+ * `api_keys` rows. Only `AiGenerationService` (the paid model call) is faked.+ */+Object.assign(process.env, { NODE_ENV: process.env.NODE_ENV ?? 'test' });+process.env.KEY_VAULTS_SECRET ??= Buffer.alloc(32, 7).toString('base64');++const holder = vi.hoisted(() => ({+ calls: [] as { ctor: unknown[]; input: any; kind: 'object' | 'text'; options: any }[],+ object: undefined as undefined | ((input: any) => Promise<unknown>),+ serverDB: undefined as unknown,+ text: undefined as undefined | ((input: any) => Promise<unknown>),+}));++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: async () => holder.serverDB,+}));+vi.mock('@/server/services/aiGeneration', () => ({+ AiGenerationService: class {+ ctor: unknown[];+ constructor(...args: unknown[]) {+ this.ctor = args.slice(1);+ }+ async generateText(input: any, options: any) {+ holder.calls.push({ ctor: this.ctor, input, kind: 'text', options });+ return holder.text+ ? holder.text(input)+ : { finishReason: 'stop', text: 'ok', usage: { totalTokens: 3 } };+ }+ async generateObject(input: any, options: any) {+ holder.calls.push({ ctor: this.ctor, input, kind: 'object', options });+ return holder.object ? holder.object(input) : { name: 'Peg hook' };+ }+ },+}));++const { getTestDB } = await import('@/database/core/getTestDB');+const { apiKeys, users, workspaceMembers, workspaces } = await import('@/database/schemas');+const { hashApiKey } = await import('@lobechat/utils/server');+const { StructuredOutputError } = await import('@lobechat/model-runtime');+const { HTTPException } = await import('hono/http-exception');+const { errorInitFromException, renderApiError } = await import('../common/errors');+const { userAuthMiddleware } = await import('../middleware/auth');+const { workspaceAuthMiddleware } = await import('../middleware/workspace');+const { ObjectGenerationSchema, TextGenerationSchema } =+ await import('../types/text-generation.type');+const TextRoutes = (await import('./text.route')).default;+const ObjectRoutes = (await import('./objects.route')).default;++const serverDB = await getTestDB();+holder.serverDB = serverDB;++const app = new Hono().basePath('/api/v1');+app.onError((error, c) =>+ error instanceof HTTPException+ ? renderApiError(c, errorInitFromException(error))+ : renderApiError(c, { message: error.message, status: 500 }),+);+app.use('*', userAuthMiddleware);+app.use('*', workspaceAuthMiddleware);+app.route('/text', TextRoutes);+app.route('/objects', ObjectRoutes);++const OWNER = 'r6-text-owner';+const STRANGER = 'r6-text-stranger';+const WORKSPACE = 'r6-text-ws';++const KEYS = {+ modelInvoke: 'sk-lh-r6textmodelinvk1',+ read: 'sk-lh-r6textgenread001',+ workspace: 'sk-lh-r6textworkspace1',+ write: 'sk-lh-r6textgenwrite01',+} as const;++const SCHEMA = {+ additionalProperties: false,+ properties: { name: { type: 'string' } },+ required: ['name'],+ type: 'object',+};++const post = (+ path: 'objects' | 'text',+ body: unknown,+ init: { key?: string; workspaceId?: string } = {},+) =>+ app.request(`/api/v1/${path}/generations`, {+ body: JSON.stringify(body),+ headers: {+ 'content-type': 'application/json',+ ...(init.key ? { authorization: `Bearer ${init.key}` } : {}),+ ...(init.workspaceId ? { 'x-workspace-id': init.workspaceId } : {}),+ },+ method: 'POST',+ });++const json = async (res: Response) => (await res.json()) as any;++beforeEach(async () => {+ holder.calls.length = 0;+ holder.object = undefined;+ holder.text = undefined;+ await serverDB.delete(apiKeys);+ await serverDB.delete(workspaceMembers);+ await serverDB.delete(workspaces);+ await serverDB.delete(users);++ await serverDB.insert(users).values([{ id: OWNER }, { id: STRANGER }]);+ await serverDB+ .insert(workspaces)+ .values([{ id: WORKSPACE, name: 'R6 text', primaryOwnerId: OWNER, slug: 'r6-text' }]);+ await serverDB+ .insert(workspaceMembers)+ .values([{ role: 'owner', userId: OWNER, workspaceId: WORKSPACE }]);+ const key = (value: string, scopes: string[], workspaceId?: string) => ({+ key: value,+ keyHash: hashApiKey(value),+ name: value,+ scopes,+ userId: OWNER,+ workspaceId: workspaceId ?? null,+ });+ await serverDB+ .insert(apiKeys)+ .values([+ key(KEYS.write, ['generation:write']),+ key(KEYS.read, ['generation:read']),+ key(KEYS.modelInvoke, ['model:invoke']),+ key(KEYS.workspace, ['generation:write'], WORKSPACE),+ ]);+});++describe('authentication and API-key scopes', () => {+ it('answers 401 without credentials', async () => {+ for (const path of ['text', 'objects'] as const) {+ const res = await post(path, { prompt: 'hi', schema: SCHEMA });+ expect(res.status).toBe(401);+ expect((await json(res)).code).toBe('unauthorized');+ }+ });++ it('refuses a read-only key', async () => {+ for (const path of ['text', 'objects'] as const) {+ const res = await post(path, { prompt: 'hi', schema: SCHEMA }, { key: KEYS.read });+ expect(res.status).toBe(403);+ expect((await json(res)).code).toBe('insufficient_scope');+ }+ expect(holder.calls).toEqual([]);+ });++ it('accepts generation:write and the legacy model:invoke scope', async () => {+ for (const key of [KEYS.write, KEYS.modelInvoke]) {+ expect((await post('text', { prompt: 'hi' }, { key })).status).toBe(200);+ expect((await post('objects', { prompt: 'hi', schema: SCHEMA }, { key })).status).toBe(200);+ }+ });++ it('runs a workspace key inside its workspace', async () => {+ const res = await post('text', { prompt: 'hi' }, { key: KEYS.workspace });++ expect(res.status).toBe(200);+ expect(holder.calls[0].ctor).toEqual([OWNER, WORKSPACE]);+ });+});++describe('request validation', () => {+ it('needs a prompt or messages and rejects unknown fields', async () => {+ const cases = [+ {},+ { messages: [] },+ { prompt: '' },+ { prompt: 'hi', temperature: 3 },+ { prompt: 'hi', unknown: true },+ { messages: [{ content: 'hi', role: 'tool' }] },+ ];+ for (const body of cases) {+ const res = await post('text', body, { key: KEYS.write });+ expect(res.status).toBe(400);+ expect((await json(res)).code).toBe('validation_error');+ }+ expect(holder.calls).toEqual([]);+ });++ it('needs an object schema and rejects root keywords the runtime would drop', async () => {+ const cases = [+ { prompt: 'hi' },+ { prompt: 'hi', schema: { properties: {}, type: 'array' } },+ { prompt: 'hi', schema: { ...SCHEMA, allOf: [] } },+ { prompt: 'hi', schema: SCHEMA, schemaName: 'has space' },+ ];+ for (const body of cases) {+ const res = await post('objects', body, { key: KEYS.write });+ expect(res.status).toBe(400);+ expect((await json(res)).code).toBe('validation_error');+ }+ expect(holder.calls).toEqual([]);+ });++ it('needs a provider when a model is named', async () => {+ const res = await post('text', { model: 'gpt-5.4-mini', prompt: 'hi' }, { key: KEYS.write });++ expect(res.status).toBe(400);+ expect((await json(res)).code).toBe('validation_error');+ });+});++describe('text generation', () => {+ it('builds the messages, attributes spend to the API and keeps reasoning out of text', async () => {+ holder.text = async () => ({+ finishReason: 'stop',+ reasoning: 'The user wants one word.',+ text: 'Pegboard',+ usage: {+ outputReasoningTokens: 6,+ totalInputTokens: 12,+ totalOutputTokens: 9,+ totalTokens: 21,+ },+ });++ const res = await post(+ 'text',+ {+ maxTokens: 50,+ messages: [{ content: 'Earlier question', role: 'user' }],+ model: 'deepseek-flash',+ prompt: 'One word?',+ provider: 'lobehub',+ system: 'Be brief.',+ temperature: 0,+ },+ { key: KEYS.write },+ );+ const body = await json(res);++ expect(res.status).toBe(200);+ expect(TextGenerationSchema.parse(body.data)).toEqual({+ finishReason: 'stop',+ model: 'deepseek-flash',+ provider: 'lobehub',+ reasoning: 'The user wants one word.',+ text: 'Pegboard',+ usage: { inputTokens: 12, outputTokens: 9, reasoningTokens: 6, totalTokens: 21 },+ });+ expect(holder.calls[0].input).toEqual({+ maxTokens: 50,+ messages: [+ { content: 'Be brief.', role: 'system' },+ { content: 'Earlier question', role: 'user' },+ { content: 'One word?', role: 'user' },+ ],+ model: 'deepseek-flash',+ provider: 'lobehub',+ temperature: 0,+ });+ expect(holder.calls[0].options.metadata.trigger).toBe('api');+ });++ it('maps provider failures to 502 and budget refusals to their own status', async () => {+ holder.text = async () => {+ throw { error: { message: 'upstream exploded' }, errorType: 'ProviderBizError' };+ };+ const upstream = await post('text', { prompt: 'hi' }, { key: KEYS.write });+ expect(upstream.status).toBe(502);+ expect(await json(upstream)).toMatchObject({ code: 'upstream_error' });+ expect((await post('text', { prompt: 'hi' }, { key: KEYS.write })).status).toBe(502);++ holder.text = async () => {+ throw { errorType: 429 };+ };+ const limited = await post('text', { prompt: 'hi' }, { key: KEYS.write });+ expect(limited.status).toBe(429);+ expect((await json(limited)).code).toBe('rate_limited');+ });+});++describe('object generation', () => {+ it('passes the schema through and answers { object }', async () => {+ const res = await post(+ 'objects',+ {+ model: 'deepseek-flash',+ prompt: 'A pegboard hook',+ provider: 'lobehub',+ schema: SCHEMA,+ schemaDescription: 'One concept',+ schemaName: 'concept',+ strict: true,+ },+ { key: KEYS.write },+ );+ const body = await json(res);++ expect(res.status).toBe(200);+ expect(ObjectGenerationSchema.parse(body.data)).toEqual({+ model: 'deepseek-flash',+ object: { name: 'Peg hook' },+ provider: 'lobehub',+ });+ expect(holder.calls[0].input).toMatchObject({+ messages: [{ content: 'A pegboard hook', role: 'user' }],+ schema: { description: 'One concept', name: 'concept', schema: SCHEMA, strict: true },+ });+ });++ it('answers 422 when the reply is not an object for the schema', async () => {+ for (const reply of [+ async () => {+ throw new StructuredOutputError('not json');+ },+ async () => undefined,+ async () => ['a list'],+ ]) {+ holder.object = reply;+ const res = await post('objects', { prompt: 'hi', schema: SCHEMA }, { key: KEYS.write });+ expect(res.status).toBe(422);+ expect((await json(res)).code).toBe('unprocessable_entity');+ }+ });+});diff --git a/packages/openapi/src/routes/text.route.ts b/packages/openapi/src/routes/text.route.tsnew file mode 100644index 00000000000..384947599dd--- /dev/null+++ b/packages/openapi/src/routes/text.route.ts@@ -0,0 +1,59 @@+import { Hono } from 'hono';++import { getAllScopePermissions } from '@/utils/rbac';++import { example } from '../common/examples';+import { routeDoc } from '../common/openapi';+import { zValidator } from '../common/validator';+import { GenerationController } from '../controllers/generation.controller';+import { requireAuth } from '../middleware/auth';+import { requireAnyPermissionWithApiKeyScope } from '../middleware/permission-check';+import { TextGenerationRequestSchema, TextGenerationSchema } from '../types/text-generation.type';++/**+ * One-shot text generation (`lh generate text`). Spends model credits: members+ * need the model-invoke permission, API keys `generation:write` (keys issued+ * with `model:invoke`, which `/chat` uses, are accepted too).+ */+const TextRoutes = new Hono();++const generationWrite = requireAnyPermissionWithApiKeyScope(+ getAllScopePermissions('AI_MODEL_INVOKE'),+ 'generation:write',+ 'You do not have permission to generate text',+ { legacyApiKeyScopes: ['model:invoke'] },+);++/** POST /api/v1/text/generations */+TextRoutes.post(+ '/generations',+ routeDoc({+ data: TextGenerationSchema,+ description:+ "Generates text with an LLM in a single completion — no tools, nothing stored as a conversation. Pass `prompt` (and optionally `system`), or a `messages` list. `model` + `provider` pick the model; omit both for the platform's default chat model. The answer is in `text`; a reasoning model's reasoning comes back separately in `reasoning`, never spliced into `text`. Provider failures answer 502 `upstream_error` with the provider's reason; budget and quota refusals keep their own status (402 / 429).",+ errors: [400, 402, 422, 429, 502],+ operationId: 'text.generate',+ requestExample: example(TextGenerationRequestSchema, {+ model: 'deepseek-flash',+ prompt: 'Name three uses for a pegboard in a home workshop.',+ provider: 'lobehub',+ system: 'Answer in one short sentence.',+ }),+ responseExample: {+ finishReason: 'stop',+ model: 'deepseek-flash',+ provider: 'lobehub',+ reasoning: null,+ text: 'Hanging hand tools, organising cables and storing small parts bins.',+ usage: { inputTokens: 24, outputTokens: 14, reasoningTokens: null, totalTokens: 38 },+ },+ summary: 'Generate text',+ tags: ['text'],+ }),+ requireAuth,+ generationWrite,+ zValidator('json', TextGenerationRequestSchema),+ async (c) => new GenerationController().generateText(c),+);++export default TextRoutes;diff --git a/packages/openapi/src/routes/videos.route.ts b/packages/openapi/src/routes/videos.route.tsnew file mode 100644index 00000000000..54e3336e5c3--- /dev/null+++ b/packages/openapi/src/routes/videos.route.ts@@ -0,0 +1,71 @@+import { Hono } from 'hono';++import { getAllScopePermissions } from '@/utils/rbac';++import { example } from '../common/examples';+import { routeDoc } from '../common/openapi';+import { zValidator } from '../common/validator';+import { GenerationController } from '../controllers/generation.controller';+import { requireAuth } from '../middleware/auth';+import { requireAnyPermissionWithApiKeyScope } from '../middleware/permission-check';+import {+ CreateVideoGenerationRequestSchema,+ GenerationBatchCreatedSchema,+} from '../types/generation.type';+import { GENERATION_EXAMPLE } from './generation.examples';++/**+ * Video generation. Generating spends model credits, so the caller needs the+ * model-invoke permission and API keys the `generation:write` scope.+ */+const VideoRoutes = new Hono();++const generationWrite = requireAnyPermissionWithApiKeyScope(+ getAllScopePermissions('AI_MODEL_INVOKE'),+ 'generation:write',+ 'You do not have permission to generate videos',+);++/** POST /api/v1/videos/generations */+VideoRoutes.post(+ '/generations',+ routeDoc({+ data: GenerationBatchCreatedSchema,+ description:+ 'Starts a video generation and answers 202 with the generation id while it runs; videos take minutes. Poll `GET /generations/{id}` until the status is `success` or `error`, or call `generations.wait(id)` in the SDK. Billing and quota follow the Video page. Each request is added to `topicId`, or to a new generation topic. A request the plan or budget refuses (insufficient credits, plan limit) is recorded as a generation that already failed: it comes back with the status `error` and the reason in the `error` field.',+ errors: [400, 404],+ operationId: 'videos.generate',+ requestExample: example(CreateVideoGenerationRequestSchema, {+ aspectRatio: '16:9',+ duration: 5,+ model: 'seedance-1-0-pro',+ prompt: 'Waves rolling onto a beach at sunset, slow pan',+ provider: 'volcengine',+ }),+ responseExample: {+ batchId: GENERATION_EXAMPLE.batchId,+ generations: [+ {+ ...GENERATION_EXAMPLE,+ asset: null,+ fileId: null,+ model: 'seedance-1-0-pro',+ prompt: 'Waves rolling onto a beach at sunset, slow pan',+ provider: 'volcengine',+ status: 'pending',+ type: 'video',+ },+ ],+ topicId: GENERATION_EXAMPLE.topicId,+ },+ status: 202,+ summary: 'Generate a video',+ tags: ['videos'],+ }),+ requireAuth,+ generationWrite,+ zValidator('json', CreateVideoGenerationRequestSchema),+ async (c) => new GenerationController().createVideo(c),+);++export default VideoRoutes;diff --git a/packages/openapi/src/services/generation.service.ts b/packages/openapi/src/services/generation.service.tsnew file mode 100644index 00000000000..63b1c6c30aa--- /dev/null+++ b/packages/openapi/src/services/generation.service.ts@@ -0,0 +1,316 @@+import type { AsyncTaskError, ImageGenerationAsset, VideoGenerationAsset } from '@lobechat/types';+import { RequestTrigger } from '@lobechat/types';++import { AsyncTaskModel } from '@/database/models/asyncTask';+import type { GenerationKind, GenerationWithBatch } from '@/database/models/generation';+import { GenerationModel } from '@/database/models/generation';+import { GenerationTopicModel } from '@/database/models/generationTopic';+import type { LobeChatDatabase } from '@/database/type';+import { generationRouter } from '@/server/routers/lambda/generation';+import { generationTopicRouter } from '@/server/routers/lambda/generationTopic';+import { imageRouter } from '@/server/routers/lambda/image';+import { videoRouter } from '@/server/routers/lambda/video';++import { BaseService } from '../common/base.service';+import { ApiException } from '../common/errors';+import { resolvePagination } from '../helpers/pagination';+import type { DeletedResource } from '../types/common.type';+import type {+ CreateImageGenerationRequest,+ CreateVideoGenerationRequest,+ GenerationAssetPayload,+ GenerationBatchCreated,+ GenerationListQuery,+ GenerationPayload,+} from '../types/generation.type';+import { GENERATION_KINDS, TERMINAL_GENERATION_STATUSES } from '../types/generation.type';++const WAIT_POLL_INTERVAL_MS = 2000;++const isTerminal = (status: string) =>+ (TERMINAL_GENERATION_STATUSES as readonly string[]).includes(status);++const sleep = (ms: number) =>+ new Promise<void>((resolve) => {+ setTimeout(resolve, ms);+ });++const withoutUndefined = <T extends Record<string, unknown>>(value: T) =>+ Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined)) as T;++const toErrorPayload = (error: AsyncTaskError | null | undefined) => {+ if (!error) return null;+ const body = error.body as unknown;+ const message =+ typeof body === 'string'+ ? body+ : body && typeof body === 'object' && 'detail' in body+ ? String((body as { detail: unknown }).detail)+ : error.name;+ return { message, name: error.name };+};++const toAssetPayload = (+ asset: ImageGenerationAsset | VideoGenerationAsset | null | undefined,+): GenerationAssetPayload | null => {+ if (!asset) return null;+ const video = asset as VideoGenerationAsset;+ return {+ coverUrl: video.coverUrl ?? null,+ duration: video.duration ?? null,+ height: asset.height ?? null,+ thumbnailUrl: asset.thumbnailUrl ?? null,+ url: asset.url ?? null,+ width: asset.width ?? null,+ };+};++/**+ * Image / video generation REST service.+ *+ * Starting a generation goes through the same `image.createImage` /+ * `video.createVideo` procedures the Image and Video pages and `lh generate`+ * call — invoked server-side without API-key scopes in their context (the REST+ * route has already narrowed the key to `generation:*`). That keeps one+ * implementation of model resolution, parameter checks, storage admission,+ * pre-charge and settlement. Reads use the generation model's ownership filter+ * (creator in personal mode, workspace visibility in a workspace); deletes go+ * through `generation.deleteGeneration`, which also enforces that only the+ * creator or a workspace owner removes a row.+ */+export class GenerationRestService extends BaseService {+ private readonly ctx: { userId: string; workspaceId?: string };++ constructor(db: LobeChatDatabase, userId: string | null, workspaceId?: string) {+ super(db, userId, workspaceId);+ this.ctx = { userId: this.userId, workspaceId };+ }++ private get generationModel() {+ return new GenerationModel(this.db, this.userId, this.workspaceId);+ }++ /** Context for paid generation procedures: spend is attributed to the public API. */+ private get spendCtx() {+ return { ...this.ctx, spendOrigin: { trigger: RequestTrigger.Api } };+ }++ /** The topic to add a request to: the caller's own `topicId`, or a new topic. */+ private async resolveTopic(+ kind: GenerationKind,+ prompt: string,+ topicId?: string,+ ): Promise<{ created: boolean; id: string }> {+ if (topicId) {+ const topic = await new GenerationTopicModel(this.db, this.userId, this.workspaceId).findById(+ topicId,+ );+ if (!topic) throw this.createNotFoundError('Generation topic not found');+ if (topic.type !== kind) {+ throw new ApiException(+ 400,+ 'validation_error',+ `Invalid request: topicId is a ${topic.type} topic, not ${kind}`,+ [{ message: `Expected a ${kind} topic`, path: 'body.topicId' }],+ );+ }+ return { created: false, id: topic.id };+ }++ const id = await generationTopicRouter.createCaller(this.ctx).createTopic({+ title: prompt.trim().slice(0, 100),+ type: kind,+ });+ return { created: true, id: id as string };+ }++ /**+ * Run a create procedure in `topic`. When the procedure refuses the request+ * (unknown model, unsupported params, storage full, …) a topic made for it is+ * removed again, so retrying clients do not leave empty topics behind.+ */+ private async inTopic<T>(topic: { created: boolean; id: string }, run: () => Promise<T>) {+ try {+ return await run();+ } catch (error) {+ if (topic.created) {+ await generationTopicRouter+ .createCaller(this.ctx)+ .deleteTopic({ id: topic.id })+ .catch((cleanupError: unknown) => {+ this.log('warn', 'Failed to remove the topic of a refused generation', {+ cleanupError,+ topicId: topic.id,+ });+ });+ }+ throw error;+ }+ }++ private async toPayload(row: GenerationWithBatch): Promise<GenerationPayload> {+ const generation = await this.generationModel.transformGeneration(row);+ const kind = row.batch.topic?.type;++ return {+ asset: toAssetPayload(generation.asset),+ batchId: row.batch.id,+ createdAt: new Date(row.createdAt).toISOString(),+ error: toErrorPayload(generation.task.error),+ fileId: generation.fileId ?? null,+ id: row.id,+ model: row.batch.model,+ prompt: row.batch.prompt,+ provider: row.batch.provider,+ seed: row.seed ?? null,+ status: generation.task.status as GenerationPayload['status'],+ topicId: row.batch.generationTopicId,+ type: (GENERATION_KINDS as readonly string[]).includes(kind ?? '')+ ? (kind as GenerationPayload['type'])+ : 'image',+ };+ }++ /**+ * The visible generations among `ids`, in that order, with their task status+ * brought up to date first (tasks past their timeout are failed), as+ * `generation.getGenerationStatus` does.+ */+ private async findFresh(ids: string[]): Promise<GenerationWithBatch[]> {+ const rows = await this.generationModel.findByIdsWithBatch(ids);+ const runningTaskIds = rows+ .filter((row) => row.asyncTaskId && !isTerminal(row.asyncTask?.status ?? 'pending'))+ .map((row) => row.asyncTaskId!);+ if (runningTaskIds.length === 0) return rows;++ await new AsyncTaskModel(this.db, this.userId, this.workspaceId).checkTimeoutTasks(+ runningTaskIds,+ );+ return this.generationModel.findByIdsWithBatch(ids);+ }++ async getGeneration(id: string): Promise<GenerationPayload> {+ const [row] = await this.findFresh([id]);+ if (!row) throw this.createNotFoundError('Generation not found');+ return this.toPayload(row);+ }++ async listGenerations(query: GenerationListQuery) {+ const { limit, offset } = resolvePagination(query);+ const { items, total } = await this.generationModel.queryWithBatch({+ limit,+ offset,+ type: query.type,+ });+ return { items: await Promise.all(items.map((row) => this.toPayload(row))), total };+ }++ async deleteGeneration(id: string): Promise<DeletedResource> {+ if (!(await this.generationModel.findById(id))) {+ throw this.createNotFoundError('Generation not found');+ }+ await generationRouter.createCaller(this.ctx).deleteGeneration({ generationId: id });+ return { deleted: true, id };+ }++ /** Poll until every generation is final or the deadline passes. */+ private async waitForGenerations(ids: string[], timeoutSeconds: number) {+ const deadline = Date.now() + timeoutSeconds * 1000;+ let rows = await this.findFresh(ids);++ while (+ rows.some((row) => !isTerminal(row.asyncTask?.status ?? 'pending')) &&+ Date.now() + WAIT_POLL_INTERVAL_MS <= deadline+ ) {+ await sleep(WAIT_POLL_INTERVAL_MS);+ rows = await this.findFresh(ids);+ }++ return rows;+ }++ /**+ * The create response. A request the plan or budget refuses (insufficient+ * credits, plan limit, frozen workspace, content moderation) is not an HTTP+ * error: the shared procedure records it as generations that already failed —+ * the Image / Video pages show them the same way — so they come back with+ * `status: 'error'` and the reason in `error`.+ */+ private async batchPayload(+ batchId: string,+ topicId: string,+ created: { id?: string | null }[],+ rows?: GenerationWithBatch[],+ ): Promise<GenerationBatchCreated> {+ const ids = created.map((generation) => generation.id).filter((id): id is string => !!id);+ const resolved = rows ?? (await this.findFresh(ids));+ const generations = await Promise.all(resolved.map((row) => this.toPayload(row)));+ return { batchId, generations, topicId };+ }++ async createImages(body: CreateImageGenerationRequest): Promise<GenerationBatchCreated> {+ const topic = await this.resolveTopic('image', body.prompt, body.topicId);++ const result = await this.inTopic(topic, () =>+ imageRouter.createCaller(this.spendCtx).createImage({+ generationTopicId: topic.id,+ imageNum: body.n,+ model: body.model,+ params: withoutUndefined({+ ...body.params,+ cfg: body.cfg,+ height: body.height,+ imageUrls: body.imageUrls,+ prompt: body.prompt,+ seed: body.seed,+ steps: body.steps,+ width: body.width,+ }),+ provider: body.provider,+ }),+ );++ const { batch, generations } = result.data;+ const rows = body.wait+ ? await this.waitForGenerations(+ generations.map((generation) => generation.id).filter((id): id is string => !!id),+ body.waitTimeoutSeconds,+ )+ : undefined;+ return this.batchPayload(batch.id as string, topic.id, generations, rows);+ }++ async createVideo(body: CreateVideoGenerationRequest): Promise<GenerationBatchCreated> {+ if (+ body.previousGenerationId &&+ !(await this.generationModel.findById(body.previousGenerationId))+ ) {+ throw this.createNotFoundError('Previous generation not found');+ }+ const topic = await this.resolveTopic('video', body.prompt, body.topicId);++ const result = await this.inTopic(topic, () =>+ videoRouter.createCaller(this.spendCtx).createVideo({+ generationTopicId: topic.id,+ model: body.model,+ params: withoutUndefined({+ ...body.params,+ aspectRatio: body.aspectRatio,+ cameraFixed: body.cameraFixed,+ duration: body.duration,+ endImageUrl: body.endImageUrl,+ generateAudio: body.generateAudio,+ imageUrl: body.imageUrl,+ prompt: body.prompt,+ resolution: body.resolution,+ seed: body.seed,+ }),+ previousGenerationId: body.previousGenerationId,+ provider: body.provider,+ }),+ );++ const { batch, generations } = result.data;+ return this.batchPayload(batch.id as string, topic.id, generations);+ }+}diff --git a/packages/openapi/src/services/text-generation.service.ts b/packages/openapi/src/services/text-generation.service.tsnew file mode 100644index 00000000000..089be73824e--- /dev/null+++ b/packages/openapi/src/services/text-generation.service.ts@@ -0,0 +1,169 @@+import { DEFAULT_MODEL, DEFAULT_PROVIDER } from '@lobechat/business-const';+import { getErrorCodeSpec, StructuredOutputError } from '@lobechat/model-runtime';+import type { OpenAIChatMessage } from '@lobechat/types';+import { RequestTrigger } from '@lobechat/types';++import type { LobeChatDatabase } from '@/database/type';+import { AiGenerationService } from '@/server/services/aiGeneration';++import { BaseService } from '../common/base.service';+import { ApiException, codeForStatus } from '../common/errors';+import type {+ ObjectGeneration,+ ObjectGenerationRequest,+ TextGeneration,+ TextGenerationRequest,+} from '../types/text-generation.type';++type Input = Pick<TextGenerationRequest, 'messages' | 'model' | 'prompt' | 'provider' | 'system'>;++/**+ * Runtime statuses that describe the caller's request (budget, quota, input),+ * kept as they are. Others — provider auth, outages and the runtime's own 4xx+ * codes such as 471 — are the provider's problem and answer 502.+ */+const CALLER_STATUSES = new Set([400, 402, 413, 422, 429]);++const pickString = (value: unknown) =>+ typeof value === 'string' && value.trim() ? value : undefined;++/**+ * A model-runtime failure (`{ errorType, error }`) or a raw provider error as an+ * API error: budget / quota / input refusals keep their status (402 / 429 /+ * 400…), anything else answers 502 with the provider's reason.+ */+const toApiError = (error: unknown): unknown => {+ if (error instanceof ApiException || !error || typeof error !== 'object') return error;+ const record = error as {+ error?: { message?: unknown };+ errorType?: unknown;+ message?: unknown;+ status?: unknown;+ };+ const errorType = record.errorType;+ const status =+ typeof errorType === 'number'+ ? errorType+ : typeof errorType === 'string'+ ? getErrorCodeSpec(errorType)?.httpStatus+ : typeof record.status === 'number'+ ? record.status+ : undefined;+ if (status === undefined && errorType === undefined) return error;++ const reason =+ pickString(record.error?.message) ?? pickString(record.message) ?? String(errorType ?? status);+ const label = typeof errorType === 'string' ? `${errorType}: ${reason}` : reason;+ if (status && CALLER_STATUSES.has(status))+ return new ApiException(status as 400, codeForStatus(status), label);+ return new ApiException(502, 'upstream_error', `Model provider error (${label})`);+};++/**+ * One-shot text and JSON generation over the same model runtime as the app's+ * `aiChat.outputJSON` (structured output) and server-side completions. Spend is+ * attributed to the public API; nothing is stored as a conversation.+ */+export class TextGenerationRestService extends BaseService {+ constructor(db: LobeChatDatabase, userId: string | null, workspaceId?: string) {+ super(db, userId, workspaceId);+ }++ private get ai() {+ return new AiGenerationService(this.db, this.userId, this.workspaceId);+ }++ /** Model and provider, defaulting both together so a bare `model` keeps its own provider. */+ private async resolveModel(input: Input) {+ const model = input.model ?? DEFAULT_MODEL;+ const provider = input.provider ?? (input.model ? undefined : DEFAULT_PROVIDER);+ if (!provider) {+ throw new ApiException(400, 'validation_error', 'Invalid request: provider is required', [+ { message: 'Required when `model` is set', path: 'body.provider' },+ ]);+ }++ const permission = await this.resolveOperationPermission('AI_MODEL_INVOKE', {+ targetModelId: model,+ });+ if (!permission.isPermitted) {+ throw this.createAuthorizationError(permission.message || 'Not allowed to use this model');+ }+ return { model, provider };+ }++ private static messagesOf(input: Input): OpenAIChatMessage[] {+ return [+ ...(input.system ? [{ content: input.system, role: 'system' as const }] : []),+ ...(input.messages ?? []),+ ...(input.prompt ? [{ content: input.prompt, role: 'user' as const }] : []),+ ];+ }++ async generateText(input: TextGenerationRequest): Promise<TextGeneration> {+ const { model, provider } = await this.resolveModel(input);+ try {+ const result = await this.ai.generateText(+ {+ maxTokens: input.maxTokens,+ messages: TextGenerationRestService.messagesOf(input),+ model,+ provider,+ temperature: input.temperature,+ },+ { metadata: { trigger: RequestTrigger.Api } },+ );+ const usage = result.usage;+ return {+ finishReason: result.finishReason ?? null,+ model,+ provider,+ reasoning: result.reasoning ?? null,+ text: result.text,+ usage: usage+ ? {+ inputTokens: usage.totalInputTokens ?? null,+ outputTokens: usage.totalOutputTokens ?? null,+ reasoningTokens: usage.outputReasoningTokens ?? null,+ totalTokens: usage.totalTokens ?? null,+ }+ : null,+ };+ } catch (error) {+ throw toApiError(error);+ }+ }++ async generateObject(input: ObjectGenerationRequest): Promise<ObjectGeneration> {+ const { model, provider } = await this.resolveModel(input);+ let object: unknown;+ try {+ object = await this.ai.generateObject(+ {+ messages: TextGenerationRestService.messagesOf(input),+ model,+ provider,+ schema: {+ description: input.schemaDescription,+ name: input.schemaName,+ schema: input.schema,+ strict: input.strict,+ },+ },+ { metadata: { trigger: RequestTrigger.Api } },+ );+ } catch (error) {+ if (error instanceof StructuredOutputError) object = undefined;+ else throw toApiError(error);+ }++ if (!object || typeof object !== 'object' || Array.isArray(object)) {+ throw new ApiException(+ 422,+ 'unprocessable_entity',+ 'The model reply was not a JSON object matching the schema',+ );+ }+ return { model, object: object as Record<string, unknown>, provider };+ }+}diff --git a/packages/openapi/src/spec.test.ts b/packages/openapi/src/spec.test.tsindex 98096ad115f..53325238938 100644--- a/packages/openapi/src/spec.test.ts+++ b/packages/openapi/src/spec.test.ts@@ -380,6 +380,17 @@ describe('generated OpenAPI document', () => {expect(media('/api/v1/responses', 'post').response).toMatchObject({ object: 'response' });});+ it('declares the JSON body of /audio/speech, which its handler validates itself', () => {+ const op = (spec.paths as Record<string, any>)['/api/v1/audio/speech'].post;+ const schema = op.requestBody?.content?.['application/json']?.schema;++ expect(op.requestBody?.required).toBe(true);+ expect(schema?.required).toEqual(['input', 'model']);+ expect(Object.keys(schema?.properties ?? {})).toEqual(+ expect.arrayContaining(['input', 'model', 'voice', 'response_format', 'params']),+ );+ });+it('types the /responses event stream as the OpenResponses event union', () => {const op = (spec.paths as Record<string, any>)['/api/v1/responses'].post;expect(op.responses['200'].content['text/event-stream'].schema).toEqual({diff --git a/packages/openapi/src/types/generation.type.ts b/packages/openapi/src/types/generation.type.tsnew file mode 100644index 00000000000..6552bd20513--- /dev/null+++ b/packages/openapi/src/types/generation.type.ts@@ -0,0 +1,206 @@+import { z } from 'zod';++import { CursorPaginationQuerySchema, paginatedListSchema } from '../helpers/pagination';++/**+ * Image / video generation on the public REST API.+ *+ * A generation is one output (one image, one video) of a generation request.+ * Requests are asynchronous: `POST /images/generations` and+ * `POST /videos/generations` queue the work and answer with the generation+ * ids; `GET /generations/{id}` reports the status and, once it succeeded, the+ * asset URLs. Each request becomes a batch inside a generation topic — the same+ * records the Image / Video pages in the app show.+ */++export const GENERATION_KINDS = ['image', 'video', 'music'] as const;+export const GENERATION_STATUSES = ['pending', 'processing', 'success', 'error'] as const;+/** Statuses after which a generation no longer changes. */+export const TERMINAL_GENERATION_STATUSES = ['success', 'error'] as const;++/** Extra model-specific parameters, checked against the model's declared parameters. */+const ExtraParamsSchema = z+ .record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string()), z.null()]))+ .describe(+ 'Model-specific parameters beyond the named fields (for example `quality` or `size`). Parameters the model does not declare are rejected with 400.',+ );++const PromptSchema = z.string().trim().min(1).max(10_000).describe('What to generate.');+const TopicIdSchema = z+ .string()+ .min(1)+ .describe(+ 'Generation topic to add this request to. Omit to start a new topic, as `lh generate` does.',+ );++export const CreateImageGenerationRequestSchema = z+ .object({+ cfg: z.number().optional().describe('Guidance scale, for models that accept one.'),+ height: z.number().int().positive().optional().describe('Image height in pixels.'),+ imageUrls: z+ .array(z.string().url())+ .max(10)+ .optional()+ .describe('Reference images (URLs) for image-to-image models.'),+ model: z+ .string()+ .min(1)+ .optional()+ .describe("Image model id. Omit to use the account's default image model."),+ n: z+ .number()+ .int()+ .min(1)+ .max(8)+ .default(1)+ .describe('Number of images to generate, 1–8. Defaults to 1.'),+ params: ExtraParamsSchema.optional(),+ prompt: PromptSchema,+ provider: z+ .string()+ .min(1)+ .optional()+ .describe('Provider id. Omit to use the first enabled provider serving `model`.'),+ seed: z.number().int().nullish().describe('Seed; omit for a random one per image.'),+ steps: z.number().int().positive().optional().describe('Sampling steps.'),+ topicId: TopicIdSchema.optional(),+ wait: z+ .boolean()+ .default(true)+ .describe(+ 'Wait for the images before answering (up to `waitTimeoutSeconds`). Generations still running at the deadline come back with their current status; poll `GET /generations/{id}` for the rest. Set `false` to answer as soon as the work is queued.',+ ),+ waitTimeoutSeconds: z+ .number()+ .int()+ .min(1)+ .max(120)+ .default(60)+ .describe('How long `wait` may hold the request, 1–120 seconds. Defaults to 60.'),+ width: z.number().int().positive().optional().describe('Image width in pixels.'),+ })+ .strict();++export const CreateVideoGenerationRequestSchema = z+ .object({+ aspectRatio: z.string().min(1).optional().describe('Aspect ratio, for example `16:9`.'),+ cameraFixed: z.boolean().optional().describe('Keep the camera still, where supported.'),+ duration: z.number().positive().optional().describe('Video length in seconds.'),+ endImageUrl: z.string().url().nullish().describe('Last frame (URL), where supported.'),+ generateAudio: z.boolean().optional().describe('Generate a soundtrack, where supported.'),+ imageUrl: z.string().url().nullish().describe('First frame (URL) for image-to-video.'),+ model: z.string().min(1).describe('Video model id.'),+ params: ExtraParamsSchema.optional(),+ previousGenerationId: z+ .string()+ .min(1)+ .optional()+ .describe('A video generation to edit, for models that support conversational editing.'),+ prompt: PromptSchema,+ provider: z.string().min(1).describe('Provider id serving `model`.'),+ resolution: z.string().min(1).optional().describe('Output resolution, for example `720p`.'),+ seed: z.number().int().nullish().describe('Seed; omit for a random one.'),+ topicId: TopicIdSchema.optional(),+ })+ .strict();++export const GenerationAssetSchema = z+ .object({+ coverUrl: z.string().nullable().describe('Video cover image URL.'),+ duration: z.number().nullable().describe('Video length in seconds.'),+ height: z.number().nullable(),+ thumbnailUrl: z.string().nullable().describe('Resized preview URL.'),+ url: z.string().nullable().describe('Full-size asset URL.'),+ width: z.number().nullable(),+ })+ .strict()+ .meta({ id: 'GenerationAsset' });++export const GenerationErrorSchema = z+ .object({+ message: z.string().describe('Human-readable failure reason.'),+ name: z.string().describe('Error type, for example `ServerError` or `Timeout`.'),+ })+ .strict()+ .meta({ id: 'GenerationError' });++export const GenerationSchema = z+ .object({+ asset: GenerationAssetSchema.nullable().describe('The output; `null` until it succeeded.'),+ batchId: z.string().describe('The request (batch) this generation belongs to.'),+ createdAt: z.string().describe('ISO 8601 timestamp.'),+ error: GenerationErrorSchema.nullable().describe('Why it failed; `null` unless `error`.'),+ fileId: z+ .string()+ .nullable()+ .describe('Library file the output was saved as, once it succeeded.'),+ id: z.string(),+ model: z.string(),+ prompt: z.string(),+ provider: z.string(),+ seed: z.number().nullable(),+ status: z+ .enum(GENERATION_STATUSES)+ .describe('`pending` → `processing` → `success` | `error`. The last two are final.'),+ topicId: z.string().describe('The generation topic the request was added to.'),+ type: z.enum(GENERATION_KINDS),+ })+ .strict()+ .meta({ id: 'Generation' });++export const GenerationBatchCreatedSchema = z+ .object({+ batchId: z.string(),+ generations: z.array(GenerationSchema),+ topicId: z.string(),+ })+ .strict();++export const GenerationListQuerySchema = CursorPaginationQuerySchema.extend({+ type: z.enum(GENERATION_KINDS).optional().describe('Only generations of this kind.'),+});++export const GenerationListResponseSchema = paginatedListSchema(GenerationSchema, { total: true });++export const GenerationIdParamSchema = z.object({ id: z.string().min(1) });++export type CreateImageGenerationRequest = z.infer<typeof CreateImageGenerationRequestSchema>;+export type CreateVideoGenerationRequest = z.infer<typeof CreateVideoGenerationRequestSchema>;+export type GenerationAssetPayload = z.infer<typeof GenerationAssetSchema>;+export type GenerationPayload = z.infer<typeof GenerationSchema>;+export type GenerationBatchCreated = z.infer<typeof GenerationBatchCreatedSchema>;+export type GenerationListQuery = z.infer<typeof GenerationListQuerySchema>;+export type GenerationIdParam = z.infer<typeof GenerationIdParamSchema>;++// ---------- transcription ----------++/**+ * Uploaded audio is handed to the transcription procedure inline, which caps a+ * clip at 3 MB; larger recordings are uploaded first and passed as `fileId`.+ */+export const MAX_TRANSCRIPTION_UPLOAD_BYTES = 3 * 1024 * 1024;++export const TRANSCRIPTION_FORMATS = ['json', 'text', 'srt', 'verbose_json', 'vtt'] as const;++/**+ * Form fields of `POST /audio/transcriptions` other than the file, OpenAI's+ * `audio.transcriptions.create` shape plus LobeHub's `provider` and `fileId`.+ */+export const TranscriptionFieldsSchema = z+ .object({+ fileId: z.string().min(1).optional(),+ language: z.string().min(2).max(16).optional(),+ model: z.string().min(1),+ prompt: z.string().max(4096).optional(),+ provider: z.string().min(1).optional(),+ response_format: z.enum(TRANSCRIPTION_FORMATS).optional(),+ })+ .strict();++export const TranscriptionSchema = z+ .object({ text: z.string().describe('The transcript.') })+ .strict()+ .meta({ id: 'Transcription' });++export type TranscriptionFields = z.infer<typeof TranscriptionFieldsSchema>;+export type Transcription = z.infer<typeof TranscriptionSchema>;diff --git a/packages/openapi/src/types/text-generation.type.ts b/packages/openapi/src/types/text-generation.type.tsnew file mode 100644index 00000000000..920bd132bbc--- /dev/null+++ b/packages/openapi/src/types/text-generation.type.ts@@ -0,0 +1,129 @@+import { z } from 'zod';++/**+ * Text and structured-output (JSON) generation on the public REST API: one+ * completion, no tools, no conversation stored — what `lh generate text` and+ * `lh generate json` do. For agents, tools and history use `/responses`.+ */++const MessageSchema = z+ .object({+ content: z.string().describe('Plain-text message content.'),+ role: z.enum(['system', 'user', 'assistant']),+ })+ .strict();++const TextGenerationInputSchema = z+ .object({+ maxTokens: z.number().int().positive().optional().describe('Maximum output tokens.'),+ messages: z+ .array(MessageSchema)+ .min(1)+ .max(200)+ .optional()+ .describe('Conversation to complete. Use instead of, or after, `system` + `prompt`.'),+ model: z+ .string()+ .min(1)+ .optional()+ .describe("Model id. Omit to use the platform's default chat model."),+ prompt: z+ .string()+ .min(1)+ .optional()+ .describe('User prompt; appended after `messages` when both are given.'),+ provider: z+ .string()+ .min(1)+ .optional()+ .describe(+ 'Provider id (for example `lobehub`, `openai`). Omit with `model` for the default.',+ ),+ system: z.string().min(1).optional().describe('System prompt, placed first.'),+ temperature: z.number().min(0).max(2).optional().describe('Sampling temperature, 0–2.'),+ })+ .strict();++const needsInput = (v: { messages?: unknown[]; prompt?: string }) =>+ Boolean(v.prompt) || Boolean(v.messages?.length);+const needsInputIssue = {+ message: 'Provide `prompt` or `messages`',+ path: ['prompt'],+};++export const TextGenerationRequestSchema = TextGenerationInputSchema.refine(+ needsInput,+ needsInputIssue,+);++/** JSON Schema of the object to generate; the keys the model runtime honours. */+export const JsonObjectSchemaSchema = z+ .object({+ $defs: z.record(z.string(), z.unknown()).optional(),+ additionalProperties: z.boolean().optional(),+ description: z.string().optional(),+ properties: z.record(z.string(), z.unknown()),+ required: z.array(z.string()).optional(),+ title: z.string().optional(),+ type: z.literal('object'),+ })+ .strict()+ .describe(+ 'A JSON Schema with `type: "object"` at the root. Supported root keywords: `properties`, `required`, `additionalProperties`, `$defs`, `title`, `description`; others (such as `allOf`) are rejected rather than silently dropped.',+ );++export const ObjectGenerationRequestSchema = TextGenerationInputSchema.omit({+ maxTokens: true,+ temperature: true,+})+ .extend({+ schema: JsonObjectSchemaSchema,+ schemaDescription: z.string().optional().describe('What the object is, sent with the schema.'),+ schemaName: z+ .string()+ .regex(/^[\w-]{1,64}$/)+ .default('response')+ .describe('Name sent with the schema. Defaults to `response`.'),+ strict: z+ .boolean()+ .optional()+ .describe(+ 'Ask the provider to enforce the schema strictly (every property required, no extras).',+ ),+ })+ .refine(needsInput, needsInputIssue);++export const TextGenerationUsageSchema = z.object({+ inputTokens: z.number().int().nullable(),+ outputTokens: z.number().int().nullable(),+ reasoningTokens: z.number().int().nullable(),+ totalTokens: z.number().int().nullable(),+});++export const TextGenerationSchema = z.object({+ finishReason: z+ .string()+ .nullable()+ .describe('Why the model stopped, as the provider reports it (`stop`, `length`, …).'),+ model: z.string(),+ provider: z.string(),+ reasoning: z+ .string()+ .nullable()+ .describe('Reasoning of a reasoning model, kept out of `text`; `null` otherwise.'),+ text: z.string().describe('The generated text.'),+ usage: TextGenerationUsageSchema.nullable(),+});++export const ObjectGenerationSchema = z.object({+ model: z.string(),+ object: z+ .record(z.string(), z.unknown())+ .describe('The generated object, valid for the requested schema.'),+ provider: z.string(),+});++export type TextGenerationRequest = z.infer<typeof TextGenerationRequestSchema>;+export type ObjectGenerationRequest = z.infer<typeof ObjectGenerationRequestSchema>;+export type TextGeneration = z.infer<typeof TextGenerationSchema>;+export type ObjectGeneration = z.infer<typeof ObjectGenerationSchema>;diff --git a/packages/sdk/README.md b/packages/sdk/README.mdindex 3dfa920cac3..57ed78a1dab 100644--- a/packages/sdk/README.md+++ b/packages/sdk/README.md@@ -39,22 +39,24 @@ Raw spec types are exported from `@lobehub/sdk` and `@lobehub/sdk/types`.## Resources-30 resources, one per top-level path segment of the API. Method names come from each operation's `operationId` (`<resource>.<method>`) in the spec: `list` / `get` / `create` / `update` / `delete` plus PascalCase sub-segments (`files.listChunks`, `roles.updatePermissions`), and a few verbs declared by the route itself (`files.uploadBatch`, `tasks.run`, `notifications.markRead`). Each method's JSDoc names the API key scopes it needs.+35 resources, one per top-level path segment of the API. Method names come from each operation's `operationId` (`<resource>.<method>`) in the spec: `list` / `get` / `create` / `update` / `delete` plus PascalCase sub-segments (`files.listChunks`, `roles.updatePermissions`), and a few verbs declared by the route itself (`files.uploadBatch`, `tasks.run`, `notifications.markRead`). Each method's JSDoc names the API key scopes it needs.| Resource | Methods || --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `agentGroups` | `create`, `delete`, `get`, `list`, `update` || `agents` | `create`, `createAccount`, `createDuplicate`, `delete`, `deleteAccount`, `get`, `getAccount`, `list`, `listAccounts`, `update`, `updateAccount`, `updateAccountCredential` || `apiKeys` | `create`, `delete`, `get`, `list`, `update` |-| `audio` | `createSpeech` |+| `audio` | `createSpeech`, `createTranscription` || `chat` | `create`, `createGenerateReply`, `createTranslate` || `chatGroups` | `addMembers`, `create`, `delete`, `get`, `list`, `removeMembers`, `update` || `documents` | `create`, `get`, `list`, `update` || `eval` | `createBenchmarks`, `createDatasets`, `createDatasetsTestCases`, `createRuns`, `createRunsClaim`, `createRunsResults`, `createRunsRetryErrors`, `deleteBenchmarks`, `deleteDatasets`, `deleteTestCases`, `getBenchmarks`, `getDatasets`, `getRuns`, `getTestCases`, `listBenchmarks`, `listDatasets`, `listDatasetsTestCases`, `listRuns`, `listRunsResults`, `listRunsTopics`, `updateBenchmarks`, `updateDatasets`, `updateRunsStatus`, `updateRunsTopicsResult`, `updateTestCases` || `files` | `create`, `createChunks`, `delete`, `get`, `getUrl`, `list`, `listChunks`, `parse`, `query`, `update`, `uploadBatch` |+| `generations` | `delete`, `get`, `list` || `goals` | `advance`, `create`, `delete`, `get`, `getSupervision`, `list`, `pause`, `restart`, `resume`, `update` || `health` | `check` || `im` | `markRead`, `send`, `sync` |+| `images` | `generate` || `knowledgeBases` | `addFiles`, `create`, `delete`, `get`, `list`, `listFiles`, `moveFiles`, `removeFiles`, `update` || `mcpServers` | `create`, `createSync`, `delete`, `get`, `list`, `update` || `memories` | `deleteAll`, `deleteEntry`, `getPersona`, `listCategory`, `listPersonaVersions` |@@ -62,6 +64,7 @@ Raw spec types are exported from `@lobehub/sdk` and `@lobehub/sdk/types`.| `messages` | `create`, `createReply`, `delete`, `deleteMany`, `get`, `getCount`, `list` || `models` | `create`, `get`, `list`, `update` || `notifications` | `archive`, `archiveAll`, `getCounts`, `getUnreadCount`, `list`, `listSettings`, `markAllRead`, `markRead`, `updateSettings` |+| `objects` | `generate` || `permissions` | `create`, `delete`, `get`, `list`, `update` || `plugins` | `list` || `providers` | `create`, `delete`, `get`, `list`, `update` |@@ -70,9 +73,11 @@ Raw spec types are exported from `@lobehub/sdk` and `@lobehub/sdk/types`.| `roles` | `create`, `delete`, `deletePermissions`, `get`, `list`, `listPermissions`, `update`, `updatePermissions` || `signals` | `emit`, `listReceipts`, `trigger` || `tasks` | `create`, `delete`, `get`, `list`, `listRuns`, `run`, `update`, `updateStatus` |+| `text` | `generate` || `topics` | `create`, `delete`, `get`, `list`, `listThreads`, `update` || `usage` | `list` || `users` | `create`, `delete`, `deleteRoles`, `get`, `list`, `listRoles`, `me`, `update`, `updateRoles` |+| `videos` | `generate` |## Workspaces@@ -177,6 +182,45 @@ await lobehub.files.upload(buffer, { name: 'image.png', type: 'image/png' });The file name defaults to the `File` name or the path's base name, and the type to the `Blob` type.+## Generations++`text.generate` and `objects.generate` run one completion and answer at once — the REST twins of `lh generate text` and `lh generate json`. A reasoning model's reasoning comes back in `reasoning`, never inside `text`; `objects.generate` returns an object that matches your JSON Schema, or 422 when the model's reply does not:++```ts+const { data: text } = await lobehub.text.generate({+ body: { model: 'deepseek-flash', provider: 'lobehub', prompt: 'Name a pegboard use.' },+});+console.log(text?.data.text);++const { data: concept } = await lobehub.objects.generate({+ body: {+ prompt: 'A pegboard headphone hanger',+ schema: {+ additionalProperties: false,+ properties: { name: { type: 'string' }, steps: { items: { type: 'string' }, type: 'array' } },+ required: ['name', 'steps'],+ type: 'object',+ },+ strict: true,+ },+});+console.log(concept?.data.object);+```++`images.generate` and `videos.generate` start image / video generations (API keys need `generation:write`). Images wait for the result by default; videos answer at once with pending generations. `generations.wait` polls `GET /generations/{id}` until the generation is `success` or `error` and resolves with its final state; it rejects with `GenerationWaitTimeoutError` after `timeout` (10 minutes by default).++```ts+const { data } = await lobehub.videos.generate({+ body: { model: 'seedance-1-0-pro', prompt: 'Waves at sunset', provider: 'volcengine' },+});+const video = await lobehub.generations.wait(data!.data.generations[0].id, {+ onPoll: (generation) => console.log(generation.status),+ pollInterval: 5000,+});+if (video.status === 'success') console.log(video.asset?.url);+else console.error(video.error?.message);+```+### Signing in with OAuth (native apps)Public clients registered in LobeHub's OIDC provider (`lobehub-mobile`, `toby`, …) sign in with authorization code + PKCE. Open the authorize URL in the system browser session (`ASWebAuthenticationSession`, Custom Tabs), then exchange the callback:diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.tsindex 72f3ae74e41..d459032cc44 100644--- a/packages/sdk/src/client.ts+++ b/packages/sdk/src/client.ts@@ -2,13 +2,14 @@ import { DEFAULT_BASE_URL } from './constants';import { toLobeHubError } from './errors';import type { Client, Config, RequestResult } from './generated/client';import { createClient, createConfig } from './generated/client';-import type { Options } from './generated/sdk.gen';+import type { Generations, Options } from './generated/sdk.gen';import { Files, LobeHub, Responses } from './generated/sdk.gen';import type {PostApiV1FilesErrors,PostApiV1FilesResponses,PostApiV1ResponsesData,} from './generated/types.gen';+import { GenerationsResource } from './generations';import type { PageItem, PageOf, PaginateOptions } from './pagination';import { paginate } from './pagination';import { ResponseStream } from './streaming';@@ -160,11 +161,12 @@ const anySignal = (signals: AbortSignal[]) => {/*** The resource-style client returned by `createLobeHub`: every generated* resource (`lobehub.agents`, `lobehub.topics`, …) plus `paginate`,- * `responses.stream` and `files.upload`.+ * `responses.stream`, `files.upload` and `generations.wait`.*/export class LobeHubClient extends LobeHub {readonly #client: Client;#files?: FilesResource;+ #generations?: GenerationsResource;#responses?: ResponsesResource;constructor(args: { client: Client; key?: string }) {@@ -176,6 +178,10 @@ export class LobeHubClient extends LobeHub {return (this.#files ??= new FilesResource({ client: this.#client }));}+ override get generations(): GenerationsResource {+ return (this.#generations ??= new GenerationsResource({ client: this.#client }));+ }+override get responses(): ResponsesResource {return (this.#responses ??= new ResponsesResource({ client: this.#client }));}@@ -223,7 +229,9 @@ export type ThrowingLobeHubClient = {options?: UploadOptions & UploadRequestOptions<true>,) => RequestResult<PostApiV1FilesResponses, PostApiV1FilesErrors, true>;}- : ThrowingResource<LobeHubClient[K]>;+ : K extends 'generations'+ ? ThrowingResource<Generations> & Pick<GenerationsResource, 'wait'>+ : ThrowingResource<LobeHubClient[K]>;};/**diff --git a/packages/sdk/src/generated/index.ts b/packages/sdk/src/generated/index.tsindex 80fb29ea7ad..a19e3d299ee 100644--- a/packages/sdk/src/generated/index.ts+++ b/packages/sdk/src/generated/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-ts-export { AgentGroups, Agents, ApiKeys, Audio, Chat, ChatGroups, Documents, Eval, Files, Goals, Health, Im, KnowledgeBases, LobeHub, McpServers, Memories, Messages, MessageTranslations, Models, Notifications, type Options, Permissions, Plugins, Providers, PushTokens, Responses, Roles, Signals, Tasks, Topics, Usage as Usage2, Users } from './sdk.gen';-export type { Agent, AgentAccount, AgentAccountCapabilities, AgentAccountList, AgentDetail, AgentFile, AgentGroup, AgentKnowledgeBase, AgentList, AgentPlugin, AgentSignalEmission, AgentSignalReceipt, AgentSignalReceiptList, ApiError, ApiErrorCode, ApiKey, AsyncTaskError, BatchFileUploadResult, BatchGetFilesResult, ChatGenerateReplyResponse, ChatGroup, ChatGroupList, ChatGroupMember, ChatResponse, ChatTranslateResponse, ClientOptions, CreatedAgentGroup, CreatedApiKey, DeleteApiV1AgentGroupsByIdData, DeleteApiV1AgentGroupsByIdError, DeleteApiV1AgentGroupsByIdErrors, DeleteApiV1AgentGroupsByIdResponse, DeleteApiV1AgentGroupsByIdResponses, DeleteApiV1AgentsByIdAccountsByAccountIdData, DeleteApiV1AgentsByIdAccountsByAccountIdError, DeleteApiV1AgentsByIdAccountsByAccountIdErrors, DeleteApiV1AgentsByIdAccountsByAccountIdResponse, DeleteApiV1AgentsByIdAccountsByAccountIdResponses, DeleteApiV1AgentsByIdData, DeleteApiV1AgentsByIdError, DeleteApiV1AgentsByIdErrors, DeleteApiV1AgentsByIdResponse, DeleteApiV1AgentsByIdResponses, DeleteApiV1ApiKeysByIdData, DeleteApiV1ApiKeysByIdError, DeleteApiV1ApiKeysByIdErrors, DeleteApiV1ApiKeysByIdResponse, DeleteApiV1ApiKeysByIdResponses, DeleteApiV1ChatGroupsByIdData, DeleteApiV1ChatGroupsByIdError, DeleteApiV1ChatGroupsByIdErrors, DeleteApiV1ChatGroupsByIdMembersData, DeleteApiV1ChatGroupsByIdMembersError, DeleteApiV1ChatGroupsByIdMembersErrors, DeleteApiV1ChatGroupsByIdMembersResponse, DeleteApiV1ChatGroupsByIdMembersResponses, DeleteApiV1ChatGroupsByIdResponse, DeleteApiV1ChatGroupsByIdResponses, DeleteApiV1EvalBenchmarksByIdData, DeleteApiV1EvalBenchmarksByIdError, DeleteApiV1EvalBenchmarksByIdErrors, DeleteApiV1EvalBenchmarksByIdResponse, DeleteApiV1EvalBenchmarksByIdResponses, DeleteApiV1EvalDatasetsByIdData, DeleteApiV1EvalDatasetsByIdError, DeleteApiV1EvalDatasetsByIdErrors, DeleteApiV1EvalDatasetsByIdResponse, DeleteApiV1EvalDatasetsByIdResponses, DeleteApiV1EvalTestCasesByIdData, DeleteApiV1EvalTestCasesByIdError, DeleteApiV1EvalTestCasesByIdErrors, DeleteApiV1EvalTestCasesByIdResponse, DeleteApiV1EvalTestCasesByIdResponses, DeleteApiV1FilesByIdData, DeleteApiV1FilesByIdError, DeleteApiV1FilesByIdErrors, DeleteApiV1FilesByIdResponse, DeleteApiV1FilesByIdResponses, DeleteApiV1GoalsByIdData, DeleteApiV1GoalsByIdError, DeleteApiV1GoalsByIdErrors, DeleteApiV1GoalsByIdResponse, DeleteApiV1GoalsByIdResponses, DeleteApiV1KnowledgeBasesByIdData, DeleteApiV1KnowledgeBasesByIdError, DeleteApiV1KnowledgeBasesByIdErrors, DeleteApiV1KnowledgeBasesByIdFilesBatchData, DeleteApiV1KnowledgeBasesByIdFilesBatchError, DeleteApiV1KnowledgeBasesByIdFilesBatchErrors, DeleteApiV1KnowledgeBasesByIdFilesBatchResponse, DeleteApiV1KnowledgeBasesByIdFilesBatchResponses, DeleteApiV1KnowledgeBasesByIdResponse, DeleteApiV1KnowledgeBasesByIdResponses, DeleteApiV1McpServersByIdData, DeleteApiV1McpServersByIdError, DeleteApiV1McpServersByIdErrors, DeleteApiV1McpServersByIdResponse, DeleteApiV1McpServersByIdResponses, DeleteApiV1MemoriesByCategoryByIdData, DeleteApiV1MemoriesByCategoryByIdError, DeleteApiV1MemoriesByCategoryByIdErrors, DeleteApiV1MemoriesByCategoryByIdResponse, DeleteApiV1MemoriesByCategoryByIdResponses, DeleteApiV1MemoriesData, DeleteApiV1MemoriesError, DeleteApiV1MemoriesErrors, DeleteApiV1MemoriesResponse, DeleteApiV1MemoriesResponses, DeleteApiV1MessagesByIdData, DeleteApiV1MessagesByIdError, DeleteApiV1MessagesByIdErrors, DeleteApiV1MessagesByIdResponse, DeleteApiV1MessagesByIdResponses, DeleteApiV1MessagesData, DeleteApiV1MessagesError, DeleteApiV1MessagesErrors, DeleteApiV1MessagesResponse, DeleteApiV1MessagesResponses, DeleteApiV1MessageTranslationsByMessageIdData, DeleteApiV1MessageTranslationsByMessageIdError, DeleteApiV1MessageTranslationsByMessageIdErrors, DeleteApiV1MessageTranslationsByMessageIdResponse, DeleteApiV1MessageTranslationsByMessageIdResponses, DeleteApiV1PermissionsByIdData, DeleteApiV1PermissionsByIdError, DeleteApiV1PermissionsByIdErrors, DeleteApiV1PermissionsByIdResponse, DeleteApiV1PermissionsByIdResponses, DeleteApiV1ProvidersByIdData, DeleteApiV1ProvidersByIdError, DeleteApiV1ProvidersByIdErrors, DeleteApiV1ProvidersByIdResponse, DeleteApiV1ProvidersByIdResponses, DeleteApiV1PushTokensByDeviceIdData, DeleteApiV1PushTokensByDeviceIdError, DeleteApiV1PushTokensByDeviceIdErrors, DeleteApiV1PushTokensByDeviceIdResponse, DeleteApiV1PushTokensByDeviceIdResponses, DeleteApiV1RolesByIdData, DeleteApiV1RolesByIdError, DeleteApiV1RolesByIdErrors, DeleteApiV1RolesByIdPermissionsData, DeleteApiV1RolesByIdPermissionsError, DeleteApiV1RolesByIdPermissionsErrors, DeleteApiV1RolesByIdPermissionsResponse, DeleteApiV1RolesByIdPermissionsResponses, DeleteApiV1RolesByIdResponse, DeleteApiV1RolesByIdResponses, DeleteApiV1TasksByIdData, DeleteApiV1TasksByIdError, DeleteApiV1TasksByIdErrors, DeleteApiV1TasksByIdResponse, DeleteApiV1TasksByIdResponses, DeleteApiV1TopicsByIdData, DeleteApiV1TopicsByIdError, DeleteApiV1TopicsByIdErrors, DeleteApiV1TopicsByIdResponse, DeleteApiV1TopicsByIdResponses, DeleteApiV1UsersByIdData, DeleteApiV1UsersByIdError, DeleteApiV1UsersByIdErrors, DeleteApiV1UsersByIdResponse, DeleteApiV1UsersByIdResponses, DeleteApiV1UsersByIdRolesData, DeleteApiV1UsersByIdRolesError, DeleteApiV1UsersByIdRolesErrors, DeleteApiV1UsersByIdRolesResponse, DeleteApiV1UsersByIdRolesResponses, DeletedResource, DeletedResources, Document, DocumentSummary, EvalBatchReportResult, EvalBenchmark, EvalBenchmarkRubric, EvalCaseResult, EvalDataset, EvalReportReceipt, EvalReportResult, EvalRetryErrors, EvalRubricScore, EvalRun, EvalRunMetrics, EvalRunResult, EvalRunTopic, EvalStoredResult, EvalTestCase, EvalThreadResult, File, FileAsyncTask, FileChunkStatus, FileChunkTask, FileDetail, FileKnowledgeBaseRef, FileList, FileListItem, FileParseResult, FileUrl, FileUser, GetApiV1AgentGroupsByIdData, GetApiV1AgentGroupsByIdError, GetApiV1AgentGroupsByIdErrors, GetApiV1AgentGroupsByIdResponse, GetApiV1AgentGroupsByIdResponses, GetApiV1AgentGroupsData, GetApiV1AgentGroupsError, GetApiV1AgentGroupsErrors, GetApiV1AgentGroupsResponse, GetApiV1AgentGroupsResponses, GetApiV1AgentsByIdAccountsByAccountIdData, GetApiV1AgentsByIdAccountsByAccountIdError, GetApiV1AgentsByIdAccountsByAccountIdErrors, GetApiV1AgentsByIdAccountsByAccountIdResponse, GetApiV1AgentsByIdAccountsByAccountIdResponses, GetApiV1AgentsByIdAccountsData, GetApiV1AgentsByIdAccountsError, GetApiV1AgentsByIdAccountsErrors, GetApiV1AgentsByIdAccountsResponse, GetApiV1AgentsByIdAccountsResponses, GetApiV1AgentsByIdData, GetApiV1AgentsByIdError, GetApiV1AgentsByIdErrors, GetApiV1AgentsByIdResponse, GetApiV1AgentsByIdResponses, GetApiV1AgentsData, GetApiV1AgentsError, GetApiV1AgentsErrors, GetApiV1AgentsResponse, GetApiV1AgentsResponses, GetApiV1ApiKeysByIdData, GetApiV1ApiKeysByIdError, GetApiV1ApiKeysByIdErrors, GetApiV1ApiKeysByIdResponse, GetApiV1ApiKeysByIdResponses, GetApiV1ApiKeysData, GetApiV1ApiKeysError, GetApiV1ApiKeysErrors, GetApiV1ApiKeysResponse, GetApiV1ApiKeysResponses, GetApiV1ChatGroupsByIdData, GetApiV1ChatGroupsByIdError, GetApiV1ChatGroupsByIdErrors, GetApiV1ChatGroupsByIdResponse, GetApiV1ChatGroupsByIdResponses, GetApiV1ChatGroupsData, GetApiV1ChatGroupsError, GetApiV1ChatGroupsErrors, GetApiV1ChatGroupsResponse, GetApiV1ChatGroupsResponses, GetApiV1DocumentsByIdData, GetApiV1DocumentsByIdError, GetApiV1DocumentsByIdErrors, GetApiV1DocumentsByIdResponse, GetApiV1DocumentsByIdResponses, GetApiV1DocumentsData, GetApiV1DocumentsError, GetApiV1DocumentsErrors, GetApiV1DocumentsResponse, GetApiV1DocumentsResponses, GetApiV1EvalBenchmarksByIdData, GetApiV1EvalBenchmarksByIdError, GetApiV1EvalBenchmarksByIdErrors, GetApiV1EvalBenchmarksByIdResponse, GetApiV1EvalBenchmarksByIdResponses, GetApiV1EvalBenchmarksData, GetApiV1EvalBenchmarksError, GetApiV1EvalBenchmarksErrors, GetApiV1EvalBenchmarksResponse, GetApiV1EvalBenchmarksResponses, GetApiV1EvalDatasetsByDatasetIdTestCasesData, GetApiV1EvalDatasetsByDatasetIdTestCasesError, GetApiV1EvalDatasetsByDatasetIdTestCasesErrors, GetApiV1EvalDatasetsByDatasetIdTestCasesResponse, GetApiV1EvalDatasetsByDatasetIdTestCasesResponses, GetApiV1EvalDatasetsByIdData, GetApiV1EvalDatasetsByIdError, GetApiV1EvalDatasetsByIdErrors, GetApiV1EvalDatasetsByIdResponse, GetApiV1EvalDatasetsByIdResponses, GetApiV1EvalDatasetsData, GetApiV1EvalDatasetsError, GetApiV1EvalDatasetsErrors, GetApiV1EvalDatasetsResponse, GetApiV1EvalDatasetsResponses, GetApiV1EvalRunsByIdData, GetApiV1EvalRunsByIdError, GetApiV1EvalRunsByIdErrors, GetApiV1EvalRunsByIdResponse, GetApiV1EvalRunsByIdResponses, GetApiV1EvalRunsByIdResultsData, GetApiV1EvalRunsByIdResultsError, GetApiV1EvalRunsByIdResultsErrors, GetApiV1EvalRunsByIdResultsResponse, GetApiV1EvalRunsByIdResultsResponses, GetApiV1EvalRunsByIdTopicsData, GetApiV1EvalRunsByIdTopicsError, GetApiV1EvalRunsByIdTopicsErrors, GetApiV1EvalRunsByIdTopicsResponse, GetApiV1EvalRunsByIdTopicsResponses, GetApiV1EvalRunsData, GetApiV1EvalRunsError, GetApiV1EvalRunsErrors, GetApiV1EvalRunsResponse, GetApiV1EvalRunsResponses, GetApiV1EvalTestCasesByIdData, GetApiV1EvalTestCasesByIdError, GetApiV1EvalTestCasesByIdErrors, GetApiV1EvalTestCasesByIdResponse, GetApiV1EvalTestCasesByIdResponses, GetApiV1FilesByIdChunksData, GetApiV1FilesByIdChunksError, GetApiV1FilesByIdChunksErrors, GetApiV1FilesByIdChunksResponse, GetApiV1FilesByIdChunksResponses, GetApiV1FilesByIdData, GetApiV1FilesByIdError, GetApiV1FilesByIdErrors, GetApiV1FilesByIdResponse, GetApiV1FilesByIdResponses, GetApiV1FilesByIdUrlData, GetApiV1FilesByIdUrlError, GetApiV1FilesByIdUrlErrors, GetApiV1FilesByIdUrlResponse, GetApiV1FilesByIdUrlResponses, GetApiV1FilesData, GetApiV1FilesError, GetApiV1FilesErrors, GetApiV1FilesResponse, GetApiV1FilesResponses, GetApiV1GoalsByIdData, GetApiV1GoalsByIdError, GetApiV1GoalsByIdErrors, GetApiV1GoalsByIdResponse, GetApiV1GoalsByIdResponses, GetApiV1GoalsByIdSupervisionData, GetApiV1GoalsByIdSupervisionError, GetApiV1GoalsByIdSupervisionErrors, GetApiV1GoalsByIdSupervisionResponse, GetApiV1GoalsByIdSupervisionResponses, GetApiV1GoalsData, GetApiV1GoalsError, GetApiV1GoalsErrors, GetApiV1GoalsResponse, GetApiV1GoalsResponses, GetApiV1HealthData, GetApiV1HealthResponse, GetApiV1HealthResponses, GetApiV1ImTopicsByTopicIdSyncData, GetApiV1ImTopicsByTopicIdSyncError, GetApiV1ImTopicsByTopicIdSyncErrors, GetApiV1ImTopicsByTopicIdSyncResponse, GetApiV1ImTopicsByTopicIdSyncResponses, GetApiV1KnowledgeBasesByIdData, GetApiV1KnowledgeBasesByIdError, GetApiV1KnowledgeBasesByIdErrors, GetApiV1KnowledgeBasesByIdFilesData, GetApiV1KnowledgeBasesByIdFilesError, GetApiV1KnowledgeBasesByIdFilesErrors, GetApiV1KnowledgeBasesByIdFilesResponse, GetApiV1KnowledgeBasesByIdFilesResponses, GetApiV1KnowledgeBasesByIdResponse, GetApiV1KnowledgeBasesByIdResponses, GetApiV1KnowledgeBasesData, GetApiV1KnowledgeBasesError, GetApiV1KnowledgeBasesErrors, GetApiV1KnowledgeBasesResponse, GetApiV1KnowledgeBasesResponses, GetApiV1McpServersByIdData, GetApiV1McpServersByIdError, GetApiV1McpServersByIdErrors, GetApiV1McpServersByIdResponse, GetApiV1McpServersByIdResponses, GetApiV1McpServersData, GetApiV1McpServersError, GetApiV1McpServersErrors, GetApiV1McpServersResponse, GetApiV1McpServersResponses, GetApiV1MemoriesByCategoryData, GetApiV1MemoriesByCategoryError, GetApiV1MemoriesByCategoryErrors, GetApiV1MemoriesByCategoryResponse, GetApiV1MemoriesByCategoryResponses, GetApiV1MemoriesPersonaData, GetApiV1MemoriesPersonaError, GetApiV1MemoriesPersonaErrors, GetApiV1MemoriesPersonaResponse, GetApiV1MemoriesPersonaResponses, GetApiV1MemoriesPersonaVersionsData, GetApiV1MemoriesPersonaVersionsError, GetApiV1MemoriesPersonaVersionsErrors, GetApiV1MemoriesPersonaVersionsResponse, GetApiV1MemoriesPersonaVersionsResponses, GetApiV1MessagesByIdData, GetApiV1MessagesByIdError, GetApiV1MessagesByIdErrors, GetApiV1MessagesByIdResponse, GetApiV1MessagesByIdResponses, GetApiV1MessagesCountData, GetApiV1MessagesCountError, GetApiV1MessagesCountErrors, GetApiV1MessagesCountResponse, GetApiV1MessagesCountResponses, GetApiV1MessagesData, GetApiV1MessagesError, GetApiV1MessagesErrors, GetApiV1MessagesResponse, GetApiV1MessagesResponses, GetApiV1MessageTranslationsByMessageIdData, GetApiV1MessageTranslationsByMessageIdError, GetApiV1MessageTranslationsByMessageIdErrors, GetApiV1MessageTranslationsByMessageIdResponse, GetApiV1MessageTranslationsByMessageIdResponses, GetApiV1ModelsByProviderIdByModelIdData, GetApiV1ModelsByProviderIdByModelIdError, GetApiV1ModelsByProviderIdByModelIdErrors, GetApiV1ModelsByProviderIdByModelIdResponse, GetApiV1ModelsByProviderIdByModelIdResponses, GetApiV1ModelsData, GetApiV1ModelsError, GetApiV1ModelsErrors, GetApiV1ModelsResponse, GetApiV1ModelsResponses, GetApiV1NotificationsCountsData, GetApiV1NotificationsCountsError, GetApiV1NotificationsCountsErrors, GetApiV1NotificationsCountsResponse, GetApiV1NotificationsCountsResponses, GetApiV1NotificationsData, GetApiV1NotificationsError, GetApiV1NotificationsErrors, GetApiV1NotificationsResponse, GetApiV1NotificationsResponses, GetApiV1NotificationsSettingsData, GetApiV1NotificationsSettingsError, GetApiV1NotificationsSettingsErrors, GetApiV1NotificationsSettingsResponse, GetApiV1NotificationsSettingsResponses, GetApiV1NotificationsUnreadCountData, GetApiV1NotificationsUnreadCountError, GetApiV1NotificationsUnreadCountErrors, GetApiV1NotificationsUnreadCountResponse, GetApiV1NotificationsUnreadCountResponses, GetApiV1PermissionsByIdData, GetApiV1PermissionsByIdError, GetApiV1PermissionsByIdErrors, GetApiV1PermissionsByIdResponse, GetApiV1PermissionsByIdResponses, GetApiV1PermissionsData, GetApiV1PermissionsError, GetApiV1PermissionsErrors, GetApiV1PermissionsResponse, GetApiV1PermissionsResponses, GetApiV1PluginsData, GetApiV1PluginsError, GetApiV1PluginsErrors, GetApiV1PluginsResponse, GetApiV1PluginsResponses, GetApiV1ProvidersByIdData, GetApiV1ProvidersByIdError, GetApiV1ProvidersByIdErrors, GetApiV1ProvidersByIdResponse, GetApiV1ProvidersByIdResponses, GetApiV1ProvidersData, GetApiV1ProvidersError, GetApiV1ProvidersErrors, GetApiV1ProvidersResponse, GetApiV1ProvidersResponses, GetApiV1RolesByIdData, GetApiV1RolesByIdError, GetApiV1RolesByIdErrors, GetApiV1RolesByIdPermissionsData, GetApiV1RolesByIdPermissionsError, GetApiV1RolesByIdPermissionsErrors, GetApiV1RolesByIdPermissionsResponse, GetApiV1RolesByIdPermissionsResponses, GetApiV1RolesByIdResponse, GetApiV1RolesByIdResponses, GetApiV1RolesData, GetApiV1RolesError, GetApiV1RolesErrors, GetApiV1RolesResponse, GetApiV1RolesResponses, GetApiV1SignalsReceiptsData, GetApiV1SignalsReceiptsError, GetApiV1SignalsReceiptsErrors, GetApiV1SignalsReceiptsResponse, GetApiV1SignalsReceiptsResponses, GetApiV1TasksByIdData, GetApiV1TasksByIdError, GetApiV1TasksByIdErrors, GetApiV1TasksByIdResponse, GetApiV1TasksByIdResponses, GetApiV1TasksByIdRunsData, GetApiV1TasksByIdRunsError, GetApiV1TasksByIdRunsErrors, GetApiV1TasksByIdRunsResponse, GetApiV1TasksByIdRunsResponses, GetApiV1TasksData, GetApiV1TasksError, GetApiV1TasksErrors, GetApiV1TasksResponse, GetApiV1TasksResponses, GetApiV1TopicsByIdData, GetApiV1TopicsByIdError, GetApiV1TopicsByIdErrors, GetApiV1TopicsByIdResponse, GetApiV1TopicsByIdResponses, GetApiV1TopicsByTopicIdThreadsData, GetApiV1TopicsByTopicIdThreadsError, GetApiV1TopicsByTopicIdThreadsErrors, GetApiV1TopicsByTopicIdThreadsResponse, GetApiV1TopicsByTopicIdThreadsResponses, GetApiV1TopicsData, GetApiV1TopicsError, GetApiV1TopicsErrors, GetApiV1TopicsResponse, GetApiV1TopicsResponses, GetApiV1UsageData, GetApiV1UsageError, GetApiV1UsageErrors, GetApiV1UsageResponse, GetApiV1UsageResponses, GetApiV1UsersByIdData, GetApiV1UsersByIdError, GetApiV1UsersByIdErrors, GetApiV1UsersByIdResponse, GetApiV1UsersByIdResponses, GetApiV1UsersByIdRolesData, GetApiV1UsersByIdRolesError, GetApiV1UsersByIdRolesErrors, GetApiV1UsersByIdRolesResponse, GetApiV1UsersByIdRolesResponses, GetApiV1UsersData, GetApiV1UsersError, GetApiV1UsersErrors, GetApiV1UsersMeData, GetApiV1UsersMeError, GetApiV1UsersMeErrors, GetApiV1UsersMeResponse, GetApiV1UsersMeResponses, GetApiV1UsersResponse, GetApiV1UsersResponses, Goal, GoalAdvanceResult, GoalDecisionOption, GoalGraph, GoalGraphDecision, GoalGraphEdge, GoalGraphEvent, GoalGraphNode, GoalGraphSnapshot, GoalGraphWorkVersionLink, GoalList, GoalListItem, GoalRestartResult, GoalSupervision, IdempotencyKey, ImMessage, ImReadResult, ImSendResult, ImSyncResult, InstalledPlugin, InstalledPluginList, KnowledgeBase, KnowledgeBaseDetail, KnowledgeBaseFileOperationResult, KnowledgeBaseList, KnowledgeBaseListItem, McpServer, McpServerSyncResult, McpServerTool, MemoryActivity, MemoryCategoryEntries, MemoryContext, MemoryExperience, MemoryIdentity, MemoryPersona, MemoryPersonaVersion, MemoryPreference, Message, MessageTranslation, MessageTranslationWrite, Model, Notification, NotificationCategoryCount, NotificationSettings, NotificationUnreadCount, PageHasMore, PageNextCursor, PageTotal, PatchApiV1AgentGroupsByIdData, PatchApiV1AgentGroupsByIdError, PatchApiV1AgentGroupsByIdErrors, PatchApiV1AgentGroupsByIdResponse, PatchApiV1AgentGroupsByIdResponses, PatchApiV1AgentsByIdAccountsByAccountIdData, PatchApiV1AgentsByIdAccountsByAccountIdError, PatchApiV1AgentsByIdAccountsByAccountIdErrors, PatchApiV1AgentsByIdAccountsByAccountIdResponse, PatchApiV1AgentsByIdAccountsByAccountIdResponses, PatchApiV1AgentsByIdData, PatchApiV1AgentsByIdError, PatchApiV1AgentsByIdErrors, PatchApiV1AgentsByIdResponse, PatchApiV1AgentsByIdResponses, PatchApiV1ApiKeysByIdData, PatchApiV1ApiKeysByIdError, PatchApiV1ApiKeysByIdErrors, PatchApiV1ApiKeysByIdResponse, PatchApiV1ApiKeysByIdResponses, PatchApiV1ChatGroupsByIdData, PatchApiV1ChatGroupsByIdError, PatchApiV1ChatGroupsByIdErrors, PatchApiV1ChatGroupsByIdResponse, PatchApiV1ChatGroupsByIdResponses, PatchApiV1DocumentsByIdData, PatchApiV1DocumentsByIdError, PatchApiV1DocumentsByIdErrors, PatchApiV1DocumentsByIdResponse, PatchApiV1DocumentsByIdResponses, PatchApiV1EvalBenchmarksByIdData, PatchApiV1EvalBenchmarksByIdError, PatchApiV1EvalBenchmarksByIdErrors, PatchApiV1EvalBenchmarksByIdResponse, PatchApiV1EvalBenchmarksByIdResponses, PatchApiV1EvalDatasetsByIdData, PatchApiV1EvalDatasetsByIdError, PatchApiV1EvalDatasetsByIdErrors, PatchApiV1EvalDatasetsByIdResponse, PatchApiV1EvalDatasetsByIdResponses, PatchApiV1EvalRunsByIdStatusData, PatchApiV1EvalRunsByIdStatusError, PatchApiV1EvalRunsByIdStatusErrors, PatchApiV1EvalRunsByIdStatusResponse, PatchApiV1EvalRunsByIdStatusResponses, PatchApiV1EvalTestCasesByIdData, PatchApiV1EvalTestCasesByIdError, PatchApiV1EvalTestCasesByIdErrors, PatchApiV1EvalTestCasesByIdResponse, PatchApiV1EvalTestCasesByIdResponses, PatchApiV1FilesByIdData, PatchApiV1FilesByIdError, PatchApiV1FilesByIdErrors, PatchApiV1FilesByIdResponse, PatchApiV1FilesByIdResponses, PatchApiV1GoalsByIdData, PatchApiV1GoalsByIdError, PatchApiV1GoalsByIdErrors, PatchApiV1GoalsByIdResponse, PatchApiV1GoalsByIdResponses, PatchApiV1KnowledgeBasesByIdData, PatchApiV1KnowledgeBasesByIdError, PatchApiV1KnowledgeBasesByIdErrors, PatchApiV1KnowledgeBasesByIdResponse, PatchApiV1KnowledgeBasesByIdResponses, PatchApiV1McpServersByIdData, PatchApiV1McpServersByIdError, PatchApiV1McpServersByIdErrors, PatchApiV1McpServersByIdResponse, PatchApiV1McpServersByIdResponses, PatchApiV1MessageTranslationsByMessageIdData, PatchApiV1MessageTranslationsByMessageIdError, PatchApiV1MessageTranslationsByMessageIdErrors, PatchApiV1MessageTranslationsByMessageIdResponse, PatchApiV1MessageTranslationsByMessageIdResponses, PatchApiV1ModelsByProviderIdByModelIdData, PatchApiV1ModelsByProviderIdByModelIdError, PatchApiV1ModelsByProviderIdByModelIdErrors, PatchApiV1ModelsByProviderIdByModelIdResponse, PatchApiV1ModelsByProviderIdByModelIdResponses, PatchApiV1NotificationsSettingsData, PatchApiV1NotificationsSettingsError, PatchApiV1NotificationsSettingsErrors, PatchApiV1NotificationsSettingsResponse, PatchApiV1NotificationsSettingsResponses, PatchApiV1PermissionsByIdData, PatchApiV1PermissionsByIdError, PatchApiV1PermissionsByIdErrors, PatchApiV1PermissionsByIdResponse, PatchApiV1PermissionsByIdResponses, PatchApiV1ProvidersByIdData, PatchApiV1ProvidersByIdError, PatchApiV1ProvidersByIdErrors, PatchApiV1ProvidersByIdResponse, PatchApiV1ProvidersByIdResponses, PatchApiV1RolesByIdData, PatchApiV1RolesByIdError, PatchApiV1RolesByIdErrors, PatchApiV1RolesByIdPermissionsData, PatchApiV1RolesByIdPermissionsError, PatchApiV1RolesByIdPermissionsErrors, PatchApiV1RolesByIdPermissionsResponse, PatchApiV1RolesByIdPermissionsResponses, PatchApiV1RolesByIdResponse, PatchApiV1RolesByIdResponses, PatchApiV1TasksByIdData, PatchApiV1TasksByIdError, PatchApiV1TasksByIdErrors, PatchApiV1TasksByIdResponse, PatchApiV1TasksByIdResponses, PatchApiV1TasksByIdStatusData, PatchApiV1TasksByIdStatusError, PatchApiV1TasksByIdStatusErrors, PatchApiV1TasksByIdStatusResponse, PatchApiV1TasksByIdStatusResponses, PatchApiV1TopicsByIdData, PatchApiV1TopicsByIdError, PatchApiV1TopicsByIdErrors, PatchApiV1TopicsByIdResponse, PatchApiV1TopicsByIdResponses, PatchApiV1UsersByIdData, PatchApiV1UsersByIdError, PatchApiV1UsersByIdErrors, PatchApiV1UsersByIdResponse, PatchApiV1UsersByIdResponses, PatchApiV1UsersByIdRolesData, PatchApiV1UsersByIdRolesError, PatchApiV1UsersByIdRolesErrors, PatchApiV1UsersByIdRolesResponse, PatchApiV1UsersByIdRolesResponses, Permission, PermissionList, PostApiV1AgentGroupsData, PostApiV1AgentGroupsError, PostApiV1AgentGroupsErrors, PostApiV1AgentGroupsResponse, PostApiV1AgentGroupsResponses, PostApiV1AgentsByIdAccountsData, PostApiV1AgentsByIdAccountsError, PostApiV1AgentsByIdAccountsErrors, PostApiV1AgentsByIdAccountsResponse, PostApiV1AgentsByIdAccountsResponses, PostApiV1AgentsByIdDuplicateData, PostApiV1AgentsByIdDuplicateError, PostApiV1AgentsByIdDuplicateErrors, PostApiV1AgentsByIdDuplicateResponse, PostApiV1AgentsByIdDuplicateResponses, PostApiV1AgentsData, PostApiV1AgentsError, PostApiV1AgentsErrors, PostApiV1AgentsResponse, PostApiV1AgentsResponses, PostApiV1ApiKeysData, PostApiV1ApiKeysError, PostApiV1ApiKeysErrors, PostApiV1ApiKeysResponse, PostApiV1ApiKeysResponses, PostApiV1AudioSpeechData, PostApiV1AudioSpeechError, PostApiV1AudioSpeechErrors, PostApiV1AudioSpeechResponse, PostApiV1AudioSpeechResponses, PostApiV1ChatData, PostApiV1ChatError, PostApiV1ChatErrors, PostApiV1ChatGenerateReplyData, PostApiV1ChatGenerateReplyError, PostApiV1ChatGenerateReplyErrors, PostApiV1ChatGenerateReplyResponse, PostApiV1ChatGenerateReplyResponses, PostApiV1ChatGroupsByIdMembersData, PostApiV1ChatGroupsByIdMembersError, PostApiV1ChatGroupsByIdMembersErrors, PostApiV1ChatGroupsByIdMembersResponse, PostApiV1ChatGroupsByIdMembersResponses, PostApiV1ChatGroupsData, PostApiV1ChatGroupsError, PostApiV1ChatGroupsErrors, PostApiV1ChatGroupsResponse, PostApiV1ChatGroupsResponses, PostApiV1ChatResponse, PostApiV1ChatResponses, PostApiV1ChatTranslateData, PostApiV1ChatTranslateError, PostApiV1ChatTranslateErrors, PostApiV1ChatTranslateResponse, PostApiV1ChatTranslateResponses, PostApiV1DocumentsData, PostApiV1DocumentsError, PostApiV1DocumentsErrors, PostApiV1DocumentsResponse, PostApiV1DocumentsResponses, PostApiV1EvalBenchmarksData, PostApiV1EvalBenchmarksError, PostApiV1EvalBenchmarksErrors, PostApiV1EvalBenchmarksResponse, PostApiV1EvalBenchmarksResponses, PostApiV1EvalDatasetsByDatasetIdTestCasesData, PostApiV1EvalDatasetsByDatasetIdTestCasesError, PostApiV1EvalDatasetsByDatasetIdTestCasesErrors, PostApiV1EvalDatasetsByDatasetIdTestCasesResponse, PostApiV1EvalDatasetsByDatasetIdTestCasesResponses, PostApiV1EvalDatasetsData, PostApiV1EvalDatasetsError, PostApiV1EvalDatasetsErrors, PostApiV1EvalDatasetsResponse, PostApiV1EvalDatasetsResponses, PostApiV1EvalRunsByIdClaimData, PostApiV1EvalRunsByIdClaimError, PostApiV1EvalRunsByIdClaimErrors, PostApiV1EvalRunsByIdClaimResponse, PostApiV1EvalRunsByIdClaimResponses, PostApiV1EvalRunsByIdResultsData, PostApiV1EvalRunsByIdResultsError, PostApiV1EvalRunsByIdResultsErrors, PostApiV1EvalRunsByIdResultsResponse, PostApiV1EvalRunsByIdResultsResponses, PostApiV1EvalRunsByIdRetryErrorsData, PostApiV1EvalRunsByIdRetryErrorsError, PostApiV1EvalRunsByIdRetryErrorsErrors, PostApiV1EvalRunsByIdRetryErrorsResponse, PostApiV1EvalRunsByIdRetryErrorsResponses, PostApiV1EvalRunsData, PostApiV1EvalRunsError, PostApiV1EvalRunsErrors, PostApiV1EvalRunsResponse, PostApiV1EvalRunsResponses, PostApiV1FilesBatchesData, PostApiV1FilesBatchesError, PostApiV1FilesBatchesErrors, PostApiV1FilesBatchesResponse, PostApiV1FilesBatchesResponses, PostApiV1FilesByIdChunksData, PostApiV1FilesByIdChunksError, PostApiV1FilesByIdChunksErrors, PostApiV1FilesByIdChunksResponse, PostApiV1FilesByIdChunksResponses, PostApiV1FilesByIdParsesData, PostApiV1FilesByIdParsesError, PostApiV1FilesByIdParsesErrors, PostApiV1FilesByIdParsesResponse, PostApiV1FilesByIdParsesResponses, PostApiV1FilesData, PostApiV1FilesError, PostApiV1FilesErrors, PostApiV1FilesQueriesData, PostApiV1FilesQueriesError, PostApiV1FilesQueriesErrors, PostApiV1FilesQueriesResponse, PostApiV1FilesQueriesResponses, PostApiV1FilesResponse, PostApiV1FilesResponses, PostApiV1GoalsByIdAdvanceData, PostApiV1GoalsByIdAdvanceError, PostApiV1GoalsByIdAdvanceErrors, PostApiV1GoalsByIdAdvanceResponse, PostApiV1GoalsByIdAdvanceResponses, PostApiV1GoalsByIdPauseData, PostApiV1GoalsByIdPauseError, PostApiV1GoalsByIdPauseErrors, PostApiV1GoalsByIdPauseResponse, PostApiV1GoalsByIdPauseResponses, PostApiV1GoalsByIdRestartData, PostApiV1GoalsByIdRestartError, PostApiV1GoalsByIdRestartErrors, PostApiV1GoalsByIdRestartResponse, PostApiV1GoalsByIdRestartResponses, PostApiV1GoalsByIdResumeData, PostApiV1GoalsByIdResumeError, PostApiV1GoalsByIdResumeErrors, PostApiV1GoalsByIdResumeResponse, PostApiV1GoalsByIdResumeResponses, PostApiV1GoalsData, PostApiV1GoalsError, PostApiV1GoalsErrors, PostApiV1GoalsResponse, PostApiV1GoalsResponses, PostApiV1ImMessagesData, PostApiV1ImMessagesError, PostApiV1ImMessagesErrors, PostApiV1ImMessagesResponse, PostApiV1ImMessagesResponses, PostApiV1ImTopicsByTopicIdReadData, PostApiV1ImTopicsByTopicIdReadError, PostApiV1ImTopicsByTopicIdReadErrors, PostApiV1ImTopicsByTopicIdReadResponse, PostApiV1ImTopicsByTopicIdReadResponses, PostApiV1KnowledgeBasesByIdFilesBatchData, PostApiV1KnowledgeBasesByIdFilesBatchError, PostApiV1KnowledgeBasesByIdFilesBatchErrors, PostApiV1KnowledgeBasesByIdFilesBatchResponse, PostApiV1KnowledgeBasesByIdFilesBatchResponses, PostApiV1KnowledgeBasesByIdFilesMoveData, PostApiV1KnowledgeBasesByIdFilesMoveError, PostApiV1KnowledgeBasesByIdFilesMoveErrors, PostApiV1KnowledgeBasesByIdFilesMoveResponse, PostApiV1KnowledgeBasesByIdFilesMoveResponses, PostApiV1KnowledgeBasesData, PostApiV1KnowledgeBasesError, PostApiV1KnowledgeBasesErrors, PostApiV1KnowledgeBasesResponse, PostApiV1KnowledgeBasesResponses, PostApiV1McpServersByIdSyncData, PostApiV1McpServersByIdSyncError, PostApiV1McpServersByIdSyncErrors, PostApiV1McpServersByIdSyncResponse, PostApiV1McpServersByIdSyncResponses, PostApiV1McpServersData, PostApiV1McpServersError, PostApiV1McpServersErrors, PostApiV1McpServersResponse, PostApiV1McpServersResponses, PostApiV1MessagesData, PostApiV1MessagesError, PostApiV1MessagesErrors, PostApiV1MessagesRepliesData, PostApiV1MessagesRepliesError, PostApiV1MessagesRepliesErrors, PostApiV1MessagesRepliesResponse, PostApiV1MessagesRepliesResponses, PostApiV1MessagesResponse, PostApiV1MessagesResponses, PostApiV1MessageTranslationsByMessageIdData, PostApiV1MessageTranslationsByMessageIdError, PostApiV1MessageTranslationsByMessageIdErrors, PostApiV1MessageTranslationsByMessageIdResponse, PostApiV1MessageTranslationsByMessageIdResponses, PostApiV1ModelsData, PostApiV1ModelsError, PostApiV1ModelsErrors, PostApiV1ModelsResponse, PostApiV1ModelsResponses, PostApiV1NotificationsArchiveAllData, PostApiV1NotificationsArchiveAllError, PostApiV1NotificationsArchiveAllErrors, PostApiV1NotificationsArchiveAllResponse, PostApiV1NotificationsArchiveAllResponses, PostApiV1NotificationsByIdArchiveData, PostApiV1NotificationsByIdArchiveError, PostApiV1NotificationsByIdArchiveErrors, PostApiV1NotificationsByIdArchiveResponse, PostApiV1NotificationsByIdArchiveResponses, PostApiV1NotificationsReadAllData, PostApiV1NotificationsReadAllError, PostApiV1NotificationsReadAllErrors, PostApiV1NotificationsReadAllResponse, PostApiV1NotificationsReadAllResponses, PostApiV1NotificationsReadData, PostApiV1NotificationsReadError, PostApiV1NotificationsReadErrors, PostApiV1NotificationsReadResponse, PostApiV1NotificationsReadResponses, PostApiV1PermissionsData, PostApiV1PermissionsError, PostApiV1PermissionsErrors, PostApiV1PermissionsResponse, PostApiV1PermissionsResponses, PostApiV1ProvidersData, PostApiV1ProvidersError, PostApiV1ProvidersErrors, PostApiV1ProvidersResponse, PostApiV1ProvidersResponses, PostApiV1ResponsesData, PostApiV1ResponsesError, PostApiV1ResponsesErrors, PostApiV1ResponsesResponse, PostApiV1ResponsesResponses, PostApiV1RolesData, PostApiV1RolesError, PostApiV1RolesErrors, PostApiV1RolesResponse, PostApiV1RolesResponses, PostApiV1SignalsSourceEventsData, PostApiV1SignalsSourceEventsError, PostApiV1SignalsSourceEventsErrors, PostApiV1SignalsSourceEventsResponse, PostApiV1SignalsSourceEventsResponses, PostApiV1SignalsTriggerData, PostApiV1SignalsTriggerError, PostApiV1SignalsTriggerErrors, PostApiV1SignalsTriggerResponse, PostApiV1SignalsTriggerResponses, PostApiV1TasksByIdRunsData, PostApiV1TasksByIdRunsError, PostApiV1TasksByIdRunsErrors, PostApiV1TasksByIdRunsResponse, PostApiV1TasksByIdRunsResponses, PostApiV1TasksData, PostApiV1TasksError, PostApiV1TasksErrors, PostApiV1TasksResponse, PostApiV1TasksResponses, PostApiV1TopicsData, PostApiV1TopicsError, PostApiV1TopicsErrors, PostApiV1TopicsResponse, PostApiV1TopicsResponses, PostApiV1UsersData, PostApiV1UsersError, PostApiV1UsersErrors, PostApiV1UsersResponse, PostApiV1UsersResponses, Provider, PushTokenRegistration, PutApiV1AgentsByIdAccountsByAccountIdCredentialData, PutApiV1AgentsByIdAccountsByAccountIdCredentialError, PutApiV1AgentsByIdAccountsByAccountIdCredentialErrors, PutApiV1AgentsByIdAccountsByAccountIdCredentialResponse, PutApiV1AgentsByIdAccountsByAccountIdCredentialResponses, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultData, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultError, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultErrors, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultResponse, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultResponses, PutApiV1PushTokensByDeviceIdData, PutApiV1PushTokensByDeviceIdError, PutApiV1PushTokensByDeviceIdErrors, PutApiV1PushTokensByDeviceIdResponse, PutApiV1PushTokensByDeviceIdResponses, ResponseCompletedEvent, ResponseContentPartAddedEvent, ResponseContentPartDoneEvent, ResponseCreatedEvent, ResponseError, ResponseFailedEvent, ResponseFunctionCall, ResponseFunctionCallArgumentsDeltaEvent, ResponseFunctionCallArgumentsDoneEvent, ResponseFunctionCallOutput, ResponseIncompleteEvent, ResponseInProgressEvent, ResponseObject, ResponseOutputItem, ResponseOutputItemAddedEvent, ResponseOutputItemDoneEvent, ResponseOutputMessage, ResponseOutputText, ResponseOutputTextDeltaEvent, ResponseOutputTextDoneEvent, ResponseStreamEvent, ResponseUsage, Role, RoleList, RolePermission, RolePermissionList, RolePermissionsUpdateResult, Task, TaskDetail, TaskDetailActivity, TaskDetailSubtask, TaskDetailWorkspaceNode, TaskLabelRef, TaskList, TaskListItem, TaskRun, TaskRunStarted, TaskStatusUpdateResult, Topic, TopicSummary, TopicThread, Usage, User, UserIdentity, UserList, UserRole, WorkspaceId } from './types.gen';+export { AgentGroups, Agents, ApiKeys, Audio, Chat, ChatGroups, Documents, Eval, Files, Generations, Goals, Health, Im, Images, KnowledgeBases, LobeHub, McpServers, Memories, Messages, MessageTranslations, Models, Notifications, Objects, type Options, Permissions, Plugins, Providers, PushTokens, Responses, Roles, Signals, Tasks, Text, Topics, Usage as Usage2, Users, Videos } from './sdk.gen';+export type { Agent, AgentAccount, AgentAccountCapabilities, AgentAccountList, AgentDetail, AgentFile, AgentGroup, AgentKnowledgeBase, AgentList, AgentPlugin, AgentSignalEmission, AgentSignalReceipt, AgentSignalReceiptList, ApiError, ApiErrorCode, ApiKey, AsyncTaskError, BatchFileUploadResult, BatchGetFilesResult, ChatGenerateReplyResponse, ChatGroup, ChatGroupList, ChatGroupMember, ChatResponse, ChatTranslateResponse, ClientOptions, CreatedAgentGroup, CreatedApiKey, DeleteApiV1AgentGroupsByIdData, DeleteApiV1AgentGroupsByIdError, DeleteApiV1AgentGroupsByIdErrors, DeleteApiV1AgentGroupsByIdResponse, DeleteApiV1AgentGroupsByIdResponses, DeleteApiV1AgentsByIdAccountsByAccountIdData, DeleteApiV1AgentsByIdAccountsByAccountIdError, DeleteApiV1AgentsByIdAccountsByAccountIdErrors, DeleteApiV1AgentsByIdAccountsByAccountIdResponse, DeleteApiV1AgentsByIdAccountsByAccountIdResponses, DeleteApiV1AgentsByIdData, DeleteApiV1AgentsByIdError, DeleteApiV1AgentsByIdErrors, DeleteApiV1AgentsByIdResponse, DeleteApiV1AgentsByIdResponses, DeleteApiV1ApiKeysByIdData, DeleteApiV1ApiKeysByIdError, DeleteApiV1ApiKeysByIdErrors, DeleteApiV1ApiKeysByIdResponse, DeleteApiV1ApiKeysByIdResponses, DeleteApiV1ChatGroupsByIdData, DeleteApiV1ChatGroupsByIdError, DeleteApiV1ChatGroupsByIdErrors, DeleteApiV1ChatGroupsByIdMembersData, DeleteApiV1ChatGroupsByIdMembersError, DeleteApiV1ChatGroupsByIdMembersErrors, DeleteApiV1ChatGroupsByIdMembersResponse, DeleteApiV1ChatGroupsByIdMembersResponses, DeleteApiV1ChatGroupsByIdResponse, DeleteApiV1ChatGroupsByIdResponses, DeleteApiV1EvalBenchmarksByIdData, DeleteApiV1EvalBenchmarksByIdError, DeleteApiV1EvalBenchmarksByIdErrors, DeleteApiV1EvalBenchmarksByIdResponse, DeleteApiV1EvalBenchmarksByIdResponses, DeleteApiV1EvalDatasetsByIdData, DeleteApiV1EvalDatasetsByIdError, DeleteApiV1EvalDatasetsByIdErrors, DeleteApiV1EvalDatasetsByIdResponse, DeleteApiV1EvalDatasetsByIdResponses, DeleteApiV1EvalTestCasesByIdData, DeleteApiV1EvalTestCasesByIdError, DeleteApiV1EvalTestCasesByIdErrors, DeleteApiV1EvalTestCasesByIdResponse, DeleteApiV1EvalTestCasesByIdResponses, DeleteApiV1FilesByIdData, DeleteApiV1FilesByIdError, DeleteApiV1FilesByIdErrors, DeleteApiV1FilesByIdResponse, DeleteApiV1FilesByIdResponses, DeleteApiV1GenerationsByIdData, DeleteApiV1GenerationsByIdError, DeleteApiV1GenerationsByIdErrors, DeleteApiV1GenerationsByIdResponse, DeleteApiV1GenerationsByIdResponses, DeleteApiV1GoalsByIdData, DeleteApiV1GoalsByIdError, DeleteApiV1GoalsByIdErrors, DeleteApiV1GoalsByIdResponse, DeleteApiV1GoalsByIdResponses, DeleteApiV1KnowledgeBasesByIdData, DeleteApiV1KnowledgeBasesByIdError, DeleteApiV1KnowledgeBasesByIdErrors, DeleteApiV1KnowledgeBasesByIdFilesBatchData, DeleteApiV1KnowledgeBasesByIdFilesBatchError, DeleteApiV1KnowledgeBasesByIdFilesBatchErrors, DeleteApiV1KnowledgeBasesByIdFilesBatchResponse, DeleteApiV1KnowledgeBasesByIdFilesBatchResponses, DeleteApiV1KnowledgeBasesByIdResponse, DeleteApiV1KnowledgeBasesByIdResponses, DeleteApiV1McpServersByIdData, DeleteApiV1McpServersByIdError, DeleteApiV1McpServersByIdErrors, DeleteApiV1McpServersByIdResponse, DeleteApiV1McpServersByIdResponses, DeleteApiV1MemoriesByCategoryByIdData, DeleteApiV1MemoriesByCategoryByIdError, DeleteApiV1MemoriesByCategoryByIdErrors, DeleteApiV1MemoriesByCategoryByIdResponse, DeleteApiV1MemoriesByCategoryByIdResponses, DeleteApiV1MemoriesData, DeleteApiV1MemoriesError, DeleteApiV1MemoriesErrors, DeleteApiV1MemoriesResponse, DeleteApiV1MemoriesResponses, DeleteApiV1MessagesByIdData, DeleteApiV1MessagesByIdError, DeleteApiV1MessagesByIdErrors, DeleteApiV1MessagesByIdResponse, DeleteApiV1MessagesByIdResponses, DeleteApiV1MessagesData, DeleteApiV1MessagesError, DeleteApiV1MessagesErrors, DeleteApiV1MessagesResponse, DeleteApiV1MessagesResponses, DeleteApiV1MessageTranslationsByMessageIdData, DeleteApiV1MessageTranslationsByMessageIdError, DeleteApiV1MessageTranslationsByMessageIdErrors, DeleteApiV1MessageTranslationsByMessageIdResponse, DeleteApiV1MessageTranslationsByMessageIdResponses, DeleteApiV1PermissionsByIdData, DeleteApiV1PermissionsByIdError, DeleteApiV1PermissionsByIdErrors, DeleteApiV1PermissionsByIdResponse, DeleteApiV1PermissionsByIdResponses, DeleteApiV1ProvidersByIdData, DeleteApiV1ProvidersByIdError, DeleteApiV1ProvidersByIdErrors, DeleteApiV1ProvidersByIdResponse, DeleteApiV1ProvidersByIdResponses, DeleteApiV1PushTokensByDeviceIdData, DeleteApiV1PushTokensByDeviceIdError, DeleteApiV1PushTokensByDeviceIdErrors, DeleteApiV1PushTokensByDeviceIdResponse, DeleteApiV1PushTokensByDeviceIdResponses, DeleteApiV1RolesByIdData, DeleteApiV1RolesByIdError, DeleteApiV1RolesByIdErrors, DeleteApiV1RolesByIdPermissionsData, DeleteApiV1RolesByIdPermissionsError, DeleteApiV1RolesByIdPermissionsErrors, DeleteApiV1RolesByIdPermissionsResponse, DeleteApiV1RolesByIdPermissionsResponses, DeleteApiV1RolesByIdResponse, DeleteApiV1RolesByIdResponses, DeleteApiV1TasksByIdData, DeleteApiV1TasksByIdError, DeleteApiV1TasksByIdErrors, DeleteApiV1TasksByIdResponse, DeleteApiV1TasksByIdResponses, DeleteApiV1TopicsByIdData, DeleteApiV1TopicsByIdError, DeleteApiV1TopicsByIdErrors, DeleteApiV1TopicsByIdResponse, DeleteApiV1TopicsByIdResponses, DeleteApiV1UsersByIdData, DeleteApiV1UsersByIdError, DeleteApiV1UsersByIdErrors, DeleteApiV1UsersByIdResponse, DeleteApiV1UsersByIdResponses, DeleteApiV1UsersByIdRolesData, DeleteApiV1UsersByIdRolesError, DeleteApiV1UsersByIdRolesErrors, DeleteApiV1UsersByIdRolesResponse, DeleteApiV1UsersByIdRolesResponses, DeletedResource, DeletedResources, Document, DocumentSummary, EvalBatchReportResult, EvalBenchmark, EvalBenchmarkRubric, EvalCaseResult, EvalDataset, EvalReportReceipt, EvalReportResult, EvalRetryErrors, EvalRubricScore, EvalRun, EvalRunMetrics, EvalRunResult, EvalRunTopic, EvalStoredResult, EvalTestCase, EvalThreadResult, File, FileAsyncTask, FileChunkStatus, FileChunkTask, FileDetail, FileKnowledgeBaseRef, FileList, FileListItem, FileParseResult, FileUrl, FileUser, Generation, GenerationAsset, GenerationError, GetApiV1AgentGroupsByIdData, GetApiV1AgentGroupsByIdError, GetApiV1AgentGroupsByIdErrors, GetApiV1AgentGroupsByIdResponse, GetApiV1AgentGroupsByIdResponses, GetApiV1AgentGroupsData, GetApiV1AgentGroupsError, GetApiV1AgentGroupsErrors, GetApiV1AgentGroupsResponse, GetApiV1AgentGroupsResponses, GetApiV1AgentsByIdAccountsByAccountIdData, GetApiV1AgentsByIdAccountsByAccountIdError, GetApiV1AgentsByIdAccountsByAccountIdErrors, GetApiV1AgentsByIdAccountsByAccountIdResponse, GetApiV1AgentsByIdAccountsByAccountIdResponses, GetApiV1AgentsByIdAccountsData, GetApiV1AgentsByIdAccountsError, GetApiV1AgentsByIdAccountsErrors, GetApiV1AgentsByIdAccountsResponse, GetApiV1AgentsByIdAccountsResponses, GetApiV1AgentsByIdData, GetApiV1AgentsByIdError, GetApiV1AgentsByIdErrors, GetApiV1AgentsByIdResponse, GetApiV1AgentsByIdResponses, GetApiV1AgentsData, GetApiV1AgentsError, GetApiV1AgentsErrors, GetApiV1AgentsResponse, GetApiV1AgentsResponses, GetApiV1ApiKeysByIdData, GetApiV1ApiKeysByIdError, GetApiV1ApiKeysByIdErrors, GetApiV1ApiKeysByIdResponse, GetApiV1ApiKeysByIdResponses, GetApiV1ApiKeysData, GetApiV1ApiKeysError, GetApiV1ApiKeysErrors, GetApiV1ApiKeysResponse, GetApiV1ApiKeysResponses, GetApiV1ChatGroupsByIdData, GetApiV1ChatGroupsByIdError, GetApiV1ChatGroupsByIdErrors, GetApiV1ChatGroupsByIdResponse, GetApiV1ChatGroupsByIdResponses, GetApiV1ChatGroupsData, GetApiV1ChatGroupsError, GetApiV1ChatGroupsErrors, GetApiV1ChatGroupsResponse, GetApiV1ChatGroupsResponses, GetApiV1DocumentsByIdData, GetApiV1DocumentsByIdError, GetApiV1DocumentsByIdErrors, GetApiV1DocumentsByIdResponse, GetApiV1DocumentsByIdResponses, GetApiV1DocumentsData, GetApiV1DocumentsError, GetApiV1DocumentsErrors, GetApiV1DocumentsResponse, GetApiV1DocumentsResponses, GetApiV1EvalBenchmarksByIdData, GetApiV1EvalBenchmarksByIdError, GetApiV1EvalBenchmarksByIdErrors, GetApiV1EvalBenchmarksByIdResponse, GetApiV1EvalBenchmarksByIdResponses, GetApiV1EvalBenchmarksData, GetApiV1EvalBenchmarksError, GetApiV1EvalBenchmarksErrors, GetApiV1EvalBenchmarksResponse, GetApiV1EvalBenchmarksResponses, GetApiV1EvalDatasetsByDatasetIdTestCasesData, GetApiV1EvalDatasetsByDatasetIdTestCasesError, GetApiV1EvalDatasetsByDatasetIdTestCasesErrors, GetApiV1EvalDatasetsByDatasetIdTestCasesResponse, GetApiV1EvalDatasetsByDatasetIdTestCasesResponses, GetApiV1EvalDatasetsByIdData, GetApiV1EvalDatasetsByIdError, GetApiV1EvalDatasetsByIdErrors, GetApiV1EvalDatasetsByIdResponse, GetApiV1EvalDatasetsByIdResponses, GetApiV1EvalDatasetsData, GetApiV1EvalDatasetsError, GetApiV1EvalDatasetsErrors, GetApiV1EvalDatasetsResponse, GetApiV1EvalDatasetsResponses, GetApiV1EvalRunsByIdData, GetApiV1EvalRunsByIdError, GetApiV1EvalRunsByIdErrors, GetApiV1EvalRunsByIdResponse, GetApiV1EvalRunsByIdResponses, GetApiV1EvalRunsByIdResultsData, GetApiV1EvalRunsByIdResultsError, GetApiV1EvalRunsByIdResultsErrors, GetApiV1EvalRunsByIdResultsResponse, GetApiV1EvalRunsByIdResultsResponses, GetApiV1EvalRunsByIdTopicsData, GetApiV1EvalRunsByIdTopicsError, GetApiV1EvalRunsByIdTopicsErrors, GetApiV1EvalRunsByIdTopicsResponse, GetApiV1EvalRunsByIdTopicsResponses, GetApiV1EvalRunsData, GetApiV1EvalRunsError, GetApiV1EvalRunsErrors, GetApiV1EvalRunsResponse, GetApiV1EvalRunsResponses, GetApiV1EvalTestCasesByIdData, GetApiV1EvalTestCasesByIdError, GetApiV1EvalTestCasesByIdErrors, GetApiV1EvalTestCasesByIdResponse, GetApiV1EvalTestCasesByIdResponses, GetApiV1FilesByIdChunksData, GetApiV1FilesByIdChunksError, GetApiV1FilesByIdChunksErrors, GetApiV1FilesByIdChunksResponse, GetApiV1FilesByIdChunksResponses, GetApiV1FilesByIdData, GetApiV1FilesByIdError, GetApiV1FilesByIdErrors, GetApiV1FilesByIdResponse, GetApiV1FilesByIdResponses, GetApiV1FilesByIdUrlData, GetApiV1FilesByIdUrlError, GetApiV1FilesByIdUrlErrors, GetApiV1FilesByIdUrlResponse, GetApiV1FilesByIdUrlResponses, GetApiV1FilesData, GetApiV1FilesError, GetApiV1FilesErrors, GetApiV1FilesResponse, GetApiV1FilesResponses, GetApiV1GenerationsByIdData, GetApiV1GenerationsByIdError, GetApiV1GenerationsByIdErrors, GetApiV1GenerationsByIdResponse, GetApiV1GenerationsByIdResponses, GetApiV1GenerationsData, GetApiV1GenerationsError, GetApiV1GenerationsErrors, GetApiV1GenerationsResponse, GetApiV1GenerationsResponses, GetApiV1GoalsByIdData, GetApiV1GoalsByIdError, GetApiV1GoalsByIdErrors, GetApiV1GoalsByIdResponse, GetApiV1GoalsByIdResponses, GetApiV1GoalsByIdSupervisionData, GetApiV1GoalsByIdSupervisionError, GetApiV1GoalsByIdSupervisionErrors, GetApiV1GoalsByIdSupervisionResponse, GetApiV1GoalsByIdSupervisionResponses, GetApiV1GoalsData, GetApiV1GoalsError, GetApiV1GoalsErrors, GetApiV1GoalsResponse, GetApiV1GoalsResponses, GetApiV1HealthData, GetApiV1HealthResponse, GetApiV1HealthResponses, GetApiV1ImTopicsByTopicIdSyncData, GetApiV1ImTopicsByTopicIdSyncError, GetApiV1ImTopicsByTopicIdSyncErrors, GetApiV1ImTopicsByTopicIdSyncResponse, GetApiV1ImTopicsByTopicIdSyncResponses, GetApiV1KnowledgeBasesByIdData, GetApiV1KnowledgeBasesByIdError, GetApiV1KnowledgeBasesByIdErrors, GetApiV1KnowledgeBasesByIdFilesData, GetApiV1KnowledgeBasesByIdFilesError, GetApiV1KnowledgeBasesByIdFilesErrors, GetApiV1KnowledgeBasesByIdFilesResponse, GetApiV1KnowledgeBasesByIdFilesResponses, GetApiV1KnowledgeBasesByIdResponse, GetApiV1KnowledgeBasesByIdResponses, GetApiV1KnowledgeBasesData, GetApiV1KnowledgeBasesError, GetApiV1KnowledgeBasesErrors, GetApiV1KnowledgeBasesResponse, GetApiV1KnowledgeBasesResponses, GetApiV1McpServersByIdData, GetApiV1McpServersByIdError, GetApiV1McpServersByIdErrors, GetApiV1McpServersByIdResponse, GetApiV1McpServersByIdResponses, GetApiV1McpServersData, GetApiV1McpServersError, GetApiV1McpServersErrors, GetApiV1McpServersResponse, GetApiV1McpServersResponses, GetApiV1MemoriesByCategoryData, GetApiV1MemoriesByCategoryError, GetApiV1MemoriesByCategoryErrors, GetApiV1MemoriesByCategoryResponse, GetApiV1MemoriesByCategoryResponses, GetApiV1MemoriesPersonaData, GetApiV1MemoriesPersonaError, GetApiV1MemoriesPersonaErrors, GetApiV1MemoriesPersonaResponse, GetApiV1MemoriesPersonaResponses, GetApiV1MemoriesPersonaVersionsData, GetApiV1MemoriesPersonaVersionsError, GetApiV1MemoriesPersonaVersionsErrors, GetApiV1MemoriesPersonaVersionsResponse, GetApiV1MemoriesPersonaVersionsResponses, GetApiV1MessagesByIdData, GetApiV1MessagesByIdError, GetApiV1MessagesByIdErrors, GetApiV1MessagesByIdResponse, GetApiV1MessagesByIdResponses, GetApiV1MessagesCountData, GetApiV1MessagesCountError, GetApiV1MessagesCountErrors, GetApiV1MessagesCountResponse, GetApiV1MessagesCountResponses, GetApiV1MessagesData, GetApiV1MessagesError, GetApiV1MessagesErrors, GetApiV1MessagesResponse, GetApiV1MessagesResponses, GetApiV1MessageTranslationsByMessageIdData, GetApiV1MessageTranslationsByMessageIdError, GetApiV1MessageTranslationsByMessageIdErrors, GetApiV1MessageTranslationsByMessageIdResponse, GetApiV1MessageTranslationsByMessageIdResponses, GetApiV1ModelsByProviderIdByModelIdData, GetApiV1ModelsByProviderIdByModelIdError, GetApiV1ModelsByProviderIdByModelIdErrors, GetApiV1ModelsByProviderIdByModelIdResponse, GetApiV1ModelsByProviderIdByModelIdResponses, GetApiV1ModelsData, GetApiV1ModelsError, GetApiV1ModelsErrors, GetApiV1ModelsResponse, GetApiV1ModelsResponses, GetApiV1NotificationsCountsData, GetApiV1NotificationsCountsError, GetApiV1NotificationsCountsErrors, GetApiV1NotificationsCountsResponse, GetApiV1NotificationsCountsResponses, GetApiV1NotificationsData, GetApiV1NotificationsError, GetApiV1NotificationsErrors, GetApiV1NotificationsResponse, GetApiV1NotificationsResponses, GetApiV1NotificationsSettingsData, GetApiV1NotificationsSettingsError, GetApiV1NotificationsSettingsErrors, GetApiV1NotificationsSettingsResponse, GetApiV1NotificationsSettingsResponses, GetApiV1NotificationsUnreadCountData, GetApiV1NotificationsUnreadCountError, GetApiV1NotificationsUnreadCountErrors, GetApiV1NotificationsUnreadCountResponse, GetApiV1NotificationsUnreadCountResponses, GetApiV1PermissionsByIdData, GetApiV1PermissionsByIdError, GetApiV1PermissionsByIdErrors, GetApiV1PermissionsByIdResponse, GetApiV1PermissionsByIdResponses, GetApiV1PermissionsData, GetApiV1PermissionsError, GetApiV1PermissionsErrors, GetApiV1PermissionsResponse, GetApiV1PermissionsResponses, GetApiV1PluginsData, GetApiV1PluginsError, GetApiV1PluginsErrors, GetApiV1PluginsResponse, GetApiV1PluginsResponses, GetApiV1ProvidersByIdData, GetApiV1ProvidersByIdError, GetApiV1ProvidersByIdErrors, GetApiV1ProvidersByIdResponse, GetApiV1ProvidersByIdResponses, GetApiV1ProvidersData, GetApiV1ProvidersError, GetApiV1ProvidersErrors, GetApiV1ProvidersResponse, GetApiV1ProvidersResponses, GetApiV1RolesByIdData, GetApiV1RolesByIdError, GetApiV1RolesByIdErrors, GetApiV1RolesByIdPermissionsData, GetApiV1RolesByIdPermissionsError, GetApiV1RolesByIdPermissionsErrors, GetApiV1RolesByIdPermissionsResponse, GetApiV1RolesByIdPermissionsResponses, GetApiV1RolesByIdResponse, GetApiV1RolesByIdResponses, GetApiV1RolesData, GetApiV1RolesError, GetApiV1RolesErrors, GetApiV1RolesResponse, GetApiV1RolesResponses, GetApiV1SignalsReceiptsData, GetApiV1SignalsReceiptsError, GetApiV1SignalsReceiptsErrors, GetApiV1SignalsReceiptsResponse, GetApiV1SignalsReceiptsResponses, GetApiV1TasksByIdData, GetApiV1TasksByIdError, GetApiV1TasksByIdErrors, GetApiV1TasksByIdResponse, GetApiV1TasksByIdResponses, GetApiV1TasksByIdRunsData, GetApiV1TasksByIdRunsError, GetApiV1TasksByIdRunsErrors, GetApiV1TasksByIdRunsResponse, GetApiV1TasksByIdRunsResponses, GetApiV1TasksData, GetApiV1TasksError, GetApiV1TasksErrors, GetApiV1TasksResponse, GetApiV1TasksResponses, GetApiV1TopicsByIdData, GetApiV1TopicsByIdError, GetApiV1TopicsByIdErrors, GetApiV1TopicsByIdResponse, GetApiV1TopicsByIdResponses, GetApiV1TopicsByTopicIdThreadsData, GetApiV1TopicsByTopicIdThreadsError, GetApiV1TopicsByTopicIdThreadsErrors, GetApiV1TopicsByTopicIdThreadsResponse, GetApiV1TopicsByTopicIdThreadsResponses, GetApiV1TopicsData, GetApiV1TopicsError, GetApiV1TopicsErrors, GetApiV1TopicsResponse, GetApiV1TopicsResponses, GetApiV1UsageData, GetApiV1UsageError, GetApiV1UsageErrors, GetApiV1UsageResponse, GetApiV1UsageResponses, GetApiV1UsersByIdData, GetApiV1UsersByIdError, GetApiV1UsersByIdErrors, GetApiV1UsersByIdResponse, GetApiV1UsersByIdResponses, GetApiV1UsersByIdRolesData, GetApiV1UsersByIdRolesError, GetApiV1UsersByIdRolesErrors, GetApiV1UsersByIdRolesResponse, GetApiV1UsersByIdRolesResponses, GetApiV1UsersData, GetApiV1UsersError, GetApiV1UsersErrors, GetApiV1UsersMeData, GetApiV1UsersMeError, GetApiV1UsersMeErrors, GetApiV1UsersMeResponse, GetApiV1UsersMeResponses, GetApiV1UsersResponse, GetApiV1UsersResponses, Goal, GoalAdvanceResult, GoalDecisionOption, GoalGraph, GoalGraphDecision, GoalGraphEdge, GoalGraphEvent, GoalGraphNode, GoalGraphSnapshot, GoalGraphWorkVersionLink, GoalList, GoalListItem, GoalRestartResult, GoalSupervision, IdempotencyKey, ImMessage, ImReadResult, ImSendResult, ImSyncResult, InstalledPlugin, InstalledPluginList, KnowledgeBase, KnowledgeBaseDetail, KnowledgeBaseFileOperationResult, KnowledgeBaseList, KnowledgeBaseListItem, McpServer, McpServerSyncResult, McpServerTool, MemoryActivity, MemoryCategoryEntries, MemoryContext, MemoryExperience, MemoryIdentity, MemoryPersona, MemoryPersonaVersion, MemoryPreference, Message, MessageTranslation, MessageTranslationWrite, Model, Notification, NotificationCategoryCount, NotificationSettings, NotificationUnreadCount, PageHasMore, PageNextCursor, PageTotal, PatchApiV1AgentGroupsByIdData, PatchApiV1AgentGroupsByIdError, PatchApiV1AgentGroupsByIdErrors, PatchApiV1AgentGroupsByIdResponse, PatchApiV1AgentGroupsByIdResponses, PatchApiV1AgentsByIdAccountsByAccountIdData, PatchApiV1AgentsByIdAccountsByAccountIdError, PatchApiV1AgentsByIdAccountsByAccountIdErrors, PatchApiV1AgentsByIdAccountsByAccountIdResponse, PatchApiV1AgentsByIdAccountsByAccountIdResponses, PatchApiV1AgentsByIdData, PatchApiV1AgentsByIdError, PatchApiV1AgentsByIdErrors, PatchApiV1AgentsByIdResponse, PatchApiV1AgentsByIdResponses, PatchApiV1ApiKeysByIdData, PatchApiV1ApiKeysByIdError, PatchApiV1ApiKeysByIdErrors, PatchApiV1ApiKeysByIdResponse, PatchApiV1ApiKeysByIdResponses, PatchApiV1ChatGroupsByIdData, PatchApiV1ChatGroupsByIdError, PatchApiV1ChatGroupsByIdErrors, PatchApiV1ChatGroupsByIdResponse, PatchApiV1ChatGroupsByIdResponses, PatchApiV1DocumentsByIdData, PatchApiV1DocumentsByIdError, PatchApiV1DocumentsByIdErrors, PatchApiV1DocumentsByIdResponse, PatchApiV1DocumentsByIdResponses, PatchApiV1EvalBenchmarksByIdData, PatchApiV1EvalBenchmarksByIdError, PatchApiV1EvalBenchmarksByIdErrors, PatchApiV1EvalBenchmarksByIdResponse, PatchApiV1EvalBenchmarksByIdResponses, PatchApiV1EvalDatasetsByIdData, PatchApiV1EvalDatasetsByIdError, PatchApiV1EvalDatasetsByIdErrors, PatchApiV1EvalDatasetsByIdResponse, PatchApiV1EvalDatasetsByIdResponses, PatchApiV1EvalRunsByIdStatusData, PatchApiV1EvalRunsByIdStatusError, PatchApiV1EvalRunsByIdStatusErrors, PatchApiV1EvalRunsByIdStatusResponse, PatchApiV1EvalRunsByIdStatusResponses, PatchApiV1EvalTestCasesByIdData, PatchApiV1EvalTestCasesByIdError, PatchApiV1EvalTestCasesByIdErrors, PatchApiV1EvalTestCasesByIdResponse, PatchApiV1EvalTestCasesByIdResponses, PatchApiV1FilesByIdData, PatchApiV1FilesByIdError, PatchApiV1FilesByIdErrors, PatchApiV1FilesByIdResponse, PatchApiV1FilesByIdResponses, PatchApiV1GoalsByIdData, PatchApiV1GoalsByIdError, PatchApiV1GoalsByIdErrors, PatchApiV1GoalsByIdResponse, PatchApiV1GoalsByIdResponses, PatchApiV1KnowledgeBasesByIdData, PatchApiV1KnowledgeBasesByIdError, PatchApiV1KnowledgeBasesByIdErrors, PatchApiV1KnowledgeBasesByIdResponse, PatchApiV1KnowledgeBasesByIdResponses, PatchApiV1McpServersByIdData, PatchApiV1McpServersByIdError, PatchApiV1McpServersByIdErrors, PatchApiV1McpServersByIdResponse, PatchApiV1McpServersByIdResponses, PatchApiV1MessageTranslationsByMessageIdData, PatchApiV1MessageTranslationsByMessageIdError, PatchApiV1MessageTranslationsByMessageIdErrors, PatchApiV1MessageTranslationsByMessageIdResponse, PatchApiV1MessageTranslationsByMessageIdResponses, PatchApiV1ModelsByProviderIdByModelIdData, PatchApiV1ModelsByProviderIdByModelIdError, PatchApiV1ModelsByProviderIdByModelIdErrors, PatchApiV1ModelsByProviderIdByModelIdResponse, PatchApiV1ModelsByProviderIdByModelIdResponses, PatchApiV1NotificationsSettingsData, PatchApiV1NotificationsSettingsError, PatchApiV1NotificationsSettingsErrors, PatchApiV1NotificationsSettingsResponse, PatchApiV1NotificationsSettingsResponses, PatchApiV1PermissionsByIdData, PatchApiV1PermissionsByIdError, PatchApiV1PermissionsByIdErrors, PatchApiV1PermissionsByIdResponse, PatchApiV1PermissionsByIdResponses, PatchApiV1ProvidersByIdData, PatchApiV1ProvidersByIdError, PatchApiV1ProvidersByIdErrors, PatchApiV1ProvidersByIdResponse, PatchApiV1ProvidersByIdResponses, PatchApiV1RolesByIdData, PatchApiV1RolesByIdError, PatchApiV1RolesByIdErrors, PatchApiV1RolesByIdPermissionsData, PatchApiV1RolesByIdPermissionsError, PatchApiV1RolesByIdPermissionsErrors, PatchApiV1RolesByIdPermissionsResponse, PatchApiV1RolesByIdPermissionsResponses, PatchApiV1RolesByIdResponse, PatchApiV1RolesByIdResponses, PatchApiV1TasksByIdData, PatchApiV1TasksByIdError, PatchApiV1TasksByIdErrors, PatchApiV1TasksByIdResponse, PatchApiV1TasksByIdResponses, PatchApiV1TasksByIdStatusData, PatchApiV1TasksByIdStatusError, PatchApiV1TasksByIdStatusErrors, PatchApiV1TasksByIdStatusResponse, PatchApiV1TasksByIdStatusResponses, PatchApiV1TopicsByIdData, PatchApiV1TopicsByIdError, PatchApiV1TopicsByIdErrors, PatchApiV1TopicsByIdResponse, PatchApiV1TopicsByIdResponses, PatchApiV1UsersByIdData, PatchApiV1UsersByIdError, PatchApiV1UsersByIdErrors, PatchApiV1UsersByIdResponse, PatchApiV1UsersByIdResponses, PatchApiV1UsersByIdRolesData, PatchApiV1UsersByIdRolesError, PatchApiV1UsersByIdRolesErrors, PatchApiV1UsersByIdRolesResponse, PatchApiV1UsersByIdRolesResponses, Permission, PermissionList, PostApiV1AgentGroupsData, PostApiV1AgentGroupsError, PostApiV1AgentGroupsErrors, PostApiV1AgentGroupsResponse, PostApiV1AgentGroupsResponses, PostApiV1AgentsByIdAccountsData, PostApiV1AgentsByIdAccountsError, PostApiV1AgentsByIdAccountsErrors, PostApiV1AgentsByIdAccountsResponse, PostApiV1AgentsByIdAccountsResponses, PostApiV1AgentsByIdDuplicateData, PostApiV1AgentsByIdDuplicateError, PostApiV1AgentsByIdDuplicateErrors, PostApiV1AgentsByIdDuplicateResponse, PostApiV1AgentsByIdDuplicateResponses, PostApiV1AgentsData, PostApiV1AgentsError, PostApiV1AgentsErrors, PostApiV1AgentsResponse, PostApiV1AgentsResponses, PostApiV1ApiKeysData, PostApiV1ApiKeysError, PostApiV1ApiKeysErrors, PostApiV1ApiKeysResponse, PostApiV1ApiKeysResponses, PostApiV1AudioSpeechData, PostApiV1AudioSpeechError, PostApiV1AudioSpeechErrors, PostApiV1AudioSpeechResponse, PostApiV1AudioSpeechResponses, PostApiV1AudioTranscriptionsData, PostApiV1AudioTranscriptionsError, PostApiV1AudioTranscriptionsErrors, PostApiV1AudioTranscriptionsResponse, PostApiV1AudioTranscriptionsResponses, PostApiV1ChatData, PostApiV1ChatError, PostApiV1ChatErrors, PostApiV1ChatGenerateReplyData, PostApiV1ChatGenerateReplyError, PostApiV1ChatGenerateReplyErrors, PostApiV1ChatGenerateReplyResponse, PostApiV1ChatGenerateReplyResponses, PostApiV1ChatGroupsByIdMembersData, PostApiV1ChatGroupsByIdMembersError, PostApiV1ChatGroupsByIdMembersErrors, PostApiV1ChatGroupsByIdMembersResponse, PostApiV1ChatGroupsByIdMembersResponses, PostApiV1ChatGroupsData, PostApiV1ChatGroupsError, PostApiV1ChatGroupsErrors, PostApiV1ChatGroupsResponse, PostApiV1ChatGroupsResponses, PostApiV1ChatResponse, PostApiV1ChatResponses, PostApiV1ChatTranslateData, PostApiV1ChatTranslateError, PostApiV1ChatTranslateErrors, PostApiV1ChatTranslateResponse, PostApiV1ChatTranslateResponses, PostApiV1DocumentsData, PostApiV1DocumentsError, PostApiV1DocumentsErrors, PostApiV1DocumentsResponse, PostApiV1DocumentsResponses, PostApiV1EvalBenchmarksData, PostApiV1EvalBenchmarksError, PostApiV1EvalBenchmarksErrors, PostApiV1EvalBenchmarksResponse, PostApiV1EvalBenchmarksResponses, PostApiV1EvalDatasetsByDatasetIdTestCasesData, PostApiV1EvalDatasetsByDatasetIdTestCasesError, PostApiV1EvalDatasetsByDatasetIdTestCasesErrors, PostApiV1EvalDatasetsByDatasetIdTestCasesResponse, PostApiV1EvalDatasetsByDatasetIdTestCasesResponses, PostApiV1EvalDatasetsData, PostApiV1EvalDatasetsError, PostApiV1EvalDatasetsErrors, PostApiV1EvalDatasetsResponse, PostApiV1EvalDatasetsResponses, PostApiV1EvalRunsByIdClaimData, PostApiV1EvalRunsByIdClaimError, PostApiV1EvalRunsByIdClaimErrors, PostApiV1EvalRunsByIdClaimResponse, PostApiV1EvalRunsByIdClaimResponses, PostApiV1EvalRunsByIdResultsData, PostApiV1EvalRunsByIdResultsError, PostApiV1EvalRunsByIdResultsErrors, PostApiV1EvalRunsByIdResultsResponse, PostApiV1EvalRunsByIdResultsResponses, PostApiV1EvalRunsByIdRetryErrorsData, PostApiV1EvalRunsByIdRetryErrorsError, PostApiV1EvalRunsByIdRetryErrorsErrors, PostApiV1EvalRunsByIdRetryErrorsResponse, PostApiV1EvalRunsByIdRetryErrorsResponses, PostApiV1EvalRunsData, PostApiV1EvalRunsError, PostApiV1EvalRunsErrors, PostApiV1EvalRunsResponse, PostApiV1EvalRunsResponses, PostApiV1FilesBatchesData, PostApiV1FilesBatchesError, PostApiV1FilesBatchesErrors, PostApiV1FilesBatchesResponse, PostApiV1FilesBatchesResponses, PostApiV1FilesByIdChunksData, PostApiV1FilesByIdChunksError, PostApiV1FilesByIdChunksErrors, PostApiV1FilesByIdChunksResponse, PostApiV1FilesByIdChunksResponses, PostApiV1FilesByIdParsesData, PostApiV1FilesByIdParsesError, PostApiV1FilesByIdParsesErrors, PostApiV1FilesByIdParsesResponse, PostApiV1FilesByIdParsesResponses, PostApiV1FilesData, PostApiV1FilesError, PostApiV1FilesErrors, PostApiV1FilesQueriesData, PostApiV1FilesQueriesError, PostApiV1FilesQueriesErrors, PostApiV1FilesQueriesResponse, PostApiV1FilesQueriesResponses, PostApiV1FilesResponse, PostApiV1FilesResponses, PostApiV1GoalsByIdAdvanceData, PostApiV1GoalsByIdAdvanceError, PostApiV1GoalsByIdAdvanceErrors, PostApiV1GoalsByIdAdvanceResponse, PostApiV1GoalsByIdAdvanceResponses, PostApiV1GoalsByIdPauseData, PostApiV1GoalsByIdPauseError, PostApiV1GoalsByIdPauseErrors, PostApiV1GoalsByIdPauseResponse, PostApiV1GoalsByIdPauseResponses, PostApiV1GoalsByIdRestartData, PostApiV1GoalsByIdRestartError, PostApiV1GoalsByIdRestartErrors, PostApiV1GoalsByIdRestartResponse, PostApiV1GoalsByIdRestartResponses, PostApiV1GoalsByIdResumeData, PostApiV1GoalsByIdResumeError, PostApiV1GoalsByIdResumeErrors, PostApiV1GoalsByIdResumeResponse, PostApiV1GoalsByIdResumeResponses, PostApiV1GoalsData, PostApiV1GoalsError, PostApiV1GoalsErrors, PostApiV1GoalsResponse, PostApiV1GoalsResponses, PostApiV1ImagesGenerationsData, PostApiV1ImagesGenerationsError, PostApiV1ImagesGenerationsErrors, PostApiV1ImagesGenerationsResponse, PostApiV1ImagesGenerationsResponses, PostApiV1ImMessagesData, PostApiV1ImMessagesError, PostApiV1ImMessagesErrors, PostApiV1ImMessagesResponse, PostApiV1ImMessagesResponses, PostApiV1ImTopicsByTopicIdReadData, PostApiV1ImTopicsByTopicIdReadError, PostApiV1ImTopicsByTopicIdReadErrors, PostApiV1ImTopicsByTopicIdReadResponse, PostApiV1ImTopicsByTopicIdReadResponses, PostApiV1KnowledgeBasesByIdFilesBatchData, PostApiV1KnowledgeBasesByIdFilesBatchError, PostApiV1KnowledgeBasesByIdFilesBatchErrors, PostApiV1KnowledgeBasesByIdFilesBatchResponse, PostApiV1KnowledgeBasesByIdFilesBatchResponses, PostApiV1KnowledgeBasesByIdFilesMoveData, PostApiV1KnowledgeBasesByIdFilesMoveError, PostApiV1KnowledgeBasesByIdFilesMoveErrors, PostApiV1KnowledgeBasesByIdFilesMoveResponse, PostApiV1KnowledgeBasesByIdFilesMoveResponses, PostApiV1KnowledgeBasesData, PostApiV1KnowledgeBasesError, PostApiV1KnowledgeBasesErrors, PostApiV1KnowledgeBasesResponse, PostApiV1KnowledgeBasesResponses, PostApiV1McpServersByIdSyncData, PostApiV1McpServersByIdSyncError, PostApiV1McpServersByIdSyncErrors, PostApiV1McpServersByIdSyncResponse, PostApiV1McpServersByIdSyncResponses, PostApiV1McpServersData, PostApiV1McpServersError, PostApiV1McpServersErrors, PostApiV1McpServersResponse, PostApiV1McpServersResponses, PostApiV1MessagesData, PostApiV1MessagesError, PostApiV1MessagesErrors, PostApiV1MessagesRepliesData, PostApiV1MessagesRepliesError, PostApiV1MessagesRepliesErrors, PostApiV1MessagesRepliesResponse, PostApiV1MessagesRepliesResponses, PostApiV1MessagesResponse, PostApiV1MessagesResponses, PostApiV1MessageTranslationsByMessageIdData, PostApiV1MessageTranslationsByMessageIdError, PostApiV1MessageTranslationsByMessageIdErrors, PostApiV1MessageTranslationsByMessageIdResponse, PostApiV1MessageTranslationsByMessageIdResponses, PostApiV1ModelsData, PostApiV1ModelsError, PostApiV1ModelsErrors, PostApiV1ModelsResponse, PostApiV1ModelsResponses, PostApiV1NotificationsArchiveAllData, PostApiV1NotificationsArchiveAllError, PostApiV1NotificationsArchiveAllErrors, PostApiV1NotificationsArchiveAllResponse, PostApiV1NotificationsArchiveAllResponses, PostApiV1NotificationsByIdArchiveData, PostApiV1NotificationsByIdArchiveError, PostApiV1NotificationsByIdArchiveErrors, PostApiV1NotificationsByIdArchiveResponse, PostApiV1NotificationsByIdArchiveResponses, PostApiV1NotificationsReadAllData, PostApiV1NotificationsReadAllError, PostApiV1NotificationsReadAllErrors, PostApiV1NotificationsReadAllResponse, PostApiV1NotificationsReadAllResponses, PostApiV1NotificationsReadData, PostApiV1NotificationsReadError, PostApiV1NotificationsReadErrors, PostApiV1NotificationsReadResponse, PostApiV1NotificationsReadResponses, PostApiV1ObjectsGenerationsData, PostApiV1ObjectsGenerationsError, PostApiV1ObjectsGenerationsErrors, PostApiV1ObjectsGenerationsResponse, PostApiV1ObjectsGenerationsResponses, PostApiV1PermissionsData, PostApiV1PermissionsError, PostApiV1PermissionsErrors, PostApiV1PermissionsResponse, PostApiV1PermissionsResponses, PostApiV1ProvidersData, PostApiV1ProvidersError, PostApiV1ProvidersErrors, PostApiV1ProvidersResponse, PostApiV1ProvidersResponses, PostApiV1ResponsesData, PostApiV1ResponsesError, PostApiV1ResponsesErrors, PostApiV1ResponsesResponse, PostApiV1ResponsesResponses, PostApiV1RolesData, PostApiV1RolesError, PostApiV1RolesErrors, PostApiV1RolesResponse, PostApiV1RolesResponses, PostApiV1SignalsSourceEventsData, PostApiV1SignalsSourceEventsError, PostApiV1SignalsSourceEventsErrors, PostApiV1SignalsSourceEventsResponse, PostApiV1SignalsSourceEventsResponses, PostApiV1SignalsTriggerData, PostApiV1SignalsTriggerError, PostApiV1SignalsTriggerErrors, PostApiV1SignalsTriggerResponse, PostApiV1SignalsTriggerResponses, PostApiV1TasksByIdRunsData, PostApiV1TasksByIdRunsError, PostApiV1TasksByIdRunsErrors, PostApiV1TasksByIdRunsResponse, PostApiV1TasksByIdRunsResponses, PostApiV1TasksData, PostApiV1TasksError, PostApiV1TasksErrors, PostApiV1TasksResponse, PostApiV1TasksResponses, PostApiV1TextGenerationsData, PostApiV1TextGenerationsError, PostApiV1TextGenerationsErrors, PostApiV1TextGenerationsResponse, PostApiV1TextGenerationsResponses, PostApiV1TopicsData, PostApiV1TopicsError, PostApiV1TopicsErrors, PostApiV1TopicsResponse, PostApiV1TopicsResponses, PostApiV1UsersData, PostApiV1UsersError, PostApiV1UsersErrors, PostApiV1UsersResponse, PostApiV1UsersResponses, PostApiV1VideosGenerationsData, PostApiV1VideosGenerationsError, PostApiV1VideosGenerationsErrors, PostApiV1VideosGenerationsResponse, PostApiV1VideosGenerationsResponses, Provider, PushTokenRegistration, PutApiV1AgentsByIdAccountsByAccountIdCredentialData, PutApiV1AgentsByIdAccountsByAccountIdCredentialError, PutApiV1AgentsByIdAccountsByAccountIdCredentialErrors, PutApiV1AgentsByIdAccountsByAccountIdCredentialResponse, PutApiV1AgentsByIdAccountsByAccountIdCredentialResponses, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultData, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultError, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultErrors, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultResponse, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultResponses, PutApiV1PushTokensByDeviceIdData, PutApiV1PushTokensByDeviceIdError, PutApiV1PushTokensByDeviceIdErrors, PutApiV1PushTokensByDeviceIdResponse, PutApiV1PushTokensByDeviceIdResponses, ResponseCompletedEvent, ResponseContentPartAddedEvent, ResponseContentPartDoneEvent, ResponseCreatedEvent, ResponseError, ResponseFailedEvent, ResponseFunctionCall, ResponseFunctionCallArgumentsDeltaEvent, ResponseFunctionCallArgumentsDoneEvent, ResponseFunctionCallOutput, ResponseIncompleteEvent, ResponseInProgressEvent, ResponseObject, ResponseOutputItem, ResponseOutputItemAddedEvent, ResponseOutputItemDoneEvent, ResponseOutputMessage, ResponseOutputText, ResponseOutputTextDeltaEvent, ResponseOutputTextDoneEvent, ResponseStreamEvent, ResponseUsage, Role, RoleList, RolePermission, RolePermissionList, RolePermissionsUpdateResult, Task, TaskDetail, TaskDetailActivity, TaskDetailSubtask, TaskDetailWorkspaceNode, TaskLabelRef, TaskList, TaskListItem, TaskRun, TaskRunStarted, TaskStatusUpdateResult, Topic, TopicSummary, TopicThread, Transcription, Usage, User, UserIdentity, UserList, UserRole, WorkspaceId } from './types.gen';diff --git a/packages/sdk/src/generated/sdk.gen.ts b/packages/sdk/src/generated/sdk.gen.tsindex 55779aeaf76..cdf30d3fda2 100644--- a/packages/sdk/src/generated/sdk.gen.ts+++ b/packages/sdk/src/generated/sdk.gen.ts@@ -2,7 +2,7 @@import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client';import { client } from './client.gen';-import type { DeleteApiV1AgentGroupsByIdData, DeleteApiV1AgentGroupsByIdErrors, DeleteApiV1AgentGroupsByIdResponses, DeleteApiV1AgentsByIdAccountsByAccountIdData, DeleteApiV1AgentsByIdAccountsByAccountIdErrors, DeleteApiV1AgentsByIdAccountsByAccountIdResponses, DeleteApiV1AgentsByIdData, DeleteApiV1AgentsByIdErrors, DeleteApiV1AgentsByIdResponses, DeleteApiV1ApiKeysByIdData, DeleteApiV1ApiKeysByIdErrors, DeleteApiV1ApiKeysByIdResponses, DeleteApiV1ChatGroupsByIdData, DeleteApiV1ChatGroupsByIdErrors, DeleteApiV1ChatGroupsByIdMembersData, DeleteApiV1ChatGroupsByIdMembersErrors, DeleteApiV1ChatGroupsByIdMembersResponses, DeleteApiV1ChatGroupsByIdResponses, DeleteApiV1EvalBenchmarksByIdData, DeleteApiV1EvalBenchmarksByIdErrors, DeleteApiV1EvalBenchmarksByIdResponses, DeleteApiV1EvalDatasetsByIdData, DeleteApiV1EvalDatasetsByIdErrors, DeleteApiV1EvalDatasetsByIdResponses, DeleteApiV1EvalTestCasesByIdData, DeleteApiV1EvalTestCasesByIdErrors, DeleteApiV1EvalTestCasesByIdResponses, DeleteApiV1FilesByIdData, DeleteApiV1FilesByIdErrors, DeleteApiV1FilesByIdResponses, DeleteApiV1GoalsByIdData, DeleteApiV1GoalsByIdErrors, DeleteApiV1GoalsByIdResponses, DeleteApiV1KnowledgeBasesByIdData, DeleteApiV1KnowledgeBasesByIdErrors, DeleteApiV1KnowledgeBasesByIdFilesBatchData, DeleteApiV1KnowledgeBasesByIdFilesBatchErrors, DeleteApiV1KnowledgeBasesByIdFilesBatchResponses, DeleteApiV1KnowledgeBasesByIdResponses, DeleteApiV1McpServersByIdData, DeleteApiV1McpServersByIdErrors, DeleteApiV1McpServersByIdResponses, DeleteApiV1MemoriesByCategoryByIdData, DeleteApiV1MemoriesByCategoryByIdErrors, DeleteApiV1MemoriesByCategoryByIdResponses, DeleteApiV1MemoriesData, DeleteApiV1MemoriesErrors, DeleteApiV1MemoriesResponses, DeleteApiV1MessagesByIdData, DeleteApiV1MessagesByIdErrors, DeleteApiV1MessagesByIdResponses, DeleteApiV1MessagesData, DeleteApiV1MessagesErrors, DeleteApiV1MessagesResponses, DeleteApiV1MessageTranslationsByMessageIdData, DeleteApiV1MessageTranslationsByMessageIdErrors, DeleteApiV1MessageTranslationsByMessageIdResponses, DeleteApiV1PermissionsByIdData, DeleteApiV1PermissionsByIdErrors, DeleteApiV1PermissionsByIdResponses, DeleteApiV1ProvidersByIdData, DeleteApiV1ProvidersByIdErrors, DeleteApiV1ProvidersByIdResponses, DeleteApiV1PushTokensByDeviceIdData, DeleteApiV1PushTokensByDeviceIdErrors, DeleteApiV1PushTokensByDeviceIdResponses, DeleteApiV1RolesByIdData, DeleteApiV1RolesByIdErrors, DeleteApiV1RolesByIdPermissionsData, DeleteApiV1RolesByIdPermissionsErrors, DeleteApiV1RolesByIdPermissionsResponses, DeleteApiV1RolesByIdResponses, DeleteApiV1TasksByIdData, DeleteApiV1TasksByIdErrors, DeleteApiV1TasksByIdResponses, DeleteApiV1TopicsByIdData, DeleteApiV1TopicsByIdErrors, DeleteApiV1TopicsByIdResponses, DeleteApiV1UsersByIdData, DeleteApiV1UsersByIdErrors, DeleteApiV1UsersByIdResponses, DeleteApiV1UsersByIdRolesData, DeleteApiV1UsersByIdRolesErrors, DeleteApiV1UsersByIdRolesResponses, GetApiV1AgentGroupsByIdData, GetApiV1AgentGroupsByIdErrors, GetApiV1AgentGroupsByIdResponses, GetApiV1AgentGroupsData, GetApiV1AgentGroupsErrors, GetApiV1AgentGroupsResponses, GetApiV1AgentsByIdAccountsByAccountIdData, GetApiV1AgentsByIdAccountsByAccountIdErrors, GetApiV1AgentsByIdAccountsByAccountIdResponses, GetApiV1AgentsByIdAccountsData, GetApiV1AgentsByIdAccountsErrors, GetApiV1AgentsByIdAccountsResponses, GetApiV1AgentsByIdData, GetApiV1AgentsByIdErrors, GetApiV1AgentsByIdResponses, GetApiV1AgentsData, GetApiV1AgentsErrors, GetApiV1AgentsResponses, GetApiV1ApiKeysByIdData, GetApiV1ApiKeysByIdErrors, GetApiV1ApiKeysByIdResponses, GetApiV1ApiKeysData, GetApiV1ApiKeysErrors, GetApiV1ApiKeysResponses, GetApiV1ChatGroupsByIdData, GetApiV1ChatGroupsByIdErrors, GetApiV1ChatGroupsByIdResponses, GetApiV1ChatGroupsData, GetApiV1ChatGroupsErrors, GetApiV1ChatGroupsResponses, GetApiV1DocumentsByIdData, GetApiV1DocumentsByIdErrors, GetApiV1DocumentsByIdResponses, GetApiV1DocumentsData, GetApiV1DocumentsErrors, GetApiV1DocumentsResponses, GetApiV1EvalBenchmarksByIdData, GetApiV1EvalBenchmarksByIdErrors, GetApiV1EvalBenchmarksByIdResponses, GetApiV1EvalBenchmarksData, GetApiV1EvalBenchmarksErrors, GetApiV1EvalBenchmarksResponses, GetApiV1EvalDatasetsByDatasetIdTestCasesData, GetApiV1EvalDatasetsByDatasetIdTestCasesErrors, GetApiV1EvalDatasetsByDatasetIdTestCasesResponses, GetApiV1EvalDatasetsByIdData, GetApiV1EvalDatasetsByIdErrors, GetApiV1EvalDatasetsByIdResponses, GetApiV1EvalDatasetsData, GetApiV1EvalDatasetsErrors, GetApiV1EvalDatasetsResponses, GetApiV1EvalRunsByIdData, GetApiV1EvalRunsByIdErrors, GetApiV1EvalRunsByIdResponses, GetApiV1EvalRunsByIdResultsData, GetApiV1EvalRunsByIdResultsErrors, GetApiV1EvalRunsByIdResultsResponses, GetApiV1EvalRunsByIdTopicsData, GetApiV1EvalRunsByIdTopicsErrors, GetApiV1EvalRunsByIdTopicsResponses, GetApiV1EvalRunsData, GetApiV1EvalRunsErrors, GetApiV1EvalRunsResponses, GetApiV1EvalTestCasesByIdData, GetApiV1EvalTestCasesByIdErrors, GetApiV1EvalTestCasesByIdResponses, GetApiV1FilesByIdChunksData, GetApiV1FilesByIdChunksErrors, GetApiV1FilesByIdChunksResponses, GetApiV1FilesByIdData, GetApiV1FilesByIdErrors, GetApiV1FilesByIdResponses, GetApiV1FilesByIdUrlData, GetApiV1FilesByIdUrlErrors, GetApiV1FilesByIdUrlResponses, GetApiV1FilesData, GetApiV1FilesErrors, GetApiV1FilesResponses, GetApiV1GoalsByIdData, GetApiV1GoalsByIdErrors, GetApiV1GoalsByIdResponses, GetApiV1GoalsByIdSupervisionData, GetApiV1GoalsByIdSupervisionErrors, GetApiV1GoalsByIdSupervisionResponses, GetApiV1GoalsData, GetApiV1GoalsErrors, GetApiV1GoalsResponses, GetApiV1HealthData, GetApiV1HealthResponses, GetApiV1ImTopicsByTopicIdSyncData, GetApiV1ImTopicsByTopicIdSyncErrors, GetApiV1ImTopicsByTopicIdSyncResponses, GetApiV1KnowledgeBasesByIdData, GetApiV1KnowledgeBasesByIdErrors, GetApiV1KnowledgeBasesByIdFilesData, GetApiV1KnowledgeBasesByIdFilesErrors, GetApiV1KnowledgeBasesByIdFilesResponses, GetApiV1KnowledgeBasesByIdResponses, GetApiV1KnowledgeBasesData, GetApiV1KnowledgeBasesErrors, GetApiV1KnowledgeBasesResponses, GetApiV1McpServersByIdData, GetApiV1McpServersByIdErrors, GetApiV1McpServersByIdResponses, GetApiV1McpServersData, GetApiV1McpServersErrors, GetApiV1McpServersResponses, GetApiV1MemoriesByCategoryData, GetApiV1MemoriesByCategoryErrors, GetApiV1MemoriesByCategoryResponses, GetApiV1MemoriesPersonaData, GetApiV1MemoriesPersonaErrors, GetApiV1MemoriesPersonaResponses, GetApiV1MemoriesPersonaVersionsData, GetApiV1MemoriesPersonaVersionsErrors, GetApiV1MemoriesPersonaVersionsResponses, GetApiV1MessagesByIdData, GetApiV1MessagesByIdErrors, GetApiV1MessagesByIdResponses, GetApiV1MessagesCountData, GetApiV1MessagesCountErrors, GetApiV1MessagesCountResponses, GetApiV1MessagesData, GetApiV1MessagesErrors, GetApiV1MessagesResponses, GetApiV1MessageTranslationsByMessageIdData, GetApiV1MessageTranslationsByMessageIdErrors, GetApiV1MessageTranslationsByMessageIdResponses, GetApiV1ModelsByProviderIdByModelIdData, GetApiV1ModelsByProviderIdByModelIdErrors, GetApiV1ModelsByProviderIdByModelIdResponses, GetApiV1ModelsData, GetApiV1ModelsErrors, GetApiV1ModelsResponses, GetApiV1NotificationsCountsData, GetApiV1NotificationsCountsErrors, GetApiV1NotificationsCountsResponses, GetApiV1NotificationsData, GetApiV1NotificationsErrors, GetApiV1NotificationsResponses, GetApiV1NotificationsSettingsData, GetApiV1NotificationsSettingsErrors, GetApiV1NotificationsSettingsResponses, GetApiV1NotificationsUnreadCountData, GetApiV1NotificationsUnreadCountErrors, GetApiV1NotificationsUnreadCountResponses, GetApiV1PermissionsByIdData, GetApiV1PermissionsByIdErrors, GetApiV1PermissionsByIdResponses, GetApiV1PermissionsData, GetApiV1PermissionsErrors, GetApiV1PermissionsResponses, GetApiV1PluginsData, GetApiV1PluginsErrors, GetApiV1PluginsResponses, GetApiV1ProvidersByIdData, GetApiV1ProvidersByIdErrors, GetApiV1ProvidersByIdResponses, GetApiV1ProvidersData, GetApiV1ProvidersErrors, GetApiV1ProvidersResponses, GetApiV1RolesByIdData, GetApiV1RolesByIdErrors, GetApiV1RolesByIdPermissionsData, GetApiV1RolesByIdPermissionsErrors, GetApiV1RolesByIdPermissionsResponses, GetApiV1RolesByIdResponses, GetApiV1RolesData, GetApiV1RolesErrors, GetApiV1RolesResponses, GetApiV1SignalsReceiptsData, GetApiV1SignalsReceiptsErrors, GetApiV1SignalsReceiptsResponses, GetApiV1TasksByIdData, GetApiV1TasksByIdErrors, GetApiV1TasksByIdResponses, GetApiV1TasksByIdRunsData, GetApiV1TasksByIdRunsErrors, GetApiV1TasksByIdRunsResponses, GetApiV1TasksData, GetApiV1TasksErrors, GetApiV1TasksResponses, GetApiV1TopicsByIdData, GetApiV1TopicsByIdErrors, GetApiV1TopicsByIdResponses, GetApiV1TopicsByTopicIdThreadsData, GetApiV1TopicsByTopicIdThreadsErrors, GetApiV1TopicsByTopicIdThreadsResponses, GetApiV1TopicsData, GetApiV1TopicsErrors, GetApiV1TopicsResponses, GetApiV1UsageData, GetApiV1UsageErrors, GetApiV1UsageResponses, GetApiV1UsersByIdData, GetApiV1UsersByIdErrors, GetApiV1UsersByIdResponses, GetApiV1UsersByIdRolesData, GetApiV1UsersByIdRolesErrors, GetApiV1UsersByIdRolesResponses, GetApiV1UsersData, GetApiV1UsersErrors, GetApiV1UsersMeData, GetApiV1UsersMeErrors, GetApiV1UsersMeResponses, GetApiV1UsersResponses, PatchApiV1AgentGroupsByIdData, PatchApiV1AgentGroupsByIdErrors, PatchApiV1AgentGroupsByIdResponses, PatchApiV1AgentsByIdAccountsByAccountIdData, PatchApiV1AgentsByIdAccountsByAccountIdErrors, PatchApiV1AgentsByIdAccountsByAccountIdResponses, PatchApiV1AgentsByIdData, PatchApiV1AgentsByIdErrors, PatchApiV1AgentsByIdResponses, PatchApiV1ApiKeysByIdData, PatchApiV1ApiKeysByIdErrors, PatchApiV1ApiKeysByIdResponses, PatchApiV1ChatGroupsByIdData, PatchApiV1ChatGroupsByIdErrors, PatchApiV1ChatGroupsByIdResponses, PatchApiV1DocumentsByIdData, PatchApiV1DocumentsByIdErrors, PatchApiV1DocumentsByIdResponses, PatchApiV1EvalBenchmarksByIdData, PatchApiV1EvalBenchmarksByIdErrors, PatchApiV1EvalBenchmarksByIdResponses, PatchApiV1EvalDatasetsByIdData, PatchApiV1EvalDatasetsByIdErrors, PatchApiV1EvalDatasetsByIdResponses, PatchApiV1EvalRunsByIdStatusData, PatchApiV1EvalRunsByIdStatusErrors, PatchApiV1EvalRunsByIdStatusResponses, PatchApiV1EvalTestCasesByIdData, PatchApiV1EvalTestCasesByIdErrors, PatchApiV1EvalTestCasesByIdResponses, PatchApiV1FilesByIdData, PatchApiV1FilesByIdErrors, PatchApiV1FilesByIdResponses, PatchApiV1GoalsByIdData, PatchApiV1GoalsByIdErrors, PatchApiV1GoalsByIdResponses, PatchApiV1KnowledgeBasesByIdData, PatchApiV1KnowledgeBasesByIdErrors, PatchApiV1KnowledgeBasesByIdResponses, PatchApiV1McpServersByIdData, PatchApiV1McpServersByIdErrors, PatchApiV1McpServersByIdResponses, PatchApiV1MessageTranslationsByMessageIdData, PatchApiV1MessageTranslationsByMessageIdErrors, PatchApiV1MessageTranslationsByMessageIdResponses, PatchApiV1ModelsByProviderIdByModelIdData, PatchApiV1ModelsByProviderIdByModelIdErrors, PatchApiV1ModelsByProviderIdByModelIdResponses, PatchApiV1NotificationsSettingsData, PatchApiV1NotificationsSettingsErrors, PatchApiV1NotificationsSettingsResponses, PatchApiV1PermissionsByIdData, PatchApiV1PermissionsByIdErrors, PatchApiV1PermissionsByIdResponses, PatchApiV1ProvidersByIdData, PatchApiV1ProvidersByIdErrors, PatchApiV1ProvidersByIdResponses, PatchApiV1RolesByIdData, PatchApiV1RolesByIdErrors, PatchApiV1RolesByIdPermissionsData, PatchApiV1RolesByIdPermissionsErrors, PatchApiV1RolesByIdPermissionsResponses, PatchApiV1RolesByIdResponses, PatchApiV1TasksByIdData, PatchApiV1TasksByIdErrors, PatchApiV1TasksByIdResponses, PatchApiV1TasksByIdStatusData, PatchApiV1TasksByIdStatusErrors, PatchApiV1TasksByIdStatusResponses, PatchApiV1TopicsByIdData, PatchApiV1TopicsByIdErrors, PatchApiV1TopicsByIdResponses, PatchApiV1UsersByIdData, PatchApiV1UsersByIdErrors, PatchApiV1UsersByIdResponses, PatchApiV1UsersByIdRolesData, PatchApiV1UsersByIdRolesErrors, PatchApiV1UsersByIdRolesResponses, PostApiV1AgentGroupsData, PostApiV1AgentGroupsErrors, PostApiV1AgentGroupsResponses, PostApiV1AgentsByIdAccountsData, PostApiV1AgentsByIdAccountsErrors, PostApiV1AgentsByIdAccountsResponses, PostApiV1AgentsByIdDuplicateData, PostApiV1AgentsByIdDuplicateErrors, PostApiV1AgentsByIdDuplicateResponses, PostApiV1AgentsData, PostApiV1AgentsErrors, PostApiV1AgentsResponses, PostApiV1ApiKeysData, PostApiV1ApiKeysErrors, PostApiV1ApiKeysResponses, PostApiV1AudioSpeechData, PostApiV1AudioSpeechErrors, PostApiV1AudioSpeechResponses, PostApiV1ChatData, PostApiV1ChatErrors, PostApiV1ChatGenerateReplyData, PostApiV1ChatGenerateReplyErrors, PostApiV1ChatGenerateReplyResponses, PostApiV1ChatGroupsByIdMembersData, PostApiV1ChatGroupsByIdMembersErrors, PostApiV1ChatGroupsByIdMembersResponses, PostApiV1ChatGroupsData, PostApiV1ChatGroupsErrors, PostApiV1ChatGroupsResponses, PostApiV1ChatResponses, PostApiV1ChatTranslateData, PostApiV1ChatTranslateErrors, PostApiV1ChatTranslateResponses, PostApiV1DocumentsData, PostApiV1DocumentsErrors, PostApiV1DocumentsResponses, PostApiV1EvalBenchmarksData, PostApiV1EvalBenchmarksErrors, PostApiV1EvalBenchmarksResponses, PostApiV1EvalDatasetsByDatasetIdTestCasesData, PostApiV1EvalDatasetsByDatasetIdTestCasesErrors, PostApiV1EvalDatasetsByDatasetIdTestCasesResponses, PostApiV1EvalDatasetsData, PostApiV1EvalDatasetsErrors, PostApiV1EvalDatasetsResponses, PostApiV1EvalRunsByIdClaimData, PostApiV1EvalRunsByIdClaimErrors, PostApiV1EvalRunsByIdClaimResponses, PostApiV1EvalRunsByIdResultsData, PostApiV1EvalRunsByIdResultsErrors, PostApiV1EvalRunsByIdResultsResponses, PostApiV1EvalRunsByIdRetryErrorsData, PostApiV1EvalRunsByIdRetryErrorsErrors, PostApiV1EvalRunsByIdRetryErrorsResponses, PostApiV1EvalRunsData, PostApiV1EvalRunsErrors, PostApiV1EvalRunsResponses, PostApiV1FilesBatchesData, PostApiV1FilesBatchesErrors, PostApiV1FilesBatchesResponses, PostApiV1FilesByIdChunksData, PostApiV1FilesByIdChunksErrors, PostApiV1FilesByIdChunksResponses, PostApiV1FilesByIdParsesData, PostApiV1FilesByIdParsesErrors, PostApiV1FilesByIdParsesResponses, PostApiV1FilesData, PostApiV1FilesErrors, PostApiV1FilesQueriesData, PostApiV1FilesQueriesErrors, PostApiV1FilesQueriesResponses, PostApiV1FilesResponses, PostApiV1GoalsByIdAdvanceData, PostApiV1GoalsByIdAdvanceErrors, PostApiV1GoalsByIdAdvanceResponses, PostApiV1GoalsByIdPauseData, PostApiV1GoalsByIdPauseErrors, PostApiV1GoalsByIdPauseResponses, PostApiV1GoalsByIdRestartData, PostApiV1GoalsByIdRestartErrors, PostApiV1GoalsByIdRestartResponses, PostApiV1GoalsByIdResumeData, PostApiV1GoalsByIdResumeErrors, PostApiV1GoalsByIdResumeResponses, PostApiV1GoalsData, PostApiV1GoalsErrors, PostApiV1GoalsResponses, PostApiV1ImMessagesData, PostApiV1ImMessagesErrors, PostApiV1ImMessagesResponses, PostApiV1ImTopicsByTopicIdReadData, PostApiV1ImTopicsByTopicIdReadErrors, PostApiV1ImTopicsByTopicIdReadResponses, PostApiV1KnowledgeBasesByIdFilesBatchData, PostApiV1KnowledgeBasesByIdFilesBatchErrors, PostApiV1KnowledgeBasesByIdFilesBatchResponses, PostApiV1KnowledgeBasesByIdFilesMoveData, PostApiV1KnowledgeBasesByIdFilesMoveErrors, PostApiV1KnowledgeBasesByIdFilesMoveResponses, PostApiV1KnowledgeBasesData, PostApiV1KnowledgeBasesErrors, PostApiV1KnowledgeBasesResponses, PostApiV1McpServersByIdSyncData, PostApiV1McpServersByIdSyncErrors, PostApiV1McpServersByIdSyncResponses, PostApiV1McpServersData, PostApiV1McpServersErrors, PostApiV1McpServersResponses, PostApiV1MessagesData, PostApiV1MessagesErrors, PostApiV1MessagesRepliesData, PostApiV1MessagesRepliesErrors, PostApiV1MessagesRepliesResponses, PostApiV1MessagesResponses, PostApiV1MessageTranslationsByMessageIdData, PostApiV1MessageTranslationsByMessageIdErrors, PostApiV1MessageTranslationsByMessageIdResponses, PostApiV1ModelsData, PostApiV1ModelsErrors, PostApiV1ModelsResponses, PostApiV1NotificationsArchiveAllData, PostApiV1NotificationsArchiveAllErrors, PostApiV1NotificationsArchiveAllResponses, PostApiV1NotificationsByIdArchiveData, PostApiV1NotificationsByIdArchiveErrors, PostApiV1NotificationsByIdArchiveResponses, PostApiV1NotificationsReadAllData, PostApiV1NotificationsReadAllErrors, PostApiV1NotificationsReadAllResponses, PostApiV1NotificationsReadData, PostApiV1NotificationsReadErrors, PostApiV1NotificationsReadResponses, PostApiV1PermissionsData, PostApiV1PermissionsErrors, PostApiV1PermissionsResponses, PostApiV1ProvidersData, PostApiV1ProvidersErrors, PostApiV1ProvidersResponses, PostApiV1ResponsesData, PostApiV1ResponsesErrors, PostApiV1ResponsesResponses, PostApiV1RolesData, PostApiV1RolesErrors, PostApiV1RolesResponses, PostApiV1SignalsSourceEventsData, PostApiV1SignalsSourceEventsErrors, PostApiV1SignalsSourceEventsResponses, PostApiV1SignalsTriggerData, PostApiV1SignalsTriggerErrors, PostApiV1SignalsTriggerResponses, PostApiV1TasksByIdRunsData, PostApiV1TasksByIdRunsErrors, PostApiV1TasksByIdRunsResponses, PostApiV1TasksData, PostApiV1TasksErrors, PostApiV1TasksResponses, PostApiV1TopicsData, PostApiV1TopicsErrors, PostApiV1TopicsResponses, PostApiV1UsersData, PostApiV1UsersErrors, PostApiV1UsersResponses, PutApiV1AgentsByIdAccountsByAccountIdCredentialData, PutApiV1AgentsByIdAccountsByAccountIdCredentialErrors, PutApiV1AgentsByIdAccountsByAccountIdCredentialResponses, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultData, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultErrors, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultResponses, PutApiV1PushTokensByDeviceIdData, PutApiV1PushTokensByDeviceIdErrors, PutApiV1PushTokensByDeviceIdResponses } from './types.gen';+import type { DeleteApiV1AgentGroupsByIdData, DeleteApiV1AgentGroupsByIdErrors, DeleteApiV1AgentGroupsByIdResponses, DeleteApiV1AgentsByIdAccountsByAccountIdData, DeleteApiV1AgentsByIdAccountsByAccountIdErrors, DeleteApiV1AgentsByIdAccountsByAccountIdResponses, DeleteApiV1AgentsByIdData, DeleteApiV1AgentsByIdErrors, DeleteApiV1AgentsByIdResponses, DeleteApiV1ApiKeysByIdData, DeleteApiV1ApiKeysByIdErrors, DeleteApiV1ApiKeysByIdResponses, DeleteApiV1ChatGroupsByIdData, DeleteApiV1ChatGroupsByIdErrors, DeleteApiV1ChatGroupsByIdMembersData, DeleteApiV1ChatGroupsByIdMembersErrors, DeleteApiV1ChatGroupsByIdMembersResponses, DeleteApiV1ChatGroupsByIdResponses, DeleteApiV1EvalBenchmarksByIdData, DeleteApiV1EvalBenchmarksByIdErrors, DeleteApiV1EvalBenchmarksByIdResponses, DeleteApiV1EvalDatasetsByIdData, DeleteApiV1EvalDatasetsByIdErrors, DeleteApiV1EvalDatasetsByIdResponses, DeleteApiV1EvalTestCasesByIdData, DeleteApiV1EvalTestCasesByIdErrors, DeleteApiV1EvalTestCasesByIdResponses, DeleteApiV1FilesByIdData, DeleteApiV1FilesByIdErrors, DeleteApiV1FilesByIdResponses, DeleteApiV1GenerationsByIdData, DeleteApiV1GenerationsByIdErrors, DeleteApiV1GenerationsByIdResponses, DeleteApiV1GoalsByIdData, DeleteApiV1GoalsByIdErrors, DeleteApiV1GoalsByIdResponses, DeleteApiV1KnowledgeBasesByIdData, DeleteApiV1KnowledgeBasesByIdErrors, DeleteApiV1KnowledgeBasesByIdFilesBatchData, DeleteApiV1KnowledgeBasesByIdFilesBatchErrors, DeleteApiV1KnowledgeBasesByIdFilesBatchResponses, DeleteApiV1KnowledgeBasesByIdResponses, DeleteApiV1McpServersByIdData, DeleteApiV1McpServersByIdErrors, DeleteApiV1McpServersByIdResponses, DeleteApiV1MemoriesByCategoryByIdData, DeleteApiV1MemoriesByCategoryByIdErrors, DeleteApiV1MemoriesByCategoryByIdResponses, DeleteApiV1MemoriesData, DeleteApiV1MemoriesErrors, DeleteApiV1MemoriesResponses, DeleteApiV1MessagesByIdData, DeleteApiV1MessagesByIdErrors, DeleteApiV1MessagesByIdResponses, DeleteApiV1MessagesData, DeleteApiV1MessagesErrors, DeleteApiV1MessagesResponses, DeleteApiV1MessageTranslationsByMessageIdData, DeleteApiV1MessageTranslationsByMessageIdErrors, DeleteApiV1MessageTranslationsByMessageIdResponses, DeleteApiV1PermissionsByIdData, DeleteApiV1PermissionsByIdErrors, DeleteApiV1PermissionsByIdResponses, DeleteApiV1ProvidersByIdData, DeleteApiV1ProvidersByIdErrors, DeleteApiV1ProvidersByIdResponses, DeleteApiV1PushTokensByDeviceIdData, DeleteApiV1PushTokensByDeviceIdErrors, DeleteApiV1PushTokensByDeviceIdResponses, DeleteApiV1RolesByIdData, DeleteApiV1RolesByIdErrors, DeleteApiV1RolesByIdPermissionsData, DeleteApiV1RolesByIdPermissionsErrors, DeleteApiV1RolesByIdPermissionsResponses, DeleteApiV1RolesByIdResponses, DeleteApiV1TasksByIdData, DeleteApiV1TasksByIdErrors, DeleteApiV1TasksByIdResponses, DeleteApiV1TopicsByIdData, DeleteApiV1TopicsByIdErrors, DeleteApiV1TopicsByIdResponses, DeleteApiV1UsersByIdData, DeleteApiV1UsersByIdErrors, DeleteApiV1UsersByIdResponses, DeleteApiV1UsersByIdRolesData, DeleteApiV1UsersByIdRolesErrors, DeleteApiV1UsersByIdRolesResponses, GetApiV1AgentGroupsByIdData, GetApiV1AgentGroupsByIdErrors, GetApiV1AgentGroupsByIdResponses, GetApiV1AgentGroupsData, GetApiV1AgentGroupsErrors, GetApiV1AgentGroupsResponses, GetApiV1AgentsByIdAccountsByAccountIdData, GetApiV1AgentsByIdAccountsByAccountIdErrors, GetApiV1AgentsByIdAccountsByAccountIdResponses, GetApiV1AgentsByIdAccountsData, GetApiV1AgentsByIdAccountsErrors, GetApiV1AgentsByIdAccountsResponses, GetApiV1AgentsByIdData, GetApiV1AgentsByIdErrors, GetApiV1AgentsByIdResponses, GetApiV1AgentsData, GetApiV1AgentsErrors, GetApiV1AgentsResponses, GetApiV1ApiKeysByIdData, GetApiV1ApiKeysByIdErrors, GetApiV1ApiKeysByIdResponses, GetApiV1ApiKeysData, GetApiV1ApiKeysErrors, GetApiV1ApiKeysResponses, GetApiV1ChatGroupsByIdData, GetApiV1ChatGroupsByIdErrors, GetApiV1ChatGroupsByIdResponses, GetApiV1ChatGroupsData, GetApiV1ChatGroupsErrors, GetApiV1ChatGroupsResponses, GetApiV1DocumentsByIdData, GetApiV1DocumentsByIdErrors, GetApiV1DocumentsByIdResponses, GetApiV1DocumentsData, GetApiV1DocumentsErrors, GetApiV1DocumentsResponses, GetApiV1EvalBenchmarksByIdData, GetApiV1EvalBenchmarksByIdErrors, GetApiV1EvalBenchmarksByIdResponses, GetApiV1EvalBenchmarksData, GetApiV1EvalBenchmarksErrors, GetApiV1EvalBenchmarksResponses, GetApiV1EvalDatasetsByDatasetIdTestCasesData, GetApiV1EvalDatasetsByDatasetIdTestCasesErrors, GetApiV1EvalDatasetsByDatasetIdTestCasesResponses, GetApiV1EvalDatasetsByIdData, GetApiV1EvalDatasetsByIdErrors, GetApiV1EvalDatasetsByIdResponses, GetApiV1EvalDatasetsData, GetApiV1EvalDatasetsErrors, GetApiV1EvalDatasetsResponses, GetApiV1EvalRunsByIdData, GetApiV1EvalRunsByIdErrors, GetApiV1EvalRunsByIdResponses, GetApiV1EvalRunsByIdResultsData, GetApiV1EvalRunsByIdResultsErrors, GetApiV1EvalRunsByIdResultsResponses, GetApiV1EvalRunsByIdTopicsData, GetApiV1EvalRunsByIdTopicsErrors, GetApiV1EvalRunsByIdTopicsResponses, GetApiV1EvalRunsData, GetApiV1EvalRunsErrors, GetApiV1EvalRunsResponses, GetApiV1EvalTestCasesByIdData, GetApiV1EvalTestCasesByIdErrors, GetApiV1EvalTestCasesByIdResponses, GetApiV1FilesByIdChunksData, GetApiV1FilesByIdChunksErrors, GetApiV1FilesByIdChunksResponses, GetApiV1FilesByIdData, GetApiV1FilesByIdErrors, GetApiV1FilesByIdResponses, GetApiV1FilesByIdUrlData, GetApiV1FilesByIdUrlErrors, GetApiV1FilesByIdUrlResponses, GetApiV1FilesData, GetApiV1FilesErrors, GetApiV1FilesResponses, GetApiV1GenerationsByIdData, GetApiV1GenerationsByIdErrors, GetApiV1GenerationsByIdResponses, GetApiV1GenerationsData, GetApiV1GenerationsErrors, GetApiV1GenerationsResponses, GetApiV1GoalsByIdData, GetApiV1GoalsByIdErrors, GetApiV1GoalsByIdResponses, GetApiV1GoalsByIdSupervisionData, GetApiV1GoalsByIdSupervisionErrors, GetApiV1GoalsByIdSupervisionResponses, GetApiV1GoalsData, GetApiV1GoalsErrors, GetApiV1GoalsResponses, GetApiV1HealthData, GetApiV1HealthResponses, GetApiV1ImTopicsByTopicIdSyncData, GetApiV1ImTopicsByTopicIdSyncErrors, GetApiV1ImTopicsByTopicIdSyncResponses, GetApiV1KnowledgeBasesByIdData, GetApiV1KnowledgeBasesByIdErrors, GetApiV1KnowledgeBasesByIdFilesData, GetApiV1KnowledgeBasesByIdFilesErrors, GetApiV1KnowledgeBasesByIdFilesResponses, GetApiV1KnowledgeBasesByIdResponses, GetApiV1KnowledgeBasesData, GetApiV1KnowledgeBasesErrors, GetApiV1KnowledgeBasesResponses, GetApiV1McpServersByIdData, GetApiV1McpServersByIdErrors, GetApiV1McpServersByIdResponses, GetApiV1McpServersData, GetApiV1McpServersErrors, GetApiV1McpServersResponses, GetApiV1MemoriesByCategoryData, GetApiV1MemoriesByCategoryErrors, GetApiV1MemoriesByCategoryResponses, GetApiV1MemoriesPersonaData, GetApiV1MemoriesPersonaErrors, GetApiV1MemoriesPersonaResponses, GetApiV1MemoriesPersonaVersionsData, GetApiV1MemoriesPersonaVersionsErrors, GetApiV1MemoriesPersonaVersionsResponses, GetApiV1MessagesByIdData, GetApiV1MessagesByIdErrors, GetApiV1MessagesByIdResponses, GetApiV1MessagesCountData, GetApiV1MessagesCountErrors, GetApiV1MessagesCountResponses, GetApiV1MessagesData, GetApiV1MessagesErrors, GetApiV1MessagesResponses, GetApiV1MessageTranslationsByMessageIdData, GetApiV1MessageTranslationsByMessageIdErrors, GetApiV1MessageTranslationsByMessageIdResponses, GetApiV1ModelsByProviderIdByModelIdData, GetApiV1ModelsByProviderIdByModelIdErrors, GetApiV1ModelsByProviderIdByModelIdResponses, GetApiV1ModelsData, GetApiV1ModelsErrors, GetApiV1ModelsResponses, GetApiV1NotificationsCountsData, GetApiV1NotificationsCountsErrors, GetApiV1NotificationsCountsResponses, GetApiV1NotificationsData, GetApiV1NotificationsErrors, GetApiV1NotificationsResponses, GetApiV1NotificationsSettingsData, GetApiV1NotificationsSettingsErrors, GetApiV1NotificationsSettingsResponses, GetApiV1NotificationsUnreadCountData, GetApiV1NotificationsUnreadCountErrors, GetApiV1NotificationsUnreadCountResponses, GetApiV1PermissionsByIdData, GetApiV1PermissionsByIdErrors, GetApiV1PermissionsByIdResponses, GetApiV1PermissionsData, GetApiV1PermissionsErrors, GetApiV1PermissionsResponses, GetApiV1PluginsData, GetApiV1PluginsErrors, GetApiV1PluginsResponses, GetApiV1ProvidersByIdData, GetApiV1ProvidersByIdErrors, GetApiV1ProvidersByIdResponses, GetApiV1ProvidersData, GetApiV1ProvidersErrors, GetApiV1ProvidersResponses, GetApiV1RolesByIdData, GetApiV1RolesByIdErrors, GetApiV1RolesByIdPermissionsData, GetApiV1RolesByIdPermissionsErrors, GetApiV1RolesByIdPermissionsResponses, GetApiV1RolesByIdResponses, GetApiV1RolesData, GetApiV1RolesErrors, GetApiV1RolesResponses, GetApiV1SignalsReceiptsData, GetApiV1SignalsReceiptsErrors, GetApiV1SignalsReceiptsResponses, GetApiV1TasksByIdData, GetApiV1TasksByIdErrors, GetApiV1TasksByIdResponses, GetApiV1TasksByIdRunsData, GetApiV1TasksByIdRunsErrors, GetApiV1TasksByIdRunsResponses, GetApiV1TasksData, GetApiV1TasksErrors, GetApiV1TasksResponses, GetApiV1TopicsByIdData, GetApiV1TopicsByIdErrors, GetApiV1TopicsByIdResponses, GetApiV1TopicsByTopicIdThreadsData, GetApiV1TopicsByTopicIdThreadsErrors, GetApiV1TopicsByTopicIdThreadsResponses, GetApiV1TopicsData, GetApiV1TopicsErrors, GetApiV1TopicsResponses, GetApiV1UsageData, GetApiV1UsageErrors, GetApiV1UsageResponses, GetApiV1UsersByIdData, GetApiV1UsersByIdErrors, GetApiV1UsersByIdResponses, GetApiV1UsersByIdRolesData, GetApiV1UsersByIdRolesErrors, GetApiV1UsersByIdRolesResponses, GetApiV1UsersData, GetApiV1UsersErrors, GetApiV1UsersMeData, GetApiV1UsersMeErrors, GetApiV1UsersMeResponses, GetApiV1UsersResponses, PatchApiV1AgentGroupsByIdData, PatchApiV1AgentGroupsByIdErrors, PatchApiV1AgentGroupsByIdResponses, PatchApiV1AgentsByIdAccountsByAccountIdData, PatchApiV1AgentsByIdAccountsByAccountIdErrors, PatchApiV1AgentsByIdAccountsByAccountIdResponses, PatchApiV1AgentsByIdData, PatchApiV1AgentsByIdErrors, PatchApiV1AgentsByIdResponses, PatchApiV1ApiKeysByIdData, PatchApiV1ApiKeysByIdErrors, PatchApiV1ApiKeysByIdResponses, PatchApiV1ChatGroupsByIdData, PatchApiV1ChatGroupsByIdErrors, PatchApiV1ChatGroupsByIdResponses, PatchApiV1DocumentsByIdData, PatchApiV1DocumentsByIdErrors, PatchApiV1DocumentsByIdResponses, PatchApiV1EvalBenchmarksByIdData, PatchApiV1EvalBenchmarksByIdErrors, PatchApiV1EvalBenchmarksByIdResponses, PatchApiV1EvalDatasetsByIdData, PatchApiV1EvalDatasetsByIdErrors, PatchApiV1EvalDatasetsByIdResponses, PatchApiV1EvalRunsByIdStatusData, PatchApiV1EvalRunsByIdStatusErrors, PatchApiV1EvalRunsByIdStatusResponses, PatchApiV1EvalTestCasesByIdData, PatchApiV1EvalTestCasesByIdErrors, PatchApiV1EvalTestCasesByIdResponses, PatchApiV1FilesByIdData, PatchApiV1FilesByIdErrors, PatchApiV1FilesByIdResponses, PatchApiV1GoalsByIdData, PatchApiV1GoalsByIdErrors, PatchApiV1GoalsByIdResponses, PatchApiV1KnowledgeBasesByIdData, PatchApiV1KnowledgeBasesByIdErrors, PatchApiV1KnowledgeBasesByIdResponses, PatchApiV1McpServersByIdData, PatchApiV1McpServersByIdErrors, PatchApiV1McpServersByIdResponses, PatchApiV1MessageTranslationsByMessageIdData, PatchApiV1MessageTranslationsByMessageIdErrors, PatchApiV1MessageTranslationsByMessageIdResponses, PatchApiV1ModelsByProviderIdByModelIdData, PatchApiV1ModelsByProviderIdByModelIdErrors, PatchApiV1ModelsByProviderIdByModelIdResponses, PatchApiV1NotificationsSettingsData, PatchApiV1NotificationsSettingsErrors, PatchApiV1NotificationsSettingsResponses, PatchApiV1PermissionsByIdData, PatchApiV1PermissionsByIdErrors, PatchApiV1PermissionsByIdResponses, PatchApiV1ProvidersByIdData, PatchApiV1ProvidersByIdErrors, PatchApiV1ProvidersByIdResponses, PatchApiV1RolesByIdData, PatchApiV1RolesByIdErrors, PatchApiV1RolesByIdPermissionsData, PatchApiV1RolesByIdPermissionsErrors, PatchApiV1RolesByIdPermissionsResponses, PatchApiV1RolesByIdResponses, PatchApiV1TasksByIdData, PatchApiV1TasksByIdErrors, PatchApiV1TasksByIdResponses, PatchApiV1TasksByIdStatusData, PatchApiV1TasksByIdStatusErrors, PatchApiV1TasksByIdStatusResponses, PatchApiV1TopicsByIdData, PatchApiV1TopicsByIdErrors, PatchApiV1TopicsByIdResponses, PatchApiV1UsersByIdData, PatchApiV1UsersByIdErrors, PatchApiV1UsersByIdResponses, PatchApiV1UsersByIdRolesData, PatchApiV1UsersByIdRolesErrors, PatchApiV1UsersByIdRolesResponses, PostApiV1AgentGroupsData, PostApiV1AgentGroupsErrors, PostApiV1AgentGroupsResponses, PostApiV1AgentsByIdAccountsData, PostApiV1AgentsByIdAccountsErrors, PostApiV1AgentsByIdAccountsResponses, PostApiV1AgentsByIdDuplicateData, PostApiV1AgentsByIdDuplicateErrors, PostApiV1AgentsByIdDuplicateResponses, PostApiV1AgentsData, PostApiV1AgentsErrors, PostApiV1AgentsResponses, PostApiV1ApiKeysData, PostApiV1ApiKeysErrors, PostApiV1ApiKeysResponses, PostApiV1AudioSpeechData, PostApiV1AudioSpeechErrors, PostApiV1AudioSpeechResponses, PostApiV1AudioTranscriptionsData, PostApiV1AudioTranscriptionsErrors, PostApiV1AudioTranscriptionsResponses, PostApiV1ChatData, PostApiV1ChatErrors, PostApiV1ChatGenerateReplyData, PostApiV1ChatGenerateReplyErrors, PostApiV1ChatGenerateReplyResponses, PostApiV1ChatGroupsByIdMembersData, PostApiV1ChatGroupsByIdMembersErrors, PostApiV1ChatGroupsByIdMembersResponses, PostApiV1ChatGroupsData, PostApiV1ChatGroupsErrors, PostApiV1ChatGroupsResponses, PostApiV1ChatResponses, PostApiV1ChatTranslateData, PostApiV1ChatTranslateErrors, PostApiV1ChatTranslateResponses, PostApiV1DocumentsData, PostApiV1DocumentsErrors, PostApiV1DocumentsResponses, PostApiV1EvalBenchmarksData, PostApiV1EvalBenchmarksErrors, PostApiV1EvalBenchmarksResponses, PostApiV1EvalDatasetsByDatasetIdTestCasesData, PostApiV1EvalDatasetsByDatasetIdTestCasesErrors, PostApiV1EvalDatasetsByDatasetIdTestCasesResponses, PostApiV1EvalDatasetsData, PostApiV1EvalDatasetsErrors, PostApiV1EvalDatasetsResponses, PostApiV1EvalRunsByIdClaimData, PostApiV1EvalRunsByIdClaimErrors, PostApiV1EvalRunsByIdClaimResponses, PostApiV1EvalRunsByIdResultsData, PostApiV1EvalRunsByIdResultsErrors, PostApiV1EvalRunsByIdResultsResponses, PostApiV1EvalRunsByIdRetryErrorsData, PostApiV1EvalRunsByIdRetryErrorsErrors, PostApiV1EvalRunsByIdRetryErrorsResponses, PostApiV1EvalRunsData, PostApiV1EvalRunsErrors, PostApiV1EvalRunsResponses, PostApiV1FilesBatchesData, PostApiV1FilesBatchesErrors, PostApiV1FilesBatchesResponses, PostApiV1FilesByIdChunksData, PostApiV1FilesByIdChunksErrors, PostApiV1FilesByIdChunksResponses, PostApiV1FilesByIdParsesData, PostApiV1FilesByIdParsesErrors, PostApiV1FilesByIdParsesResponses, PostApiV1FilesData, PostApiV1FilesErrors, PostApiV1FilesQueriesData, PostApiV1FilesQueriesErrors, PostApiV1FilesQueriesResponses, PostApiV1FilesResponses, PostApiV1GoalsByIdAdvanceData, PostApiV1GoalsByIdAdvanceErrors, PostApiV1GoalsByIdAdvanceResponses, PostApiV1GoalsByIdPauseData, PostApiV1GoalsByIdPauseErrors, PostApiV1GoalsByIdPauseResponses, PostApiV1GoalsByIdRestartData, PostApiV1GoalsByIdRestartErrors, PostApiV1GoalsByIdRestartResponses, PostApiV1GoalsByIdResumeData, PostApiV1GoalsByIdResumeErrors, PostApiV1GoalsByIdResumeResponses, PostApiV1GoalsData, PostApiV1GoalsErrors, PostApiV1GoalsResponses, PostApiV1ImagesGenerationsData, PostApiV1ImagesGenerationsErrors, PostApiV1ImagesGenerationsResponses, PostApiV1ImMessagesData, PostApiV1ImMessagesErrors, PostApiV1ImMessagesResponses, PostApiV1ImTopicsByTopicIdReadData, PostApiV1ImTopicsByTopicIdReadErrors, PostApiV1ImTopicsByTopicIdReadResponses, PostApiV1KnowledgeBasesByIdFilesBatchData, PostApiV1KnowledgeBasesByIdFilesBatchErrors, PostApiV1KnowledgeBasesByIdFilesBatchResponses, PostApiV1KnowledgeBasesByIdFilesMoveData, PostApiV1KnowledgeBasesByIdFilesMoveErrors, PostApiV1KnowledgeBasesByIdFilesMoveResponses, PostApiV1KnowledgeBasesData, PostApiV1KnowledgeBasesErrors, PostApiV1KnowledgeBasesResponses, PostApiV1McpServersByIdSyncData, PostApiV1McpServersByIdSyncErrors, PostApiV1McpServersByIdSyncResponses, PostApiV1McpServersData, PostApiV1McpServersErrors, PostApiV1McpServersResponses, PostApiV1MessagesData, PostApiV1MessagesErrors, PostApiV1MessagesRepliesData, PostApiV1MessagesRepliesErrors, PostApiV1MessagesRepliesResponses, PostApiV1MessagesResponses, PostApiV1MessageTranslationsByMessageIdData, PostApiV1MessageTranslationsByMessageIdErrors, PostApiV1MessageTranslationsByMessageIdResponses, PostApiV1ModelsData, PostApiV1ModelsErrors, PostApiV1ModelsResponses, PostApiV1NotificationsArchiveAllData, PostApiV1NotificationsArchiveAllErrors, PostApiV1NotificationsArchiveAllResponses, PostApiV1NotificationsByIdArchiveData, PostApiV1NotificationsByIdArchiveErrors, PostApiV1NotificationsByIdArchiveResponses, PostApiV1NotificationsReadAllData, PostApiV1NotificationsReadAllErrors, PostApiV1NotificationsReadAllResponses, PostApiV1NotificationsReadData, PostApiV1NotificationsReadErrors, PostApiV1NotificationsReadResponses, PostApiV1ObjectsGenerationsData, PostApiV1ObjectsGenerationsErrors, PostApiV1ObjectsGenerationsResponses, PostApiV1PermissionsData, PostApiV1PermissionsErrors, PostApiV1PermissionsResponses, PostApiV1ProvidersData, PostApiV1ProvidersErrors, PostApiV1ProvidersResponses, PostApiV1ResponsesData, PostApiV1ResponsesErrors, PostApiV1ResponsesResponses, PostApiV1RolesData, PostApiV1RolesErrors, PostApiV1RolesResponses, PostApiV1SignalsSourceEventsData, PostApiV1SignalsSourceEventsErrors, PostApiV1SignalsSourceEventsResponses, PostApiV1SignalsTriggerData, PostApiV1SignalsTriggerErrors, PostApiV1SignalsTriggerResponses, PostApiV1TasksByIdRunsData, PostApiV1TasksByIdRunsErrors, PostApiV1TasksByIdRunsResponses, PostApiV1TasksData, PostApiV1TasksErrors, PostApiV1TasksResponses, PostApiV1TextGenerationsData, PostApiV1TextGenerationsErrors, PostApiV1TextGenerationsResponses, PostApiV1TopicsData, PostApiV1TopicsErrors, PostApiV1TopicsResponses, PostApiV1UsersData, PostApiV1UsersErrors, PostApiV1UsersResponses, PostApiV1VideosGenerationsData, PostApiV1VideosGenerationsErrors, PostApiV1VideosGenerationsResponses, PutApiV1AgentsByIdAccountsByAccountIdCredentialData, PutApiV1AgentsByIdAccountsByAccountIdCredentialErrors, PutApiV1AgentsByIdAccountsByAccountIdCredentialResponses, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultData, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultErrors, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultResponses, PutApiV1PushTokensByDeviceIdData, PutApiV1PushTokensByDeviceIdErrors, PutApiV1PushTokensByDeviceIdResponses } from './types.gen';const mergeMethodHeaders = (defaults: Record<string, unknown>,@@ -386,15 +386,33 @@ export class Audio extends HeyApiClient {/*** Create speech*- * OpenAI-compatible text-to-speech. Point an OpenAI SDK at `/api/v1` and call `audio.speech.create`. `model` takes `provider/model` (for example `lobehub/speech-2.8-hd`) or a bare model id; the optional `provider` and `params` (emotion, pitch, volume, sampleRate) are LobeHub extensions. Returns the audio bytes; usage is reported in `X-LobeHub-*` headers. Synthesis errors use OpenAI's `{ error: { message, type, code, param } }` body; authentication and permission errors use the platform `ApiError` envelope.+ * OpenAI-compatible text-to-speech. Point an OpenAI SDK at `/api/v1` and call `audio.speech.create`. `model` takes `provider/model` (for example `lobehub/speech-2.8-hd`) or a bare model id; the optional `provider` and `params` (emotion, pitch, volume, sampleRate) are LobeHub extensions. Returns the audio bytes; usage is reported in `X-LobeHub-*` headers. API keys need the `generation:write` scope (keys issued with `model:invoke` are also accepted). Synthesis errors use OpenAI's `{ error: { message, type, code, param } }` body; authentication and permission errors use the platform `ApiError` envelope.*- * **API key scopes:** `model:invoke`.+ * **API key scopes:** `generation:write`.*/- public createSpeech<ThrowOnError extends boolean = false>(options?: Options<PostApiV1AudioSpeechData, ThrowOnError>): RequestResult<PostApiV1AudioSpeechResponses, PostApiV1AudioSpeechErrors, ThrowOnError> {- return (options?.client ?? this.client).post<PostApiV1AudioSpeechResponses, PostApiV1AudioSpeechErrors, ThrowOnError>({+ public createSpeech<ThrowOnError extends boolean = false>(options: Options<PostApiV1AudioSpeechData, ThrowOnError>): RequestResult<PostApiV1AudioSpeechResponses, PostApiV1AudioSpeechErrors, ThrowOnError> {+ return (options.client ?? this.client).post<PostApiV1AudioSpeechResponses, PostApiV1AudioSpeechErrors, ThrowOnError>({security: [{ scheme: 'bearer', type: 'http' }],url: '/api/v1/audio/speech',- ...options+ ...options,+ headers: mergeMethodHeaders({ 'Content-Type': 'application/json' }, options.headers)+ });+ }++ /**+ * Create a transcription+ *+ * OpenAI-compatible speech-to-text: upload the audio as multipart/form-data and get `{ text }` back, so an OpenAI SDK pointed at `/api/v1` can call `audio.transcriptions.create`. Send the clip as `file` (up to 3 MB), or the id of an uploaded file as `fileId` (the key then also needs `file:read`). `provider` (default `openai`) is a LobeHub extension. Billing follows the provider configuration, like the in-app voice input. The transcript is always returned as JSON `{ text }`, whatever `response_format` asks of the provider.+ *+ * **API key scopes:** `generation:write`.+ */+ public createTranscription<ThrowOnError extends boolean = false>(options: Options<PostApiV1AudioTranscriptionsData, ThrowOnError>): RequestResult<PostApiV1AudioTranscriptionsResponses, PostApiV1AudioTranscriptionsErrors, ThrowOnError> {+ return (options.client ?? this.client).post<PostApiV1AudioTranscriptionsResponses, PostApiV1AudioTranscriptionsErrors, ThrowOnError>({+ ...formDataBodySerializer,+ security: [{ scheme: 'bearer', type: 'http' }],+ url: '/api/v1/audio/transcriptions',+ ...options,+ headers: mergeMethodHeaders({ 'Content-Type': null }, options.headers)});}}@@ -2640,6 +2658,125 @@ export class Usage extends HeyApiClient {}}+export class Generations extends HeyApiClient {+ /**+ * List generations+ *+ * Lists the image, video and music generations the caller can see, newest first. Filter by `type`; page with `cursor` / `limit`.+ *+ * **API key scopes:** `generation:read`.+ */+ public list<ThrowOnError extends boolean = false>(options?: Options<GetApiV1GenerationsData, ThrowOnError>): RequestResult<GetApiV1GenerationsResponses, GetApiV1GenerationsErrors, ThrowOnError> {+ return (options?.client ?? this.client).get<GetApiV1GenerationsResponses, GetApiV1GenerationsErrors, ThrowOnError>({+ security: [{ scheme: 'bearer', type: 'http' }],+ url: '/api/v1/generations',+ ...options+ });+ }++ /**+ * Delete a generation+ *+ * Deletes a generation record and its thumbnail. The library file it was saved as is kept. In a workspace only the creator or a workspace owner may delete it.+ *+ * **API key scopes:** `generation:write`.+ */+ public delete<ThrowOnError extends boolean = false>(options: Options<DeleteApiV1GenerationsByIdData, ThrowOnError>): RequestResult<DeleteApiV1GenerationsByIdResponses, DeleteApiV1GenerationsByIdErrors, ThrowOnError> {+ return (options.client ?? this.client).delete<DeleteApiV1GenerationsByIdResponses, DeleteApiV1GenerationsByIdErrors, ThrowOnError>({+ security: [{ scheme: 'bearer', type: 'http' }],+ url: '/api/v1/generations/{id}',+ ...options+ });+ }++ /**+ * Get a generation+ *+ * Reports one generation: its `status` (`pending`, `processing`, `success` or `error`), the asset URLs once it succeeded, or the failure reason. Poll until the status is `success` or `error` — the SDK does this in `generations.wait(id)`.+ *+ * **API key scopes:** `generation:read`.+ */+ public get<ThrowOnError extends boolean = false>(options: Options<GetApiV1GenerationsByIdData, ThrowOnError>): RequestResult<GetApiV1GenerationsByIdResponses, GetApiV1GenerationsByIdErrors, ThrowOnError> {+ return (options.client ?? this.client).get<GetApiV1GenerationsByIdResponses, GetApiV1GenerationsByIdErrors, ThrowOnError>({+ security: [{ scheme: 'bearer', type: 'http' }],+ url: '/api/v1/generations/{id}',+ ...options+ });+ }+}++export class Images extends HeyApiClient {+ /**+ * Generate images+ *+ * Generates `n` images from a prompt with an image model (the account's default when `model` is omitted). Billing and quota follow the Image page. By default the request waits up to `waitTimeoutSeconds` and returns the finished images with their URLs; any still running come back with their current status — poll `GET /generations/{id}` or call `generations.wait(id)` in the SDK. With `wait: false` it answers as soon as the work is queued. Each request is added to `topicId`, or to a new generation topic. A request the plan or budget refuses (insufficient credits, plan limit) is recorded as generations that already failed: they come back with `status: 'error'` and the reason in `error`, as on the Image page.+ *+ * **API key scopes:** `generation:write`.+ */+ public generate<ThrowOnError extends boolean = false>(options: Options<PostApiV1ImagesGenerationsData, ThrowOnError>): RequestResult<PostApiV1ImagesGenerationsResponses, PostApiV1ImagesGenerationsErrors, ThrowOnError> {+ return (options.client ?? this.client).post<PostApiV1ImagesGenerationsResponses, PostApiV1ImagesGenerationsErrors, ThrowOnError>({+ security: [{ scheme: 'bearer', type: 'http' }],+ url: '/api/v1/images/generations',+ ...options,+ headers: mergeMethodHeaders({ 'Content-Type': 'application/json' }, options.headers)+ });+ }+}++export class Videos extends HeyApiClient {+ /**+ * Generate a video+ *+ * Starts a video generation and answers 202 with the generation id while it runs; videos take minutes. Poll `GET /generations/{id}` until the status is `success` or `error`, or call `generations.wait(id)` in the SDK. Billing and quota follow the Video page. Each request is added to `topicId`, or to a new generation topic. A request the plan or budget refuses (insufficient credits, plan limit) is recorded as a generation that already failed: it comes back with the status `error` and the reason in the `error` field.+ *+ * **API key scopes:** `generation:write`.+ */+ public generate<ThrowOnError extends boolean = false>(options: Options<PostApiV1VideosGenerationsData, ThrowOnError>): RequestResult<PostApiV1VideosGenerationsResponses, PostApiV1VideosGenerationsErrors, ThrowOnError> {+ return (options.client ?? this.client).post<PostApiV1VideosGenerationsResponses, PostApiV1VideosGenerationsErrors, ThrowOnError>({+ security: [{ scheme: 'bearer', type: 'http' }],+ url: '/api/v1/videos/generations',+ ...options,+ headers: mergeMethodHeaders({ 'Content-Type': 'application/json' }, options.headers)+ });+ }+}++export class Text extends HeyApiClient {+ /**+ * Generate text+ *+ * Generates text with an LLM in a single completion — no tools, nothing stored as a conversation. Pass `prompt` (and optionally `system`), or a `messages` list. `model` + `provider` pick the model; omit both for the platform's default chat model. The answer is in `text`; a reasoning model's reasoning comes back separately in `reasoning`, never spliced into `text`. Provider failures answer 502 `upstream_error` with the provider's reason; budget and quota refusals keep their own status (402 / 429).+ *+ * **API key scopes:** `generation:write`.+ */+ public generate<ThrowOnError extends boolean = false>(options: Options<PostApiV1TextGenerationsData, ThrowOnError>): RequestResult<PostApiV1TextGenerationsResponses, PostApiV1TextGenerationsErrors, ThrowOnError> {+ return (options.client ?? this.client).post<PostApiV1TextGenerationsResponses, PostApiV1TextGenerationsErrors, ThrowOnError>({+ security: [{ scheme: 'bearer', type: 'http' }],+ url: '/api/v1/text/generations',+ ...options,+ headers: mergeMethodHeaders({ 'Content-Type': 'application/json' }, options.headers)+ });+ }+}++export class Objects extends HeyApiClient {+ /**+ * Generate a JSON object+ *+ * Generates a JSON object that matches `schema` (structured output, single completion) — the same path `lh generate json` uses. The root of `schema` must be `type: "object"`; `strict: true` asks providers that support it to enforce the schema exactly (every property required, `additionalProperties: false`). `model` + `provider` pick the model; omit both for the platform's default. A reply that is not a JSON object for the schema answers 422 `unprocessable_entity`; provider failures answer 502 `upstream_error`.+ *+ * **API key scopes:** `generation:write`.+ */+ public generate<ThrowOnError extends boolean = false>(options: Options<PostApiV1ObjectsGenerationsData, ThrowOnError>): RequestResult<PostApiV1ObjectsGenerationsResponses, PostApiV1ObjectsGenerationsErrors, ThrowOnError> {+ return (options.client ?? this.client).post<PostApiV1ObjectsGenerationsResponses, PostApiV1ObjectsGenerationsErrors, ThrowOnError>({+ security: [{ scheme: 'bearer', type: 'http' }],+ url: '/api/v1/objects/generations',+ ...options,+ headers: mergeMethodHeaders({ 'Content-Type': 'application/json' }, options.headers)+ });+ }+}+export class LobeHub extends HeyApiClient {public static readonly __registry: HeyApiRegistry<LobeHub> = new HeyApiRegistry<LobeHub>();@@ -2800,4 +2937,29 @@ export class LobeHub extends HeyApiClient {get usage(): Usage {return this._usage ??= new Usage({ client: this.client });}++ private _generations?: Generations;+ get generations(): Generations {+ return this._generations ??= new Generations({ client: this.client });+ }++ private _images?: Images;+ get images(): Images {+ return this._images ??= new Images({ client: this.client });+ }++ private _videos?: Videos;+ get videos(): Videos {+ return this._videos ??= new Videos({ client: this.client });+ }++ private _text?: Text;+ get text(): Text {+ return this._text ??= new Text({ client: this.client });+ }++ private _objects?: Objects;+ get objects(): Objects {+ return this._objects ??= new Objects({ client: this.client });+ }}diff --git a/packages/sdk/src/generated/types.gen.ts b/packages/sdk/src/generated/types.gen.tsindex ac3d194d07c..85bfc016a04 100644--- a/packages/sdk/src/generated/types.gen.ts+++ b/packages/sdk/src/generated/types.gen.ts@@ -226,7 +226,7 @@ export type ApiKey = {id: string;lastUsedAt: string | null;name: string;- scopes: Array<'*' | 'agent:read' | 'agent:write' | 'agent:credential:write' | 'eval:read' | 'eval:write' | 'chat:read' | 'chat:write' | 'model:invoke' | 'model:read' | 'model:write' | 'file:read' | 'file:write' | 'knowledge:read' | 'knowledge:write' | 'mcp:read' | 'mcp:write' | 'usage:read' | 'workspace:read' | 'workspace:write' | 'user:read' | 'user:write'> | null;+ scopes: Array<'*' | 'agent:read' | 'agent:write' | 'agent:credential:write' | 'eval:read' | 'eval:write' | 'chat:read' | 'chat:write' | 'model:invoke' | 'model:read' | 'model:write' | 'file:read' | 'file:write' | 'knowledge:read' | 'knowledge:write' | 'generation:read' | 'generation:write' | 'mcp:read' | 'mcp:write' | 'usage:read' | 'workspace:read' | 'workspace:write' | 'user:read' | 'user:write'> | null;updatedAt: string;};@@ -237,11 +237,18 @@ export type CreatedApiKey = {id: string;lastUsedAt: string | null;name: string;- scopes: Array<'*' | 'agent:read' | 'agent:write' | 'agent:credential:write' | 'eval:read' | 'eval:write' | 'chat:read' | 'chat:write' | 'model:invoke' | 'model:read' | 'model:write' | 'file:read' | 'file:write' | 'knowledge:read' | 'knowledge:write' | 'mcp:read' | 'mcp:write' | 'usage:read' | 'workspace:read' | 'workspace:write' | 'user:read' | 'user:write'> | null;+ scopes: Array<'*' | 'agent:read' | 'agent:write' | 'agent:credential:write' | 'eval:read' | 'eval:write' | 'chat:read' | 'chat:write' | 'model:invoke' | 'model:read' | 'model:write' | 'file:read' | 'file:write' | 'knowledge:read' | 'knowledge:write' | 'generation:read' | 'generation:write' | 'mcp:read' | 'mcp:write' | 'usage:read' | 'workspace:read' | 'workspace:write' | 'user:read' | 'user:write'> | null;updatedAt: string;key: string;};+export type Transcription = {+ /**+ * The transcript.+ */+ text: string;+};+export type ChatResponse = {content: string;model: string;@@ -2800,6 +2807,75 @@ export type Usage = {}>;};+export type Generation = {+ /**+ * The output; `null` until it succeeded.+ */+ asset: GenerationAsset | null;+ /**+ * The request (batch) this generation belongs to.+ */+ batchId: string;+ /**+ * ISO 8601 timestamp.+ */+ createdAt: string;+ /**+ * Why it failed; `null` unless `error`.+ */+ error: GenerationError | null;+ /**+ * Library file the output was saved as, once it succeeded.+ */+ fileId: string | null;+ id: string;+ model: string;+ prompt: string;+ provider: string;+ seed: number | null;+ /**+ * `pending` → `processing` → `success` | `error`. The last two are final.+ */+ status: 'pending' | 'processing' | 'success' | 'error';+ /**+ * The generation topic the request was added to.+ */+ topicId: string;+ type: 'image' | 'video' | 'music';+};++export type GenerationAsset = {+ /**+ * Video cover image URL.+ */+ coverUrl: string | null;+ /**+ * Video length in seconds.+ */+ duration: number | null;+ height: number | null;+ /**+ * Resized preview URL.+ */+ thumbnailUrl: string | null;+ /**+ * Full-size asset URL.+ */+ url: string | null;+ width: number | null;+};++export type GenerationError = {+ /**+ * Human-readable failure reason.+ */+ message: string;+ /**+ * Error type, for example `ServerError` or `Timeout`.+ */+ name: string;+};+/*** Makes the request safe to retry: the first request with a key runs, and repeats with the same key and the same request within 24 hours get its stored response back (with `Idempotent-Replayed: true`). A repeat while the first is still running answers 409, and reusing a key for a different request (method, path or body) answers 422 (both `idempotency_conflict`). Server errors, 429s and streamed responses are not stored. Keys are scoped to the authenticated user, the credential (API key) and the resolved workspace. A request still running after 5 minutes releases its in-flight claim, after which a retry with the same key runs again.*/@@ -4136,7 +4212,7 @@ export type PostApiV1ApiKeysData = {body: {expiresAt?: string | null;name: string;- scopes?: Array<'*' | 'agent:read' | 'agent:write' | 'agent:credential:write' | 'eval:read' | 'eval:write' | 'chat:read' | 'chat:write' | 'model:invoke' | 'model:read' | 'model:write' | 'file:read' | 'file:write' | 'knowledge:read' | 'knowledge:write' | 'mcp:read' | 'mcp:write' | 'usage:read' | 'workspace:read' | 'workspace:write' | 'user:read' | 'user:write'> | null;+ scopes?: Array<'*' | 'agent:read' | 'agent:write' | 'agent:credential:write' | 'eval:read' | 'eval:write' | 'chat:read' | 'chat:write' | 'model:invoke' | 'model:read' | 'model:write' | 'file:read' | 'file:write' | 'knowledge:read' | 'knowledge:write' | 'generation:read' | 'generation:write' | 'mcp:read' | 'mcp:write' | 'usage:read' | 'workspace:read' | 'workspace:write' | 'user:read' | 'user:write'> | null;};headers?: {/**@@ -4371,7 +4447,24 @@ export type PatchApiV1ApiKeysByIdResponses = {export type PatchApiV1ApiKeysByIdResponse = PatchApiV1ApiKeysByIdResponses[keyof PatchApiV1ApiKeysByIdResponses];export type PostApiV1AudioSpeechData = {- body?: never;+ body: {+ input: string;+ instructions?: string;+ model: string;+ params?: {+ emotion?: string;+ pitch?: number;+ sampleRate?: number;+ volume?: number;+ };+ provider?: string;+ response_format?: 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm';+ speed?: number;+ stream_format?: 'audio' | 'sse';+ voice?: string | {+ id: string;+ };+ };headers?: {/*** Run the request inside a workspace instead of the caller's personal space. Omit it for personal data. A personal API key cannot send it (403 `workspace_mismatch`); a workspace API key is bound to its workspace, so the header may be omitted and, when sent, must name that same workspace (403 `workspace_mismatch` otherwise). An unknown workspace answers 404, and a caller who is not a member answers 403 `workspace_mismatch`. Workspace API key access also depends on the workspace's plan. Routes that change workspace-wide settings additionally require the admin or owner role.@@ -4464,6 +4557,95 @@ export type PostApiV1AudioSpeechResponses = {export type PostApiV1AudioSpeechResponse = PostApiV1AudioSpeechResponses[keyof PostApiV1AudioSpeechResponses];+export type PostApiV1AudioTranscriptionsData = {+ body: {+ /**+ * The audio clip.+ */+ file?: Blob | File;+ /**+ * An uploaded audio file, instead of `file`.+ */+ fileId?: string;+ /**+ * ISO-639-1 language code, e.g. `en`.+ */+ language?: string;+ /**+ * Transcription model, e.g. `whisper-1`.+ */+ model: string;+ /**+ * Text to guide the model's style.+ */+ prompt?: string;+ /**+ * Provider id; defaults to `openai`.+ */+ provider?: string;+ response_format?: 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt';+ };+ headers?: {+ /**+ * Run the request inside a workspace instead of the caller's personal space. Omit it for personal data. A personal API key cannot send it (403 `workspace_mismatch`); a workspace API key is bound to its workspace, so the header may be omitted and, when sent, must name that same workspace (403 `workspace_mismatch` otherwise). An unknown workspace answers 404, and a caller who is not a member answers 403 `workspace_mismatch`. Workspace API key access also depends on the workspace's plan. Routes that change workspace-wide settings additionally require the admin or owner role.+ */+ 'X-Workspace-Id'?: string;+ /**+ * Makes the request safe to retry: the first request with a key runs, and repeats with the same key and the same request within 24 hours get its stored response back (with `Idempotent-Replayed: true`). A repeat while the first is still running answers 409, and reusing a key for a different request (method, path or body) answers 422 (both `idempotency_conflict`). Server errors, 429s and streamed responses are not stored. Keys are scoped to the authenticated user, the credential (API key) and the resolved workspace. A request still running after 5 minutes releases its in-flight claim, after which a retry with the same key runs again.+ */+ 'Idempotency-Key'?: string;+ };+ path?: never;+ query?: never;+ url: '/api/v1/audio/transcriptions';+};++export type PostApiV1AudioTranscriptionsErrors = {+ /**+ * Invalid request+ */+ 400: ApiError;+ /**+ * Authentication required+ */+ 401: ApiError;+ /**+ * Insufficient permission+ */+ 403: ApiError;+ /**+ * Resource not found+ */+ 404: ApiError;+ /**+ * Payload too large+ */+ 413: ApiError;+ /**+ * Rate limit exceeded+ */+ 429: ApiError;+ /**+ * Internal server error+ */+ 500: ApiError;+ /**+ * Upstream error+ */+ 502: ApiError;+};++export type PostApiV1AudioTranscriptionsError = PostApiV1AudioTranscriptionsErrors[keyof PostApiV1AudioTranscriptionsErrors];++export type PostApiV1AudioTranscriptionsResponses = {+ /**+ * Successful response+ */+ 200: Transcription;+};++export type PostApiV1AudioTranscriptionsResponse = PostApiV1AudioTranscriptionsResponses[keyof PostApiV1AudioTranscriptionsResponses];+export type PostApiV1ChatData = {body: {frequency_penalty?: number;@@ -15046,3 +15228,691 @@ export type GetApiV1UsageResponses = {};export type GetApiV1UsageResponse = GetApiV1UsageResponses[keyof GetApiV1UsageResponses];++export type GetApiV1GenerationsData = {+ body?: never;+ headers?: {+ /**+ * Run the request inside a workspace instead of the caller's personal space. Omit it for personal data. A personal API key cannot send it (403 `workspace_mismatch`); a workspace API key is bound to its workspace, so the header may be omitted and, when sent, must name that same workspace (403 `workspace_mismatch` otherwise). An unknown workspace answers 404, and a caller who is not a member answers 403 `workspace_mismatch`. Workspace API key access also depends on the workspace's plan. Routes that change workspace-wide settings additionally require the admin or owner role.+ */+ 'X-Workspace-Id'?: string;+ };+ path?: never;+ query?: {+ /**+ * Opaque cursor from the previous page's `nextCursor`. Omit for the first page.+ */+ cursor?: string;+ /**+ * Page size, 1–100. Defaults to 20.+ */+ limit?: number;+ /**+ * Only generations of this kind.+ */+ type?: 'image' | 'video' | 'music';+ };+ url: '/api/v1/generations';+};++export type GetApiV1GenerationsErrors = {+ /**+ * Invalid request+ */+ 400: ApiError;+ /**+ * Authentication required+ */+ 401: ApiError;+ /**+ * Insufficient permission+ */+ 403: ApiError;+ /**+ * Rate limit exceeded+ */+ 429: ApiError;+ /**+ * Internal server error+ */+ 500: ApiError;+};++export type GetApiV1GenerationsError = GetApiV1GenerationsErrors[keyof GetApiV1GenerationsErrors];++export type GetApiV1GenerationsResponses = {+ /**+ * Successful response+ */+ 200: {+ data: {+ items: Array<Generation>;+ hasMore: PageHasMore;+ nextCursor: PageNextCursor;+ total: PageTotal;+ };+ message?: string;+ success: true;+ timestamp: string;+ };+};++export type GetApiV1GenerationsResponse = GetApiV1GenerationsResponses[keyof GetApiV1GenerationsResponses];++export type DeleteApiV1GenerationsByIdData = {+ body?: never;+ headers?: {+ /**+ * Run the request inside a workspace instead of the caller's personal space. Omit it for personal data. A personal API key cannot send it (403 `workspace_mismatch`); a workspace API key is bound to its workspace, so the header may be omitted and, when sent, must name that same workspace (403 `workspace_mismatch` otherwise). An unknown workspace answers 404, and a caller who is not a member answers 403 `workspace_mismatch`. Workspace API key access also depends on the workspace's plan. Routes that change workspace-wide settings additionally require the admin or owner role.+ */+ 'X-Workspace-Id'?: string;+ };+ path: {+ id: string;+ };+ query?: never;+ url: '/api/v1/generations/{id}';+};++export type DeleteApiV1GenerationsByIdErrors = {+ /**+ * Invalid request+ */+ 400: ApiError;+ /**+ * Authentication required+ */+ 401: ApiError;+ /**+ * Insufficient permission+ */+ 403: ApiError;+ /**+ * Resource not found+ */+ 404: ApiError;+ /**+ * Rate limit exceeded+ */+ 429: ApiError;+ /**+ * Internal server error+ */+ 500: ApiError;+};++export type DeleteApiV1GenerationsByIdError = DeleteApiV1GenerationsByIdErrors[keyof DeleteApiV1GenerationsByIdErrors];++export type DeleteApiV1GenerationsByIdResponses = {+ /**+ * Successful response+ */+ 200: {+ data: DeletedResource;+ message?: string;+ success: true;+ timestamp: string;+ };+};++export type DeleteApiV1GenerationsByIdResponse = DeleteApiV1GenerationsByIdResponses[keyof DeleteApiV1GenerationsByIdResponses];++export type GetApiV1GenerationsByIdData = {+ body?: never;+ headers?: {+ /**+ * Run the request inside a workspace instead of the caller's personal space. Omit it for personal data. A personal API key cannot send it (403 `workspace_mismatch`); a workspace API key is bound to its workspace, so the header may be omitted and, when sent, must name that same workspace (403 `workspace_mismatch` otherwise). An unknown workspace answers 404, and a caller who is not a member answers 403 `workspace_mismatch`. Workspace API key access also depends on the workspace's plan. Routes that change workspace-wide settings additionally require the admin or owner role.+ */+ 'X-Workspace-Id'?: string;+ };+ path: {+ id: string;+ };+ query?: never;+ url: '/api/v1/generations/{id}';+};++export type GetApiV1GenerationsByIdErrors = {+ /**+ * Invalid request+ */+ 400: ApiError;+ /**+ * Authentication required+ */+ 401: ApiError;+ /**+ * Insufficient permission+ */+ 403: ApiError;+ /**+ * Resource not found+ */+ 404: ApiError;+ /**+ * Rate limit exceeded+ */+ 429: ApiError;+ /**+ * Internal server error+ */+ 500: ApiError;+};++export type GetApiV1GenerationsByIdError = GetApiV1GenerationsByIdErrors[keyof GetApiV1GenerationsByIdErrors];++export type GetApiV1GenerationsByIdResponses = {+ /**+ * Successful response+ */+ 200: {+ data: Generation;+ message?: string;+ success: true;+ timestamp: string;+ };+};++export type GetApiV1GenerationsByIdResponse = GetApiV1GenerationsByIdResponses[keyof GetApiV1GenerationsByIdResponses];++export type PostApiV1ImagesGenerationsData = {+ body: {+ /**+ * Guidance scale, for models that accept one.+ */+ cfg?: number;+ /**+ * Image height in pixels.+ */+ height?: number;+ /**+ * Reference images (URLs) for image-to-image models.+ */+ imageUrls?: Array<string>;+ /**+ * Image model id. Omit to use the account's default image model.+ */+ model?: string;+ /**+ * Number of images to generate, 1–8. Defaults to 1.+ */+ n?: number;+ /**+ * Model-specific parameters beyond the named fields (for example `quality` or `size`). Parameters the model does not declare are rejected with 400.+ */+ params?: {+ [key: string]: string | number | boolean | Array<string> | null;+ };+ /**+ * What to generate.+ */+ prompt: string;+ /**+ * Provider id. Omit to use the first enabled provider serving `model`.+ */+ provider?: string;+ /**+ * Seed; omit for a random one per image.+ */+ seed?: number | null;+ /**+ * Sampling steps.+ */+ steps?: number;+ /**+ * Generation topic to add this request to. Omit to start a new topic, as `lh generate` does.+ */+ topicId?: string;+ /**+ * Wait for the images before answering (up to `waitTimeoutSeconds`). Generations still running at the deadline come back with their current status; poll `GET /generations/{id}` for the rest. Set `false` to answer as soon as the work is queued.+ */+ wait?: boolean;+ /**+ * How long `wait` may hold the request, 1–120 seconds. Defaults to 60.+ */+ waitTimeoutSeconds?: number;+ /**+ * Image width in pixels.+ */+ width?: number;+ };+ headers?: {+ /**+ * Run the request inside a workspace instead of the caller's personal space. Omit it for personal data. A personal API key cannot send it (403 `workspace_mismatch`); a workspace API key is bound to its workspace, so the header may be omitted and, when sent, must name that same workspace (403 `workspace_mismatch` otherwise). An unknown workspace answers 404, and a caller who is not a member answers 403 `workspace_mismatch`. Workspace API key access also depends on the workspace's plan. Routes that change workspace-wide settings additionally require the admin or owner role.+ */+ 'X-Workspace-Id'?: string;+ /**+ * Makes the request safe to retry: the first request with a key runs, and repeats with the same key and the same request within 24 hours get its stored response back (with `Idempotent-Replayed: true`). A repeat while the first is still running answers 409, and reusing a key for a different request (method, path or body) answers 422 (both `idempotency_conflict`). Server errors, 429s and streamed responses are not stored. Keys are scoped to the authenticated user, the credential (API key) and the resolved workspace. A request still running after 5 minutes releases its in-flight claim, after which a retry with the same key runs again.+ */+ 'Idempotency-Key'?: string;+ };+ path?: never;+ query?: never;+ url: '/api/v1/images/generations';+};++export type PostApiV1ImagesGenerationsErrors = {+ /**+ * Invalid request+ */+ 400: ApiError;+ /**+ * Authentication required+ */+ 401: ApiError;+ /**+ * Insufficient permission+ */+ 403: ApiError;+ /**+ * Resource not found+ */+ 404: ApiError;+ /**+ * Rate limit exceeded+ */+ 429: ApiError;+ /**+ * Internal server error+ */+ 500: ApiError;+};++export type PostApiV1ImagesGenerationsError = PostApiV1ImagesGenerationsErrors[keyof PostApiV1ImagesGenerationsErrors];++export type PostApiV1ImagesGenerationsResponses = {+ /**+ * Successful response+ */+ 200: {+ data: {+ batchId: string;+ generations: Array<Generation>;+ topicId: string;+ };+ message?: string;+ success: true;+ timestamp: string;+ };+};++export type PostApiV1ImagesGenerationsResponse = PostApiV1ImagesGenerationsResponses[keyof PostApiV1ImagesGenerationsResponses];++export type PostApiV1VideosGenerationsData = {+ body: {+ /**+ * Aspect ratio, for example `16:9`.+ */+ aspectRatio?: string;+ /**+ * Keep the camera still, where supported.+ */+ cameraFixed?: boolean;+ /**+ * Video length in seconds.+ */+ duration?: number;+ /**+ * Last frame (URL), where supported.+ */+ endImageUrl?: string | null;+ /**+ * Generate a soundtrack, where supported.+ */+ generateAudio?: boolean;+ /**+ * First frame (URL) for image-to-video.+ */+ imageUrl?: string | null;+ /**+ * Video model id.+ */+ model: string;+ /**+ * Model-specific parameters beyond the named fields (for example `quality` or `size`). Parameters the model does not declare are rejected with 400.+ */+ params?: {+ [key: string]: string | number | boolean | Array<string> | null;+ };+ /**+ * A video generation to edit, for models that support conversational editing.+ */+ previousGenerationId?: string;+ /**+ * What to generate.+ */+ prompt: string;+ /**+ * Provider id serving `model`.+ */+ provider: string;+ /**+ * Output resolution, for example `720p`.+ */+ resolution?: string;+ /**+ * Seed; omit for a random one.+ */+ seed?: number | null;+ /**+ * Generation topic to add this request to. Omit to start a new topic, as `lh generate` does.+ */+ topicId?: string;+ };+ headers?: {+ /**+ * Run the request inside a workspace instead of the caller's personal space. Omit it for personal data. A personal API key cannot send it (403 `workspace_mismatch`); a workspace API key is bound to its workspace, so the header may be omitted and, when sent, must name that same workspace (403 `workspace_mismatch` otherwise). An unknown workspace answers 404, and a caller who is not a member answers 403 `workspace_mismatch`. Workspace API key access also depends on the workspace's plan. Routes that change workspace-wide settings additionally require the admin or owner role.+ */+ 'X-Workspace-Id'?: string;+ /**+ * Makes the request safe to retry: the first request with a key runs, and repeats with the same key and the same request within 24 hours get its stored response back (with `Idempotent-Replayed: true`). A repeat while the first is still running answers 409, and reusing a key for a different request (method, path or body) answers 422 (both `idempotency_conflict`). Server errors, 429s and streamed responses are not stored. Keys are scoped to the authenticated user, the credential (API key) and the resolved workspace. A request still running after 5 minutes releases its in-flight claim, after which a retry with the same key runs again.+ */+ 'Idempotency-Key'?: string;+ };+ path?: never;+ query?: never;+ url: '/api/v1/videos/generations';+};++export type PostApiV1VideosGenerationsErrors = {+ /**+ * Invalid request+ */+ 400: ApiError;+ /**+ * Authentication required+ */+ 401: ApiError;+ /**+ * Insufficient permission+ */+ 403: ApiError;+ /**+ * Resource not found+ */+ 404: ApiError;+ /**+ * Rate limit exceeded+ */+ 429: ApiError;+ /**+ * Internal server error+ */+ 500: ApiError;+};++export type PostApiV1VideosGenerationsError = PostApiV1VideosGenerationsErrors[keyof PostApiV1VideosGenerationsErrors];++export type PostApiV1VideosGenerationsResponses = {+ /**+ * Successful response+ */+ 202: {+ data: {+ batchId: string;+ generations: Array<Generation>;+ topicId: string;+ };+ message?: string;+ success: true;+ timestamp: string;+ };+};++export type PostApiV1VideosGenerationsResponse = PostApiV1VideosGenerationsResponses[keyof PostApiV1VideosGenerationsResponses];++export type PostApiV1TextGenerationsData = {+ body: {+ /**+ * Maximum output tokens.+ */+ maxTokens?: number;+ /**+ * Conversation to complete. Use instead of, or after, `system` + `prompt`.+ */+ messages?: Array<{+ /**+ * Plain-text message content.+ */+ content: string;+ role: 'system' | 'user' | 'assistant';+ }>;+ /**+ * Model id. Omit to use the platform's default chat model.+ */+ model?: string;+ /**+ * User prompt; appended after `messages` when both are given.+ */+ prompt?: string;+ /**+ * Provider id (for example `lobehub`, `openai`). Omit with `model` for the default.+ */+ provider?: string;+ /**+ * System prompt, placed first.+ */+ system?: string;+ /**+ * Sampling temperature, 0–2.+ */+ temperature?: number;+ };+ headers?: {+ /**+ * Run the request inside a workspace instead of the caller's personal space. Omit it for personal data. A personal API key cannot send it (403 `workspace_mismatch`); a workspace API key is bound to its workspace, so the header may be omitted and, when sent, must name that same workspace (403 `workspace_mismatch` otherwise). An unknown workspace answers 404, and a caller who is not a member answers 403 `workspace_mismatch`. Workspace API key access also depends on the workspace's plan. Routes that change workspace-wide settings additionally require the admin or owner role.+ */+ 'X-Workspace-Id'?: string;+ /**+ * Makes the request safe to retry: the first request with a key runs, and repeats with the same key and the same request within 24 hours get its stored response back (with `Idempotent-Replayed: true`). A repeat while the first is still running answers 409, and reusing a key for a different request (method, path or body) answers 422 (both `idempotency_conflict`). Server errors, 429s and streamed responses are not stored. Keys are scoped to the authenticated user, the credential (API key) and the resolved workspace. A request still running after 5 minutes releases its in-flight claim, after which a retry with the same key runs again.+ */+ 'Idempotency-Key'?: string;+ };+ path?: never;+ query?: never;+ url: '/api/v1/text/generations';+};++export type PostApiV1TextGenerationsErrors = {+ /**+ * Invalid request+ */+ 400: ApiError;+ /**+ * Authentication required+ */+ 401: ApiError;+ /**+ * Payment required+ */+ 402: ApiError;+ /**+ * Insufficient permission+ */+ 403: ApiError;+ /**+ * Unprocessable content+ */+ 422: ApiError;+ /**+ * Rate limit exceeded+ */+ 429: ApiError;+ /**+ * Internal server error+ */+ 500: ApiError;+ /**+ * Upstream error+ */+ 502: ApiError;+};++export type PostApiV1TextGenerationsError = PostApiV1TextGenerationsErrors[keyof PostApiV1TextGenerationsErrors];++export type PostApiV1TextGenerationsResponses = {+ /**+ * Successful response+ */+ 200: {+ data: {+ /**+ * Why the model stopped, as the provider reports it (`stop`, `length`, …).+ */+ finishReason: string | null;+ model: string;+ provider: string;+ /**+ * Reasoning of a reasoning model, kept out of `text`; `null` otherwise.+ */+ reasoning: string | null;+ /**+ * The generated text.+ */+ text: string;+ usage: {+ inputTokens: number | null;+ outputTokens: number | null;+ reasoningTokens: number | null;+ totalTokens: number | null;+ } | null;+ };+ message?: string;+ success: true;+ timestamp: string;+ };+};++export type PostApiV1TextGenerationsResponse = PostApiV1TextGenerationsResponses[keyof PostApiV1TextGenerationsResponses];++export type PostApiV1ObjectsGenerationsData = {+ body: {+ /**+ * Conversation to complete. Use instead of, or after, `system` + `prompt`.+ */+ messages?: Array<{+ /**+ * Plain-text message content.+ */+ content: string;+ role: 'system' | 'user' | 'assistant';+ }>;+ /**+ * Model id. Omit to use the platform's default chat model.+ */+ model?: string;+ /**+ * User prompt; appended after `messages` when both are given.+ */+ prompt?: string;+ /**+ * Provider id (for example `lobehub`, `openai`). Omit with `model` for the default.+ */+ provider?: string;+ /**+ * System prompt, placed first.+ */+ system?: string;+ /**+ * A JSON Schema with `type: "object"` at the root. Supported root keywords: `properties`, `required`, `additionalProperties`, `$defs`, `title`, `description`; others (such as `allOf`) are rejected rather than silently dropped.+ */+ schema: {+ $defs?: {+ [key: string]: unknown;+ };+ additionalProperties?: boolean;+ description?: string;+ properties: {+ [key: string]: unknown;+ };+ required?: Array<string>;+ title?: string;+ type: 'object';+ };+ /**+ * What the object is, sent with the schema.+ */+ schemaDescription?: string;+ /**+ * Name sent with the schema. Defaults to `response`.+ */+ schemaName?: string;+ /**+ * Ask the provider to enforce the schema strictly (every property required, no extras).+ */+ strict?: boolean;+ };+ headers?: {+ /**+ * Run the request inside a workspace instead of the caller's personal space. Omit it for personal data. A personal API key cannot send it (403 `workspace_mismatch`); a workspace API key is bound to its workspace, so the header may be omitted and, when sent, must name that same workspace (403 `workspace_mismatch` otherwise). An unknown workspace answers 404, and a caller who is not a member answers 403 `workspace_mismatch`. Workspace API key access also depends on the workspace's plan. Routes that change workspace-wide settings additionally require the admin or owner role.+ */+ 'X-Workspace-Id'?: string;+ /**+ * Makes the request safe to retry: the first request with a key runs, and repeats with the same key and the same request within 24 hours get its stored response back (with `Idempotent-Replayed: true`). A repeat while the first is still running answers 409, and reusing a key for a different request (method, path or body) answers 422 (both `idempotency_conflict`). Server errors, 429s and streamed responses are not stored. Keys are scoped to the authenticated user, the credential (API key) and the resolved workspace. A request still running after 5 minutes releases its in-flight claim, after which a retry with the same key runs again.+ */+ 'Idempotency-Key'?: string;+ };+ path?: never;+ query?: never;+ url: '/api/v1/objects/generations';+};++export type PostApiV1ObjectsGenerationsErrors = {+ /**+ * Invalid request+ */+ 400: ApiError;+ /**+ * Authentication required+ */+ 401: ApiError;+ /**+ * Payment required+ */+ 402: ApiError;+ /**+ * Insufficient permission+ */+ 403: ApiError;+ /**+ * Unprocessable content+ */+ 422: ApiError;+ /**+ * Rate limit exceeded+ */+ 429: ApiError;+ /**+ * Internal server error+ */+ 500: ApiError;+ /**+ * Upstream error+ */+ 502: ApiError;+};++export type PostApiV1ObjectsGenerationsError = PostApiV1ObjectsGenerationsErrors[keyof PostApiV1ObjectsGenerationsErrors];++export type PostApiV1ObjectsGenerationsResponses = {+ /**+ * Successful response+ */+ 200: {+ data: {+ model: string;+ /**+ * The generated object, valid for the requested schema.+ */+ object: {+ [key: string]: unknown;+ };+ provider: string;+ };+ message?: string;+ success: true;+ timestamp: string;+ };+};++export type PostApiV1ObjectsGenerationsResponse = PostApiV1ObjectsGenerationsResponses[keyof PostApiV1ObjectsGenerationsResponses];diff --git a/packages/sdk/src/generations.test.ts b/packages/sdk/src/generations.test.tsnew file mode 100644index 00000000000..b2fa03ec0c8--- /dev/null+++ b/packages/sdk/src/generations.test.ts@@ -0,0 +1,157 @@+import { describe, expect, expectTypeOf, it } from 'vitest';++import type { Generation } from './index';+import { createLobeHub, GenerationWaitTimeoutError, LobeHubAPIError } from './index';++const json = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), {+ headers: { 'Content-Type': 'application/json' },+ status,+ });++const generation = (status: Generation['status'], extra: Partial<Generation> = {}): Generation => ({+ asset: null,+ batchId: 'gb_1',+ createdAt: '2026-01-01T00:00:00.000Z',+ error: null,+ fileId: null,+ id: 'gen_1',+ model: 'seedance-1-0-pro',+ prompt: 'waves',+ provider: 'volcengine',+ seed: null,+ status,+ topicId: 'gt_1',+ type: 'video',+ ...extra,+});++/** Answers `GET /generations/{id}` with each state in turn, repeating the last one. */+const statusFetch = (states: (Generation | Response)[]) => {+ const urls: string[] = [];+ const fetch = (async (input: Request) => {+ urls.push(new URL(input.url).pathname);+ const next = states[Math.min(urls.length - 1, states.length - 1)];+ return next instanceof Response+ ? next.clone()+ : json({ data: next, success: true, timestamp: '2026-01-01T00:00:00Z' });+ }) as typeof globalThis.fetch;+ return { fetch, urls };+};++describe('generations.wait', () => {+ it('polls until the generation succeeds and returns its final state', async () => {+ const done = generation('success', {+ asset: {+ coverUrl: 'https://cdn.test/cover.webp',+ duration: 5,+ height: 720,+ thumbnailUrl: 'https://cdn.test/thumb.webp',+ url: 'https://cdn.test/video.mp4',+ width: 1280,+ },+ });+ const { fetch, urls } = statusFetch([generation('pending'), generation('processing'), done]);+ const lobehub = createLobeHub({ apiKey: 'sk-lh-test', fetch });+ const seen: string[] = [];++ const result = await lobehub.generations.wait('gen_1', {+ onPoll: (state) => seen.push(state.status),+ pollInterval: 1,+ });++ expect(result).toEqual(done);+ expect(seen).toEqual(['pending', 'processing', 'success']);+ expect(urls).toEqual(Array.from({ length: 3 }, () => '/api/v1/generations/gen_1'));+ expectTypeOf(result).toEqualTypeOf<Generation>();+ });++ it('resolves with a failed generation instead of throwing', async () => {+ const failed = generation('error', {+ error: { message: 'Content policy', name: 'ServerError' },+ });+ const { fetch } = statusFetch([generation('processing'), failed]);+ const lobehub = createLobeHub({ apiKey: 'sk-lh-test', fetch });++ await expect(lobehub.generations.wait('gen_1', { pollInterval: 1 })).resolves.toEqual(failed);+ });++ it('gives up after the timeout with the last state it read', async () => {+ const { fetch } = statusFetch([generation('processing')]);+ const lobehub = createLobeHub({ apiKey: 'sk-lh-test', fetch });++ const error = await lobehub.generations+ .wait('gen_1', { pollInterval: 5, timeout: 20 })+ .catch((error_: unknown) => error_);++ expect(error).toBeInstanceOf(GenerationWaitTimeoutError);+ expect((error as GenerationWaitTimeoutError).generation.status).toBe('processing');+ });++ it('bounds a slow status request by the wait timeout', async () => {+ const fetch = (async (input: Request) => {+ await new Promise((resolve, reject) => {+ const timer = setTimeout(resolve, 2000);+ input.signal.addEventListener('abort', () => {+ clearTimeout(timer);+ reject(input.signal.reason);+ });+ });+ return json({ data: generation('success'), success: true, timestamp: 't' });+ }) as typeof globalThis.fetch;+ const lobehub = createLobeHub({ apiKey: 'sk-lh-test', fetch });++ const started = Date.now();+ const error = await lobehub.generations+ .wait('gen_1', { timeout: 50 })+ .catch((error_: unknown) => error_);++ expect(error).toBeInstanceOf(GenerationWaitTimeoutError);+ expect((error as GenerationWaitTimeoutError).generation).toBeUndefined();+ expect(Date.now() - started).toBeLessThan(1000);+ });++ it('rejects with the API error when the generation cannot be read', async () => {+ const { fetch, urls } = statusFetch([+ json(+ {+ code: 'not_found',+ message: 'Generation not found',+ success: false,+ timestamp: '2026-01-01T00:00:00Z',+ },+ 404,+ ),+ ]);+ const lobehub = createLobeHub({ apiKey: 'sk-lh-test', fetch, maxRetries: 0 });++ const error = await lobehub.generations.wait('gen_x').catch((error_: unknown) => error_);++ expect(error).toBeInstanceOf(LobeHubAPIError);+ expect(error).toMatchObject({ code: 'not_found', status: 404 });+ expect(urls).toHaveLength(1);+ });++ it('stops when the signal aborts', async () => {+ const { fetch } = statusFetch([generation('pending')]);+ const lobehub = createLobeHub({ apiKey: 'sk-lh-test', fetch });+ const controller = new AbortController();++ const waiting = lobehub.generations.wait('gen_1', {+ pollInterval: 10_000,+ signal: controller.signal,+ });+ setTimeout(() => controller.abort(new Error('stop')), 5);++ await expect(waiting).rejects.toThrow('stop');+ });++ it('is available on a throwOnError client too', async () => {+ const { fetch } = statusFetch([generation('success')]);+ const lobehub = createLobeHub({ apiKey: 'sk-lh-test', fetch, throwOnError: true });++ await expect(lobehub.generations.wait('gen_1')).resolves.toMatchObject({ status: 'success' });+ const { data } = await lobehub.generations.get({ path: { id: 'gen_1' } });+ expectTypeOf(data.data).toEqualTypeOf<Generation>();+ });+});diff --git a/packages/sdk/src/generations.ts b/packages/sdk/src/generations.tsnew file mode 100644index 00000000000..ea4c05c166a--- /dev/null+++ b/packages/sdk/src/generations.ts@@ -0,0 +1,129 @@+import { Generations } from './generated/sdk.gen';+import type { Generation } from './generated/types.gen';++/** Statuses after which a generation no longer changes. */+export const TERMINAL_GENERATION_STATUSES: readonly Generation['status'][] = ['success', 'error'];++export const DEFAULT_GENERATION_POLL_INTERVAL = 2000;+export const DEFAULT_GENERATION_WAIT_TIMEOUT = 10 * 60 * 1000;++export interface GenerationWaitOptions {+ /** Called with every state read, e.g. to report progress. */+ onPoll?: (generation: Generation) => void;+ /** Milliseconds between status reads. Defaults to 2 s. */+ pollInterval?: number;+ /** Stops waiting (rejecting with the signal's reason) when aborted. */+ signal?: AbortSignal;+ /**+ * Give up after this many milliseconds, including a status request still in+ * flight. Defaults to 10 minutes; videos can take several.+ */+ timeout?: number;+}++/**+ * `generations.wait` ran out of time; `generation` is the last state it read+ * (absent when no status request finished in time).+ */+export class GenerationWaitTimeoutError extends Error {+ readonly generation?: Generation;+ readonly timeout: number;++ constructor(id: string, timeout: number, generation?: Generation) {+ super(+ `Generation ${id} is still ${generation?.status ?? 'unread'} after ${timeout} ms; call generations.wait again to keep waiting`,+ );+ this.name = 'GenerationWaitTimeoutError';+ this.generation = generation;+ this.timeout = timeout;+ }+}++/** Abort when any of `signals` does (`AbortSignal.any`, with a fallback for older hosts). */+const anySignal = (signals: AbortSignal[]) => {+ if (typeof AbortSignal.any === 'function') return AbortSignal.any(signals);+ const controller = new AbortController();+ for (const signal of signals) {+ if (signal.aborted) {+ controller.abort(signal.reason);+ break;+ }+ signal.addEventListener('abort', () => controller.abort(signal.reason), {+ once: true,+ signal: controller.signal,+ });+ }+ return controller.signal;+};++const sleep = (ms: number, signal?: AbortSignal) =>+ new Promise<void>((resolve, reject) => {+ if (signal?.aborted) return reject(signal.reason);+ const onAbort = () => {+ clearTimeout(timer);+ reject(signal!.reason);+ };+ const timer = setTimeout(() => {+ signal?.removeEventListener('abort', onAbort);+ resolve();+ }, ms);+ signal?.addEventListener('abort', onAbort, { once: true });+ });++/** `lobehub.generations`, plus `wait()` to poll a generation until it is final. */+export class GenerationsResource extends Generations {+ /**+ * Poll `GET /generations/{id}` until the generation succeeded or failed, and+ * return its final state. A failed generation resolves too — check `status`+ * (and `error`). Request errors (404, 403, …) reject with `LobeHubAPIError`;+ * running out of `timeout` rejects with `GenerationWaitTimeoutError`.+ *+ * ```ts+ * const { data } = await lobehub.videos.generate({ body: { model, prompt, provider } });+ * const video = await lobehub.generations.wait(data!.data.generations[0].id);+ * if (video.status === 'success') console.log(video.asset?.url);+ * ```+ */+ async wait(id: string, options: GenerationWaitOptions = {}): Promise<Generation> {+ const {+ onPoll,+ pollInterval = DEFAULT_GENERATION_POLL_INTERVAL,+ signal,+ timeout = DEFAULT_GENERATION_WAIT_TIMEOUT,+ } = options;+ const deadline = Date.now() + timeout;+ // The deadline also aborts a status request in flight (and its retries),+ // so a slow or stalled request cannot outlive `timeout`.+ const expiry = new AbortController();+ const timer = setTimeout(() => expiry.abort(), timeout);+ const waitSignal = signal ? anySignal([signal, expiry.signal]) : expiry.signal;+ let last: Generation | undefined;++ try {+ for (;;) {+ const { data } = await this.get({+ path: { id },+ signal: waitSignal,+ throwOnError: true,+ timeout: Math.max(1, deadline - Date.now()),+ });+ last = data.data;+ onPoll?.(last);+ if (TERMINAL_GENERATION_STATUSES.includes(last.status)) return last;++ const remaining = deadline - Date.now();+ if (remaining <= 0) throw new GenerationWaitTimeoutError(id, timeout, last);+ await sleep(Math.min(pollInterval, remaining), waitSignal);+ }+ } catch (error) {+ // A caller's own abort keeps its reason; running out of time is a timeout.+ if (!signal?.aborted && (expiry.signal.aborted || Date.now() >= deadline)) {+ if (error instanceof GenerationWaitTimeoutError) throw error;+ throw new GenerationWaitTimeoutError(id, timeout, last);+ }+ throw error;+ } finally {+ clearTimeout(timer);+ }+ }+}diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.tsindex 796a5ba9c7f..a1e02f821e3 100644--- a/packages/sdk/src/index.ts+++ b/packages/sdk/src/index.ts@@ -13,6 +13,14 @@ export { LobeHubAPIError, LobeHubConnectionError, LobeHubTimeoutError } from './export type { Client, Config } from './generated/client';export { LobeHub } from './generated/sdk.gen';export type * from './generated/types.gen';+export type { GenerationWaitOptions } from './generations';+export {+ DEFAULT_GENERATION_POLL_INTERVAL,+ DEFAULT_GENERATION_WAIT_TIMEOUT,+ GenerationsResource,+ GenerationWaitTimeoutError,+ TERMINAL_GENERATION_STATUSES,+} from './generations';export type { PageItem, PageOf, PaginateOptions } from './pagination';export type { ServerSentEvent } from './streaming';export { parseServerSentEvents, ResponseStream } from './streaming';diff --git a/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.test.ts b/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.test.tsindex 3420c1494e7..a3a237491cf 100644--- a/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.test.ts+++ b/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.test.ts@@ -33,4 +33,11 @@ describe('toggleScopeSelection', () => {'agent:read',]);});++ it('selects generation read together with generation write', () => {+ expect(sorted(toggleScopeSelection([], 'generation:write', true))).toEqual([+ 'generation:read',+ 'generation:write',+ ]);+ });});diff --git a/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsx b/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsxindex a52980acba0..5ca833d92fd 100644--- a/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsx+++ b/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsx@@ -68,7 +68,16 @@ const styles = stylex.create({* accounts — managing the agent's accounts must not imply that.*/type ScopeGroupKey =- 'agent' | 'chat' | 'file' | 'knowledge' | 'mcp' | 'model' | 'usage' | 'user' | 'workspace';+ | 'agent'+ | 'chat'+ | 'file'+ | 'generation'+ | 'knowledge'+ | 'mcp'+ | 'model'+ | 'usage'+ | 'user'+ | 'workspace';/*** Labels an extra scope can carry. Kept as literals (not `string`) so the@@ -120,6 +129,12 @@ const SCOPE_GROUPS: readonly ScopeGroup[] = [},},{ key: 'file', label: 'apikey.scopes.groups.file', read: 'file:read', write: 'file:write' },+ {+ key: 'generation',+ label: 'apikey.scopes.groups.generation',+ read: 'generation:read',+ write: 'generation:write',+ },{key: 'knowledge',label: 'apikey.scopes.groups.knowledge',