38 KiB
API Reference
Last source audit: 2026-05-12, based on git commit 8ee86a9.
All routes are Next.js App Router route handlers under src/app/api/**/route.ts.
Auth Conventions
- Bearer token:
Authorization: Bearer <token>. - Token creation and verification:
src/lib/session-auth.ts. - Authenticated user helpers:
getAuthenticatedUser(request)getAuthenticatedUserId(request)requireAdminUser(request)requireAdmin(request)fromsrc/lib/admin-auth.ts
- Internal generation requests use header
x-miaojing-generation-internal, generated bysrc/lib/server-api-config.ts.
Response Conventions
- Success responses are JSON unless the route explicitly streams/downloads a file.
- Error responses usually use
{ "error": "message" }with an HTTP status. - Admin-only routes return 401 when not logged in and 403 when role is not
adminorenterprise_admin.
Public/System Routes
| Method | Path | Auth | Source | Purpose |
|---|---|---|---|---|
| GET | /api/health |
Public | src/app/api/health/route.ts |
Health check. |
| GET | /api/site-stats |
Public | src/app/api/site-stats/route.ts |
Read total visits. |
| POST | /api/site-stats |
Public | src/app/api/site-stats/route.ts |
Increment visits. |
| GET | /api/site-config |
Public | src/app/api/site-config/route.ts |
Read site config, policy Markdown, filing, membership flag, and redeem-code mall URL. |
| PUT | /api/site-config |
Admin | src/app/api/site-config/route.ts |
Update site config, redeem-code mall URL, and upload logo/favicon data URLs. |
| GET | /api/announcements |
Public | src/app/api/announcements/route.ts |
List announcements. |
| POST | /api/announcements |
Admin | src/app/api/announcements/route.ts |
Create announcement. Body: title, content, startDate, endDate, enabled. |
| PUT | /api/announcements |
Admin | src/app/api/announcements/route.ts |
Update announcement. Body includes id and changed fields. |
| DELETE | /api/announcements?id=... |
Admin | src/app/api/announcements/route.ts |
Delete announcement. |
| GET | /api/model-config |
Public, optional bearer token | src/app/api/model-config/route.ts |
Read managed provider/model configuration for clients. System APIs are filtered to active platform-default models allowed for the current user's membership tier; anonymous users are treated as free. |
| GET | /api/style-presets |
Public | src/app/api/style-presets/route.ts |
Returns active image style presets from image_style_presets, sorted by usage count. |
| GET | /api/local-storage/[...path] |
Public by URL | src/app/api/local-storage/[...path]/route.ts |
Serve storage object by key. Generated work images/videos and their generated/gallery/work thumbnails are watermarked server-side before display, using src/lib/media-watermark*.ts; object-backed generated originals must not redirect raw to object storage. When a generated image original has an existing local works.thumbnail_url, display requests may 302 to that thumbnail first and then watermark the thumbnail, keeping page loads fast while preserving the stable original URL for fullscreen/download actions. Thumbnail keys under thumbnails/... are served from local disk with long immutable browser cache headers; non-generated object-backed originals can return a short-lived signed object-storage redirect when configured. Video frame thumbnails are WEBP files, while fallback SVG video thumbnails under thumbnails/.../*.svg may be rasterized when watermarked. The public URL shape remains stable across migration. |
| GET | /api/download?url=...&filename=... |
Public by URL, optional bearer/downloadToken | src/app/api/download/route.ts |
Download proxy for remote, same-origin, and /api/local-storage/* URLs, including object-backed storage keys. Generated local-storage media returns watermarked bytes by default; raw generated media is allowed only after the route authenticates an admin role or a user whose profiles.watermark_disabled=true. Add disposition=inline or inline=1 when the proxy is used as an image/video preview source instead of a forced download. |
Auth And Account Routes
| Method | Path | Auth | Source | Request | Response |
|---|---|---|---|---|---|
| POST | /api/auth/login |
Public | src/app/api/auth/login/route.ts |
account or email or phone, password, optional adminOnly |
User profile data and session token. |
| POST | /api/auth/register |
Public | src/app/api/auth/register/route.ts |
email, password, nickname as login username, phone, inviteCode, emailCode, acceptedTerms |
Created profile/session flow. New normal users receive a random Chinese display nickname and default 3D cartoon avatar. |
| GET | /api/auth/admin-exists |
Public | src/app/api/auth/admin-exists/route.ts |
None | Whether an admin profile exists. |
| POST | /api/auth/test-api |
Public/auth context depends caller | src/app/api/auth/test-api/route.ts |
Provider/API config | Tests upstream API. |
| POST | /api/auth/fetch-models |
Public/auth context depends caller | src/app/api/auth/fetch-models/route.ts |
Endpoint/API key | Fetch model list from provider. |
| GET | /api/profile |
User | src/app/api/profile/route.ts |
None | { profile }, including watermark_disabled for the user's no-watermark download preference. |
| PUT | /api/profile |
User | src/app/api/profile/route.ts |
email, username, displayNickname/nickname, phone, avatarUrl, optional watermarkDisabled, password fields |
Updated profile. username remains usable for login; display nickname is returned as nickname for UI and gallery display. watermarkDisabled=true is accepted only for members/admins as a self-service preference; free users cannot self-enable it, and an accidental/old-client false payload must not clear an admin-granted per-user authorization. The flag controls download-original entitlement, not platform display. |
| PUT | /api/profile/theme |
User | src/app/api/profile/theme/route.ts |
theme |
{ success, preferred_theme }. |
| GET | /api/credit-transactions |
User | src/app/api/credit-transactions/route.ts |
Optional limit |
Latest user credit transaction records as { records }, used by the profile credits tab. |
| GET | /api/invitations/me |
User | src/app/api/invitations/me/route.ts |
None | Returns the current user's stable inviteCode plus invitee records for the profile credits tab. Creates profiles.invite_code if missing. |
| POST | /api/redeem-codes/redeem |
User | src/app/api/redeem-codes/redeem/route.ts |
{ code } |
Atomically redeems one active unused redeem code. Credit codes increment profiles.credits_balance, mark the code used, write a credit_transactions row of type redeem, and return the new credit balance. Membership codes update profiles.membership_tier, extend membership_expires_at by the configured day/month/year duration, mark the code used, and return the membership result. |
| GET | /api/user-api-keys |
User | src/app/api/user-api-keys/route.ts |
None | { keys }, with previews only. Rows may include manifestPath, which points to that key/model's independent API Manifest file. |
| POST | /api/user-api-keys |
User | src/app/api/user-api-keys/route.ts |
Single key or { keys: [...] }; fields provider, supplierName, apiUrl, modelName, apiKey, type, isActive, optional manifestPath |
Saved keys. Updating an imported key preserves its existing manifest_path when omitted. |
| PUT | /api/user-api-keys |
User | src/app/api/user-api-keys/route.ts |
Same as POST | Saved keys. |
| DELETE | /api/user-api-keys?id=... |
User | src/app/api/user-api-keys/route.ts |
Query id |
{ success: true }. |
| POST | /api/user-api-keys/smart-import |
User | src/app/api/user-api-keys/smart-import/route.ts |
{ configText }, containing either { customProviders, profiles } or a single provider Manifest |
Creates one user_api_keys row per profile/model and writes a separate user-api-manifests/<userId>/<keyId>.json file. The imported row uses the Manifest provider name as the editable provider/supplier display value and resolves apiUrl from profile.baseUrl + submit.path for synchronous endpoints. The route rejects configs that do not contain enough data to resolve a relay API request URL. Optional profile.capabilities is returned to the client and filters selected-model image options. API Key is intentionally left blank with preview 待填写 until the user edits the row. |
Email Routes
| Method | Path | Auth | Source | Purpose |
|---|---|---|---|---|
| POST | /api/email/send-register-code |
Public | src/app/api/email/send-register-code/route.ts |
Send registration verification code. |
| POST | /api/email/send-reset-code |
Public | src/app/api/email/send-reset-code/route.ts |
Send password reset code. |
| POST | /api/email/reset-password |
Public | src/app/api/email/reset-password/route.ts |
Reset password with verification code. |
| POST | /api/email/send-profile-code |
User | src/app/api/email/send-profile-code/route.ts |
Send profile email-binding code. |
| POST | /api/email/verify-profile |
User | src/app/api/email/verify-profile/route.ts |
Verify profile email code. |
| POST | /api/email/send-notification |
Internal/admin-oriented | src/app/api/email/send-notification/route.ts |
Send notification email. |
All email sends route through src/lib/email-service.ts, which renders HTML and plain-text multipart messages and sends them via the configured SMTP server. Keep MIME body encoding standards-compliant: base64 body parts must be folded to safe line lengths and both text/plain and text/html parts should be non-empty, otherwise SMTP can accept the message while some mailbox clients render a blank email.
Generation Routes
| Method | Path | Auth | Source | Request | Response/Side Effects |
|---|---|---|---|---|---|
| POST | /api/generation-jobs |
User | src/app/api/generation-jobs/route.ts |
`{ type: "image" | "video" |
| GET | /api/generation-jobs/[id] |
User/admin | src/app/api/generation-jobs/[id]/route.ts |
Path UUID | Job status/result/error/progress. Owner or admin only. Status may be queued, running, succeeded, failed, or cancelled. The create pages use this endpoint to resume jobs after refresh, auth change, or a new tab; client-side pending job ids also use it to recover terminal results/errors that happened while the browser was closed. |
| PATCH | /api/generation-jobs/[id] |
User/admin | src/app/api/generation-jobs/[id]/route.ts |
Path UUID plus { action: "cancel" } |
Owner or admin can cancel a queued/running job. The route marks the row cancelled, clears payload/result, writes a cancellation progress payload and finished_at, and returns the updated job row with jobId; if the job already settled it returns the existing row. Workers re-check that the job is still running before charging credits, persisting history, or writing success/failure so late upstream responses cannot resurrect a cancelled job. |
Admin Invitation Routes
| Method | Path | Auth | Source | Request | Response |
|---|---|---|---|---|---|
| GET | /api/admin/invitations |
Admin | src/app/api/admin/invitations/route.ts |
Optional search, page, pageSize |
Long-term invitation records joining inviter and invitee profile details. |
| POST | /api/generate/image |
Trusted internal or resolved user/system API context | src/app/api/generate/image/route.ts |
Image generation payload; supports prompt, negative prompt, reference images (image plus extraImages), optional referenceImageAnnotations, model/system/custom API config, aspect/size/resolution/count/quality. |
Calls SDK or OpenAI/New API-compatible endpoint, persists original images to object storage and local WEBP thumbnails to thumbnails/generated/images, returns images original URLs plus thumbnails, thumbnailUrls, and dimensions { [originalUrl]: { width, height } }, updates job progress when headers include job ID. When referenceImageAnnotations is present, src/lib/reference-image-prompt.ts adds a model-readable @参考图N mapping block to the upstream prompt before style prompts and Manifest execution. |
| POST | /api/generate/video |
Trusted internal or resolved user/system API context | src/app/api/generate/video/route.ts |
Video generation payload; supports prompt, reference images (image, images, extraImages), optional referenceImageAnnotations, model/system/custom API config, ratio/duration/fps-like params. |
Calls SDK or Manifest/custom endpoint, polls async Manifest providers such as 元界 media tasks, then persists generated video media as object-backed /api/local-storage/generated/videos/... URLs when object storage is configured. When referenceImageAnnotations is present, src/lib/reference-image-prompt.ts adds a model-readable @参考图N mapping block to the upstream prompt before Manifest/custom/SDK execution. |
| POST | /api/generate/reverse-prompt |
Uses supplied/resolved API config; Bearer token required when resolving user custom or gated system API IDs | src/app/api/generate/reverse-prompt/route.ts |
image, outputMode, language, optional customApiConfig/system/custom IDs |
Returns prompt fields and may persist reference image. The create-panel caller must forward the stored access token in Authorization because server-side API resolution cannot read browser localStorage. When the input image is a data URL, the route persists it under reverse-prompt/reference-images/... and sends the public /api/local-storage/... URL upstream when available so the multimodal model sees a normal fetchable image URL instead of a raw upload blob. This route sends a multimodal chat/completions payload with image_url, so 524 errors here reflect multimodal upstream latency/capability rather than image-generation sync behavior. |
| POST | /api/generate/suggest-prompt |
Uses supplied/resolved API config | src/app/api/generate/suggest-prompt/route.ts |
prompt, optional customApiConfig, systemPrefix |
Returns optimized prompt and optional negativePrompt. This route also uses a multimodal chat/completions path, so 524 should be interpreted as a multimodal upstream timeout. |
Important generation helpers:
src/lib/generation-job-client.ts: frontend create/poll helper.src/lib/generation-job-worker.ts: queued job processor.src/lib/generation-job-runner.ts: internal call into generate routes.src/lib/generation-job-estimates.ts: ETA/progress schema and estimates.src/lib/server-api-config.ts: resolvescustomApiKeyIdandsystemApiId.src/lib/custom-api-fetch.ts: upstream request/retry/error parsing.src/lib/user-api-manifest.tsandsrc/lib/user-api-manifest-executor.ts: parse/import per-key user and system API Manifests and execute the selected model's JSON/multipart/poll mapping before falling back to legacy custom API compatibility. User Manifest files are never merged per user; the chosencustomApiKeyIdcontrols the exactmanifest_path. Admin system imports use separatesystem-api-manifests/<systemApiId>.jsonfiles and generation resolves them from the selectedsystemApiId.pnpm run migration:checkrunsscripts/migration-integrity-check.mjsas a read-only production migration gate. It checks auth/profile parity, password hash presence, user-owned table references, API key preview metadata, same-user work dedupe state, required schema columns, and/api/local-storage/*URL availability without printing secret values. The default probe base URL is the production web porthttp://127.0.0.1:8000; override withMIGRATION_CHECK_BASE_URLwhen checking another runtime. Storage URL probes are bounded by timeout/concurrency helpers so one slow media URL is counted as a blocker instead of crashing the whole check.pnpm run rainyun:ros-prepare -- --createrunsscripts/rainyun-ros-prepare.mjsagainst Rainyun's ROS control-plane API (POST https://api.v2.rainyun.com/product/ros/bucket, body{ bucket_name, instance_id },x-api-keyheader). It writes standard S3-compatibleOBJECT_STORAGE_*values to.env.rainyun-object.generated; secrets are redacted from console output.
Creation History And Gallery
| Method | Path | Auth | Source | Request | Response/Side Effects |
|---|---|---|---|---|---|
| GET | /api/creation-history |
User | src/app/api/creation-history/route.ts |
Optional query `mode=text2img | img2img |
| POST | /api/creation-history |
User | src/app/api/creation-history/route.ts |
Single record or { records: [...] }; image records may include thumbnailUrl, width, height, referenceImage, and referenceImages |
Inserts/deduplicates completed works into works, storing thumbnail_url and dimensions when supplied or generating thumbnails for image works and video works without thumbnails. Data URL or remote reference images are persisted into stable /api/local-storage/works/references/... URLs with local thumbnails under thumbnails/works/references; the route writes params.referenceImages and params.referenceImageThumbnails, and can patch an existing same-URL row whose first insert came from the background worker before frontend reference metadata arrived. Imported/local records are only inserted as public when both published and publishedAt are present, so stale local published flags do not create or block gallery state. |
| DELETE | /api/creation-history?id=... |
User | src/app/api/creation-history/route.ts |
Optional id; omit to delete all user history |
Deletes user's private history rows by id and user_id. Creation detail deletion waits for this server delete before refreshing local history. |
| GET | /api/gallery |
Public | src/app/api/gallery/route.ts, src/lib/gallery-response.ts |
Query `type=image | video, category=text2img |
| DELETE | /api/gallery |
Admin | src/app/api/gallery/route.ts |
Query id or body { ids: [...] } |
Unpublishes up to 100 works by setting is_public=false. |
| POST | /api/gallery/publish |
User | src/app/api/gallery/publish/route.ts, src/lib/gallery-publish-media.ts |
Work metadata, resultUrl, optional thumbnail/reference/model fields, optional referenceImage/referenceImages plus matching params.referenceImage/params.referenceImages |
Reuses stable /api/local-storage/... image and video originals instead of synchronously copying object-backed generated media during share. External image/video URLs are still copied into object-backed gallery storage before insertion. For image-to-image and image-to-video shares, data URL or remote reference images are persisted under stable gallery/references/... local-storage URLs and stored in works.params.referenceImage/referenceImages; stable /api/local-storage/... references are reused as-is. The response includes referenceImages so clients can keep local published state aligned. Existing image thumbnails are reused; gallery/history reads can lazily backfill missing or stale thumbnails. Video publish thumbnails prefer WEBP frame extraction through ffmpeg-static; a client-provided thumbnail is copied only after frame extraction fails. If media preparation fails, the route returns an error instead of inserting a public row that /api/gallery will filter out. Clients should show success and mark local history as shared only after this route returns 2xx. |
| GET | /api/admin/gallery/works |
Admin | src/app/api/admin/gallery/works/route.ts |
Query q, `type=all |
image |
| PUT | /api/admin/gallery/prompt |
Admin | src/app/api/admin/gallery/prompt/route.ts, src/lib/admin-gallery-prompt-service.ts |
{ workId, prompt, emailSubject, emailBody, reasonKey } |
Sends the author notification email first, then updates works.prompt only after email success, and writes a platform log without storing full prompt text. Missing/invalid author email, unchanged prompt, non-public work, or email failure blocks the update. |
Admin Routes
All routes in this section require admin unless noted.
| Method | Path | Source | Purpose |
|---|---|---|---|
| GET | /api/admin/dashboard |
src/app/api/admin/dashboard/route.ts |
Console dashboard aggregate stats and recent activity. |
| GET | /api/admin/stats |
src/app/api/admin/stats/route.ts |
Additional admin stats. |
| GET/PUT/DELETE | /api/admin/users |
src/app/api/admin/users/route.ts |
List/update/delete users. GET returns watermark_disabled; PUT accepts profile fields, watermarkDisabled/watermark_disabled, and newPassword. newPassword is admin-only and upserts auth.users.password_hash with PostgreSQL crypt(..., gen_salt('bf')) so the user can immediately log in with the reset password. |
| POST | /api/admin/clear-users |
src/app/api/admin/clear-users/route.ts |
Dangerous user cleanup controlled by env switch. |
| GET/POST/PUT | /api/admin/orders |
src/app/api/admin/orders/route.ts |
List/create/update orders. |
| GET/POST/PUT/DELETE | /api/admin/redeem-codes |
src/app/api/admin/redeem-codes/route.ts |
Admin redeem-code management. GET lists codes by status/search, POST generates 1-500 unique single-use credit or membership codes, PUT enables/disables unused codes, and DELETE removes unused codes. Membership-code payloads include membershipTier, membershipDurationValue, and membershipDurationUnit (day, month, year). The redeem-code management UI also saves the shared external mall URL through /api/site-config as redeemCodeMallUrl. |
| GET/PUT | /api/admin/payment-methods |
src/app/api/admin/payment-methods/route.ts |
Payment config. |
| GET/POST/PUT/DELETE | /api/admin/providers |
src/app/api/admin/providers/route.ts |
Provider registry CRUD. All methods require admin bearer auth. |
| GET/POST/PUT/DELETE | /api/admin/system-apis |
src/app/api/admin/system-apis/route.ts |
System API config CRUD with encrypted keys, pricing metadata, platform-default visibility, allowed membership tiers, default-model polling fields pollingMode/pollingOrder, and video entry usage modes videoUsageModes. Successful system-default image/video generation jobs charge user credits from this selected row's pricing through src/lib/generation-credit-service.ts; queued/running system-default jobs are counted during new-job balance preflight, and failed jobs do not write consume transactions. |
| POST | /api/admin/system-apis/smart-import |
src/app/api/admin/system-apis/smart-import/route.ts |
Admin-only intelligent Manifest import. Creates one global system_api_configs row per imported profile/model, resolves the visible API request URL from the Manifest profile/provider, rejects configs without a resolvable relay API request URL, writes system-api-manifests/<systemApiId>.json, and leaves API Key empty for admin review. Optional profile.capabilities is returned through system model config for selected-model image option filtering. Imported rows also carry platform-default visibility, membership-tier allowlist, and default polling fields. |
| GET | /api/admin/system-apis/agnes-capabilities |
src/app/api/admin/system-apis/agnes-capabilities/route.ts |
Admin-only Agnes AI built-in template preview for the system-default-model flow. Returns capabilitiesText, image templates from src/lib/agnes-model-templates.ts, video templates, and text templates. It covers Agnes Image 2.1 Flash, Agnes Image 2.0 Flash, Agnes Video V2.0, Agnes 2.0 Flash, and Agnes 1.5 Flash without calling upstream. |
| POST | /api/admin/system-apis/agnes-capabilities |
src/app/api/admin/system-apis/agnes-capabilities/route.ts |
Admin-only Agnes AI built-in installer. { syncImageModels, syncVideoModels, syncTextModels } resets only matching provider = 'Agnes AI' rows by media type. Rows are installed as inactive free system default templates (billing_mode = free, 0 credits) with empty API Key. Image/video rows also get independent system-api-manifests/<systemApiId>.json files. Text rows use OpenAI-compatible chat/completions directly and do not need a Manifest. Admins must edit rows to fill the API Key and enable them before users can generate. |
| GET | /api/admin/system-apis/yuanjie-capabilities |
src/app/api/admin/system-apis/yuanjie-capabilities/route.ts |
Admin-only 元界 AI built-in image/video template preview retained for the system-default-model template path, not for the 智能配置 API UI. Returns capabilitiesText, image templates from src/lib/yuanjie-image-model-templates.ts, and video templates from src/lib/yuanjie-video-model-templates.ts; it does not call 元界 /v1/skills or /v1/skills/guide. |
| POST | /api/admin/system-apis/yuanjie-capabilities |
src/app/api/admin/system-apis/yuanjie-capabilities/route.ts |
Admin-only 元界 AI built-in installer retained for system-default-model template management, not for the generic smart import UI. { syncModels: true } resets only provider = '元界 AI' AND type = 'image' rows and installs 17 inactive image rows. { syncVideoModels: true } resets only provider = '元界 AI' AND type = 'video' rows and installs inactive video rows with videoUsageModes. Rows have no API Key by default; admins must edit each model to set Key, pricing, visibility/member scope, polling, usage mode, and enable it before users can generate. |
| GET/POST | /api/admin/system-apis/yuanjie-pricing |
src/app/api/admin/system-apis/yuanjie-pricing/route.ts |
Admin-only manual 元界 AI pricing sync. GET previews built-in pricing targets from src/lib/yuanjie-pricing-sync.ts. POST updates only existing 元界 image/video system API rows by model_name, matching compatible provider spellings such as 元界 AI/元界AI plus yuanjie-* model groups, and synchronizes billing_mode plus the 元界计费同步 price_note while preserving administrator-entered numeric prices and non-元界 providers such as mozheAPI. Optional body `{ type: "image" |
| GET/POST/PUT/DELETE | /api/admin/model-recommendations |
src/app/api/admin/model-recommendations/route.ts |
Managed model recommendations. All methods require admin bearer auth. |
| GET/DELETE | /api/admin/generation-jobs |
src/app/api/admin/generation-jobs/route.ts |
Admin task listing and deletion. |
| GET | /api/admin/gallery/works |
src/app/api/admin/gallery/works/route.ts |
Admin public gallery work listing for prompt moderation. |
| PUT | /api/admin/gallery/prompt |
src/app/api/admin/gallery/prompt/route.ts |
Admin prompt moderation endpoint. Requires email notification success before updating works.prompt. |
| GET | /api/admin/data-export |
src/app/api/admin/data-export/route.ts |
Export business data plus _media entries for storage assets referenced by works and site config. _meta reports media count/bytes/missing/skipped. |
| POST | /api/admin/data-import |
src/app/api/admin/data-import/route.ts |
Import business data. Accepts optional _media; restores media to sha-based keys, remaps users/custom API keys/works, imports in a transaction with per-row savepoints, preserves password hashes/encrypted secrets, and dedupes works by URL/source URL/media SHA only inside the same user_id. |
| GET/PUT/POST | /api/admin/email-settings |
src/app/api/admin/email-settings/route.ts |
Read/update/test email settings. |
| GET | /api/admin/email-recipients |
src/app/api/admin/email-recipients/route.ts |
Email recipient list. |
| POST | /api/admin/send-email |
src/app/api/admin/send-email/route.ts |
Send admin email. |
| GET/PUT | /api/admin/logs |
src/app/api/admin/logs/route.ts |
Admin system log listing and retention settings. GET supports type, level, user, keyword, startTime, endTime, page, and pageSize filters and returns logs plus retention settings. PUT updates the retention days, cleans expired rows, and writes a platform log. |
| GET/POST | /api/admin/upgrade |
src/app/api/admin/upgrade/route.ts |
Read upgrade runtime/status/history; upload/start dry run or upgrade package. New deployable work should be classified against this path: static/public asset-only payloads may be hot-update candidates after preflight, while source/API/server/dependency/schema/env/runtime/script changes are cold-update candidates. |
Persistence Tables Mentioned By APIs
Primary SQL tables touched directly in API routes include:
profilesauth.usersworkscredit_transactionsredeem_codesordersuser_api_keyssite_configsite_statsannouncementsgeneration_jobsapi_providerssystem_api_configsplatform_logs
src/storage/database/shared/schema.ts contains a Drizzle snapshot of core tables, while several runtime APIs add compatibility columns/tables with CREATE TABLE IF NOT EXISTS or ALTER TABLE ... ADD COLUMN IF NOT EXISTS.
user_api_keys.manifest_path is an optional local-storage key for an imported JSON Manifest. The storage convention is user-api-manifests/<userId>/<keyId>.json, so even the same user can have multiple isolated request configs. Generation must load the manifest linked to the selected model/key row instead of looking up a user-level shared config.
system_api_configs.polling_mode and system_api_configs.polling_order control admin default-model supplier fallback for image generation. system_api_configs.video_usage_modes controls whether a video model appears in 文生视频, 图生视频, or both creation entries. /api/model-config deduplicates default system rows by media type plus admin display name (system_api_configs.name) for clients, while /api/generate/image expands the selected row back into allowed supplier candidates with the same media type and display name. System image candidates retry stream-timeout 524 responses once with stream:false, and shared custom API transport retries 502/503/504 once before surfacing a concise gateway error. model_name stays provider-specific and is used as the upstream request model value.
site_config.image_composition_skill_enabled controls the built-in 100 Layout Compositions image composition skill. /api/site-config returns and updates it as imageCompositionSkillEnabled, and /api/generate/image reads it through src/lib/layout-composition-skill.ts before calling SDK, Manifest, custom API, or system default polling providers. The skill source is nevertoday/100-layout-compositions under CC BY 4.0; prompt injection must preserve attribution internally and avoid adding literal text/logo/poster elements.
redeem_codes stores admin-generated single-use credit and membership redemption codes. Runtime code generation and redemption go through src/lib/redeem-code-service.ts; redemption must lock both the code row and profile row in one transaction before updating profiles.credits_balance for credit codes or profiles.membership_tier/membership_expires_at for membership codes. Credit-code redemptions also insert a credit_transactions record.
src/lib/yuanjie-image-model-templates.ts is the canonical source for built-in 元界 AI image model definitions. It maps each documented model to its Manifest request body and stores capability flags so the create page only shows the documented aspect ratio, resolution, image format, and quality controls for the selected model. For 元界 GPT Image 2 / GPT Image 2 官转 and other size-enum models, the create page hides the separate aspect-ratio control and shows the documented pixel size values as the resolution list. 元界媒体轮询 uses is_final === true as the final-state gate and state for success/failure, matching the documented media task contract.
src/lib/yuanjie-video-model-templates.ts is the canonical source for built-in 元界 AI video model definitions from the local video docs. It maps each model to a Manifest request body, records whether the model supports 文生视频 and/or 图生视频, and stores aspect ratio, resolution, duration, and quality/mode capability options for the selected system video model. Video submit bodies must follow 元界 media docs as model, prompt, and params; HappyHorse text-to-video maps UI ratio to params.ratio, resolution to params.resolution, duration to params.duration, and reads async task IDs from output.task_id. Video templates use the documented is_final plus state polling rule.
src/lib/yuanjie-pricing-sync.ts is the canonical source for manual 元界 AI pricing metadata sync. It derives billing modes from the built-in image/video templates and local docs: image models default to fixed per-use pricing, duration-sensitive video models sync to duration, Seedance token-billed video models sync to token, and special variable-cost video models sync to ratio with a warning note. The sync is manual from the admin system-default-model page and only updates existing 元界 rows, including legacy provider spellings such as 元界AI; update SQL still includes a 元界 provider/model-group guard so mozheAPI rows cannot be touched by the sync.
Yuanjie Manifest references use $inputImages.urls for provider-facing JSON fields. For image-to-image, /api/generate/image reads the primary image plus extraImages and sends all references to src/lib/user-api-manifest-executor.ts; for image-to-video, /api/generate/video reads image, images, and extraImages before Manifest execution. The executor uploads data URL references into storage before rendering Yuanjie params.images, top-level images, reference_urls, or base64Array. referenceImageAnnotations is an API payload field rather than a Manifest variable; image/video routes use src/lib/reference-image-prompt.ts to merge @参考图N token mappings into the upstream prompt so existing Manifest templates receive the mapping through $prompt. Yuanjie video templates keep documented model-specific fields inside src/lib/yuanjie-video-model-templates.ts, including first/last reference fields and mode fields such as input_reference, reference_urls, img_url, image_tail, ratio, size, and generation_mode.
src/lib/agnes-model-templates.ts is the canonical source for Agnes AI built-in free templates. Agnes Video V2.0 uses Manifest POST /v1/videos plus /agnesapi polling, but duration must be sent as num_frames rather than duration. /api/generate/video maps the currently stable Agnes UI durations 3/5/10 seconds to 24fps frame counts 81/121/241 and sends frame_rate: 24; 18 seconds is intentionally hidden and rejected because production evidence showed the upstream task moves past creation but returns failed for that length. In image-to-video mode the top-level image is the provider's starting/first frame field, not a generic non-first-frame reference slot. The Manifest executor keeps Agnes-style total polling budgets separate from per-request submit/poll timeouts, so one slow or transiently failed poll request does not end the whole async video job before the full video budget expires.
src/lib/yuanjie-system-manifest.ts provides the runtime bridge for existing admin system API rows that were created before Manifest-backed Yuanjie templates. It exposes built-in capabilities to /api/model-config even when manifest_path is empty, and when a known 元界 system API is resolved directly or as a default-model polling candidate it writes missing or stale system-api-manifests/<systemApiId>.json, normalizes api_url back to the 元界 base URL, and preserves the encrypted API key and administrator pricing.
Profile naming convention: profiles.nickname is the stable login username; profiles.display_nickname is the public nickname shown in navbar/gallery/profile UI. APIs return username plus nickname/display_nickname so older clients can keep reading nickname as the display name.