cmvr-visual/docs/api-contract.md

93 lines
12 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.
## V2 additions
HTTP remains the command/query channel, SSE the owner-scoped notification channel. `execution_policy` is returned by capabilities/status: `{timezone:'Asia/Shanghai',start:'21:00',end:'08:00',batch_open,next_batch_at,close_behavior:'finish_current'}`. The server accepts and persists batch commands all day; only new compute phases are gated. Current work is never killed by the clock or a browser disconnect.
- GET `/live` process liveness; GET `/ready` 200/503 with database, coordinator, upstream_protocol and accepting checks. GPU capacity does not affect readiness.
- User DTO adds `disabled,must_change_password`; GET/PATCH `/auth/users[/{id}]` administer users, POST `/auth/password` `{current_password,new_password}` revokes sessions and requires relogin.
- GET/POST `/auth/tokens`, DELETE `/auth/tokens/{id}`. POST `{name,scopes,expires_at?}` returns `{token,record}` once. Use `Authorization: Bearer ...` for machine calls; tokens never grant admin authority. Interactive use additionally requires `interactive:write`.
- POST `/jobs` adds `execution_mode:'interactive'|'batch'`; new UI always persists and supplies an Idempotency-Key. GET list adds `root_only=true` to exclude workflow children. Job DTO adds `run_id,step_key,batch_id,batch_item_index,execution_mode,explicit_attempt,desired_state,hold_reasons,current_execution_id`. States additionally include `paused,pausing,needs_attention`.
- POST `/jobs/{id}/retry` honors Idempotency-Key; legacy callers omitting it explicitly create a fresh attempt without replay guarantees. Parent-owned children require their parent retry/control APIs.
- GET `/submissions/{key}?operation=jobs.create|jobs.retry|workflow.run|workflow.retry|workflow.pause|workflow.resume|workflow.cancel|batch.create|batch.control` recovers owned resources. Replaying the original key and immutable JSON is safe after a lost response; 404 alone does not prove an in-flight command was rejected.
- POST/GET `/workflows`; GET/PATCH `/workflows/{id}`. PATCH requires `If-Match: <version>`. Draft edits increment revision; new Runs freeze a snapshot.
- POST `/workflows/{id}/runs` `{draft_revision,expected_version,execution_mode?,reuse_run_id?}` plus Idempotency-Key → `{draft,run,steps,jobs,cursor}`. GET `/workflow-runs` is paginated; GET `/{id}` returns the consistent snapshot.
- POST `/workflow-runs/{id}/pause|resume|cancel` `{expected_version?}` plus Idempotency-Key. Pause closes future admission and drains current work. Cancel remains pending until cleanup/completion is known.
- POST `/workflow-runs/{id}/steps/{step_key}/retry` `{expected_run_version,target_job_id}` plus Idempotency-Key retries only the selected failed step, preserving other successful shots and inherited mode/holds.
- POST `/batches` `{name?,items:[{kind:'workflow',draft_id,draft_revision,expected_version}|{kind:'job',task_type,input,parameters?,count?}]}` plus Idempotency-Key. Maximum100 items, fixed `batch` mode, one active member per batch. GET list and `/{id}` snapshots; POST `/{id}/control` `{desired_state:'run'|'pause'|'cancel',expected_version?}` plus Idempotency-Key.
- Asset list additionally accepts `favorite` and `origin` SQL filters. Workflow references protect frozen inputs/outputs from physical deletion.
- SSE adds `draft.updated:{draft}`, `workflow.updated:{run,steps,jobs}`, `batch.updated:{batch,items}` with object versions. Ignore older/equal versions; reconnect/reset refreshes HTTP snapshots. Machine SSE requires `events:read` and Authorization, never tokens in URLs.
Workflow spec schema1: exactly ordered `shot_1,shot_2,shot_3`, each `{key,prompt,image_asset_id:null|string,parameters:{seed}}`; `profile=landscape_1080_v1|portrait_1080_v1`; `render={fps:24,total_frames:360,fit:'contain'|'cover',audio:null|{asset_id,source_start_ms,source_end_ms,offset_frame,short_policy:'silence'},subtitles:[{start_frame,end_frame,text}],template_version:'plain-v1'}`. Video track is exactly360 frames. Each enhanced shot contributes120 frames; short sources fail. Audio must fit the timeline explicitly, subtitles use whole-film half-open frame intervals.
Private inference protocol2 carries server-generated `scheduling={execution_mode,principal_id,batch_id?,run_id?,step_key?,policy_version:'night-v1'}`. Its `/capabilities` reports admission_pause/control_versions/final_output_indices. GPU result metadata identifies final enhanced output indices; workflows never choose the native intermediate by list order. Internal phase callbacks acquire separate `new_gpu`, `cpu_media`, `qwen_http` slots. No endpoint accepts arbitrary PIDs, Docker IDs, FFmpeg scripts or server filesystem paths from web users.