cmvr-visual/docs/api-contract.md

71 lines
6.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Shared API contract
All endpoints use `/api`. JSON errors: `{detail:{code,message}}`; normal FastAPI validation errors may additionally contain field locations. Session cookie `cmvr_session` is HttpOnly, same-origin. POST/PATCH/DELETE except login need `X-CSRF-Token` from auth response. Never expose inference keys or absolute server paths.
## Authentication
- POST `/auth/login` `{username,password}` → `{user:{id,username,display_name,role},csrf_token}` plus session cookie.
- GET `/auth/me` → same shape; 401 when signed out.
- POST `/auth/logout` → 204; close SSE on frontend.
- Admin POST `/auth/users` `{username,display_name,password}` → user.
## Capabilities and resources
- GET `/capabilities` → `{items:Capability[],scheduler:Scheduler}`.
- GET `/system/status` → `{inference_online:boolean,scheduler:Scheduler,models:Capability[]}`.
- Capability: `{task_type,label,model,available,input_types:string[],defaults:object,constraints:object,description:string}`.
- Scheduler: `{available:boolean,state:string,reason:string|null,gpus:[{index,name,busy:boolean,eligible:boolean,free_gib:number|null}],updated_at:string|null}`. No PID or user identity.
- Types: `image.generate`, `video.generate`, `defect.generate`, `audio.transcribe`, `math.solve`, `media.structure`, `video.compose`, optional `audio.speech` (only available when a real provider is configured).
## Assets
- POST `/assets` multipart field `file`, optional `name` → Asset.
- GET `/assets?page=1&page_size=24&kind=&q=&tag=` → `{items:Asset[],total,page,page_size}`.
- GET `/assets/{id}` → Asset.
- PATCH `/assets/{id}` `{name?,tags?:string[],favorite?:boolean}` → Asset.
- DELETE `/assets/{id}` → 204; retain referenced physical input.
- GET `/assets/{id}/content` inline, Range supported; `?download=1` attachment.
- GET `/assets/{id}/thumbnail` authenticated image preview (fallback image content when no separate thumbnail).
- Asset: `{id,name,kind:'image'|'video'|'audio'|'text'|'json',mime_type,size_bytes,width:null|number,height:null|number,duration_seconds:null|number,preview_url,thumbnail_url:null|string,download_url,source_job_id:null|string,origin:'upload'|'generated',tags:string[],favorite:boolean,created_at:string}`.
## Jobs
- POST `/jobs`, optional `Idempotency-Key`, body `{task_type,input:{prompt?,negative_prompt?,image_asset_id?,audio_asset_id?,asset_id?,asset_ids?:string[]},parameters:object,count?:1..4,scheduled_at?:ISO8601|null}` → `{jobs:Job[]}`. Batch only for image/defect; each gets its own serial upstream job. Composition clip order and trims live in `parameters.clips:[{asset_id,start_seconds?,end_seconds?}]`, optional `audio_asset_id`, `subtitles:[{start,end,text}]`, width/height/fps. Server resolves owned assets only.
- GET `/jobs?page=1&page_size=24&task_type=&state=` → `{items:Job[],total,page,page_size,cursor:number}`.
- GET `/jobs/{id}` → Job.
- POST `/jobs/{id}/cancel` → Job, cancellation may remain pending.
- POST `/jobs/{id}/retry` → `{jobs:Job[]}` (user requested new generation, new business ID).
- Job: `{id,task_type,state,phase,version,prompt:string,parameters:object,input_asset_ids:string[],result_assets:Asset[],result:object|null,progress:number|null,queue_position:number|null,upstream_id:string|null,attempt_count:number,preemptions:number,last_preempted_reason:string|null,cancel_requested:boolean,error:null|{code,message,retriable},sync_warning:string|null,created_at:string,scheduled_at:string|null,started_at:string|null,finished_at:string|null}`.
- States: `scheduled,submitting,queued,running,collecting,cancelling,succeeded,failed,cancelled,timed_out`. Remote sync failures do not invent terminal failures; set sync_warning. Requeue is the same job ID and may go running→queued.
- Image defaults1024²/50 steps; video defaults1280×704/121frames/24fps/50steps, 1080p enhancement optional. Advanced field is exactly `num_inference_steps`. No fake generation percentage.
- ASR input accepts audio asset or video asset (CPU extract to owned WAV before upstream dispatch). Structure accepts image/video; result `subjects,scene,ocr,tags,frames?`, timestamps reflect actual sampled frames. Math result `{text}`; ASR result `{text,segments}`; composition produces video asset.
## Events
- GET `/events?after=0` authenticated EventSource. `Last-Event-ID` header overrides query on reconnect.
- Durable event: `id: <integer>\nevent: job.updated\ndata: {"job":Job}\n\n`.
- Other events: `asset.created` data `{asset:Asset}`, `asset.updated` same; `asset.deleted` `{id}`, `reset` asks client to refetch snapshots. Heartbeat comments do not change cursor. Stream owner-filtered; logout/expiry ends stream.
- Fetch jobs snapshot and cursor before opening stream; after reconnection refresh HTTP state as well. Ignore Job versions older than or equal to the current version.
## Backend provider interface
Implemented in `app/providers.py` and `app/media.py`, independent of database models.
`Provider(settings)` methods (async):
- `health() -> bool`
- `scheduler_status() -> dict` sanitized Scheduler above.
- `prepare_gpu_payload(task_type:str, inputs:dict, parameters:dict, assets:dict[str,Path], work_dir:Path) -> dict` validated original upstream payload `{task_type,input,parameters,timeout_seconds}`. Input paths must be within shared workspace. Preprocess video ASR as needed.
- `submit(payload:dict,idempotency_key:str) -> dict` original upstream job response; retry only same immutable payload/key.
- `query(upstream_id:str) -> dict`, `cancel(upstream_id:str) -> dict`.
- `download(upstream_id:str,index:int,destination:Path) -> None` atomic streamed output, size bounded.
- `run_cpu(task_type:str, inputs:dict, parameters:dict, assets:dict[str,Path], work_dir:Path) -> CpuResult`.
- `aclose() -> None`.
- `CpuResult` dataclass: `outputs:list[Path]`, `result:dict`, `metadata:dict`.
- `ProviderError(code,message,retriable=False)` has those attributes; no secret/path leaks in public messages.
- Settings attributes consumed: `inference_base_url,inference_api_key,inference_api_key_file,workspace_root,asset_root,job_work_root,gpu_status_path,gpu_scheduler_path,qwen_base_url,qwen_model,qwen_api_key,ffmpeg_bin,ffprobe_bin,tts_base_url,tts_model,tts_api_key,request_timeout_seconds,max_output_bytes`.
- `app/media.py`: `inspect_media(path:Path,settings)->dict` (kind,mime_type,width,height,duration_seconds); `make_thumbnail(path:Path,destination:Path,settings)->Path|None`. These are async, subprocess is fixed argv, bounded time/resources; no shell. Image validation can use Pillow. JSON/text generated outputs supported.
- `capabilities(settings)->list[dict]` returns exact DTO above. Optional speech is false unless real service configured; provider speech through OpenAI-compatible `/audio/speech` if selected later.
Production files live under `/workspace/cmvr-visual`. Tests/explicit local preview use isolated configured roots, never implicitly access host files. CPU provider cancellation must kill/wait only its own subprocess. The coordinator supplies one task-private work directory per attempt.