World's first open-source, agentic video production system. 12 production pipelines, 100+ tools, 700+ agent skill and production-knowledge files. Turn your AI coding assistant into a full video production studio.
Python agentagentic-aiaiclaudecopilotcursorelevenlabsffmpegfluximage-generationopen-sourceopenaipythonremotionstable-diffusiontext-to-speechtext-to-videovideo-generationvideo-production
Clean up Kling official PR artifacts
xucailiang8e1128400b40
diff --git a/.agents/skills/kling-official/SKILL.md b/.agents/skills/kling-official/SKILL.mdindex f2ffd86e..a1939e95 100644--- a/.agents/skills/kling-official/SKILL.md+++ b/.agents/skills/kling-official/SKILL.md@@ -69,7 +69,7 @@ Local image references may be normalized through `tools/_kling/media.py`. LocalImage Omni accepts `image_list[]` with official `image` values. Prompt placeholders such as `<<<image_1>>>` must map stably to the provided image order. If the prompt already contains placeholders, validate that the referenced images exist and do not insert duplicates.-## Phase 3 Capability Boundaries+## Capability BoundariesTTS, avatar, and lip sync are provider additions to existing OpenMontage capabilities. Audio effects and video effects are official Kling endpoints, but they are not registered as default OpenMontage tools until a pipeline has a stable capability slot for them.@@ -148,7 +148,7 @@ Local video paths must not be silently uploaded through fal.ai or any other prov## Audio Effects And Video Effects-Official Kling audio effects (`/v1/audio/text-to-audio`, `/v1/audio/video-to-audio`) and video effects (`/v1/videos/effects`) are intentionally not default OpenMontage selector tools in Phase 3. Record the non-mapping reason in docs/tests instead of registering tools that current pipelines might misuse.+Official Kling audio effects (`/v1/audio/text-to-audio`, `/v1/audio/video-to-audio`) and video effects (`/v1/videos/effects`) are intentionally not default OpenMontage selector tools. Record the non-mapping reason in docs/tests instead of registering tools that current pipelines might misuse.## Elements Helperdiff --git a/.agents/skills/video_toolkit/SKILL.md b/.agents/skills/video_toolkit/SKILL.mddeleted file mode 100644index 88d337f0..00000000--- a/.agents/skills/video_toolkit/SKILL.md+++ /dev/null@@ -1,456 +0,0 @@-----name: video-toolkit-description: Create professional videos autonomously using Codex-video-toolkit — AI voiceovers, image generation, music, talking heads, and Remotion rendering.-metadata:- openclaw:- emoji: "🎬"- skillKey: "video-toolkit"- os: ["darwin", "linux"]- requires:- bins: ["node", "python3", "ffmpeg", "npm"]------# Video Toolkit--Create professional explainer videos from a text brief. The toolkit uses open-source AI models on cloud GPUs (Modal or RunPod) for voiceover, image generation, music, and talking head animation. Remotion (React) handles composition and rendering.--## CRITICAL: Toolkit Path--The toolkit lives at a fixed path. **ALWAYS `cd` here before running any tool command.**--```bash-TOOLKIT=~/.openclaw/workspace/Codex-video-toolkit-cd $TOOLKIT-```--**NEVER run tool commands from inside a project directory.** Tools resolve paths relative to the toolkit root.--## Setup--### Step 1: Check Current State--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit-python3 tools/verify_setup.py-```--If everything shows `[x]`, skip to "Quick Test" below. Otherwise continue setup.--### Step 2: Install Python Dependencies--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit-pip3 install --break-system-packages -r tools/requirements.txt-```--Note: `--break-system-packages` is needed on Debian/Ubuntu with managed Python (PEP 668). Safe inside containers.--### Step 3: Configure Cloud GPU Endpoints--The toolkit needs cloud GPU endpoint URLs in `.env`. Check if `.env` exists and has Modal endpoints:--```bash-cat ~/.openclaw/workspace/Codex-video-toolkit/.env | grep MODAL-```--If Modal endpoints are configured, you're ready. If not, **ask the user to provide Modal endpoint URLs** or set up Modal:--```bash-pip3 install --break-system-packages modal-python3 -m modal setup # Opens browser for authentication--# Deploy each tool — capture the endpoint URL from output-cd ~/.openclaw/workspace/Codex-video-toolkit-modal deploy docker/modal-qwen3-tts/app.py-modal deploy docker/modal-flux2/app.py-modal deploy docker/modal-music-gen/app.py-modal deploy docker/modal-sadtalker/app.py-modal deploy docker/modal-image-edit/app.py-modal deploy docker/modal-upscale/app.py-modal deploy docker/modal-propainter/app.py-modal deploy docker/modal-ltx2/app.py # Requires: modal secret create huggingface-token HF_TOKEN=hf_...-```--**LTX-2 prerequisite:** Before deploying LTX-2, create a HuggingFace secret and accept the [Gemma 3 license](https://huggingface.co/google/gemma-3-12b-it-qat-q4_0-unquantized):-```bash-modal secret create huggingface-token HF_TOKEN=hf_your_read_access_token-```--Add each URL to `.env`:-```-MODAL_QWEN3_TTS_ENDPOINT_URL=https://...modal.run-MODAL_FLUX2_ENDPOINT_URL=https://...modal.run-MODAL_MUSIC_GEN_ENDPOINT_URL=https://...modal.run-MODAL_SADTALKER_ENDPOINT_URL=https://...modal.run-MODAL_IMAGE_EDIT_ENDPOINT_URL=https://...modal.run-MODAL_UPSCALE_ENDPOINT_URL=https://...modal.run-MODAL_DEWATERMARK_ENDPOINT_URL=https://...modal.run-MODAL_LTX2_ENDPOINT_URL=https://...modal.run-```--Optional but recommended — Cloudflare R2 for reliable file transfer:-```-R2_ACCOUNT_ID=...-R2_ACCESS_KEY_ID=...-R2_SECRET_ACCESS_KEY=...-R2_BUCKET_NAME=video-toolkit-```--### Step 4: Verify and Quick Test--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit-python3 tools/verify_setup.py-```--All tools should show `[x]`. Then run a quick test to confirm the GPU pipeline works:--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit-python3 tools/qwen3_tts.py --text "Hello, this is a test." --speaker Ryan --tone warm --output /tmp/video-toolkit-test.mp3 --cloud modal-```--If you get a valid .mp3 file, setup is complete. If it fails, check:-- `.env` has the correct `MODAL_QWEN3_TTS_ENDPOINT_URL`-- Run `python3 tools/verify_setup.py --json` and check `modal_tools` for which endpoints are missing--**Cost:** Modal includes $30/month free compute. A typical 60s video costs $1-3.-------## Creating a Video--### Step 1: Create Project--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit-cp -r templates/product-demo projects/PROJECT_NAME-cd projects/PROJECT_NAME-npm install-```--Templates: `product-demo` (marketing/explainer), `sprint-review`, `sprint-review-v2` (composable scenes).--### Step 2: Write Config--Edit `projects/PROJECT_NAME/src/config/demo-config.ts`:--```typescript-export const demoConfig: ProductDemoConfig = {- product: {- name: 'My Product',- tagline: 'What it does in one line',- website: 'example.com',- },- scenes: [- { type: 'title', durationSeconds: 9, content: { headline: '...', subheadline: '...' } },- { type: 'problem', durationSeconds: 14, content: { headline: '...', problems: ['...', '...'] } },- { type: 'solution', durationSeconds: 13, content: { headline: '...', highlights: ['...', '...'] } },- { type: 'stats', durationSeconds: 12, content: { stats: [{value: '99%', label: '...'}, ...] } },- { type: 'cta', durationSeconds: 10, content: { headline: '...', links: ['...'] } },- ],- audio: {- backgroundMusicFile: 'audio/bg-music.mp3',- backgroundMusicVolume: 0.12,- },-};-```--Scene types: `title`, `problem`, `solution`, `demo`, `feature`, `stats`, `cta`.--**Duration rule:** Estimate `durationSeconds` as `ceil(word_count / 2.5) + 2`. You will adjust this after generating audio in Step 4.--### Step 3: Write Voiceover Script--Create `projects/PROJECT_NAME/VOICEOVER-SCRIPT.md`:--```markdown-## Scene 1: Title (9s, ~17 words)-Build videos with AI. The product name toolkit makes it easy.--## Scene 2: Problem (14s, ~30 words)-The problem statement goes here. Keep it punchy and relatable.-```--**Word budget per scene:** `(durationSeconds - 2) * 2.5` words. The -2 accounts for 1s audio delay + 1s padding.--### Step 4: Generate Assets--**CRITICAL: All commands below MUST be run from the toolkit root, not the project directory.**--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit-```--#### 4a. Background Music--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit-python3 tools/music_gen.py \- --preset corporate-bg \- --duration 90 \- --output projects/PROJECT_NAME/public/audio/bg-music.mp3 \- --cloud modal-```--Presets: `corporate-bg`, `upbeat-tech`, `ambient`, `dramatic`, `tension`, `hopeful`, `cta`, `lofi`.--#### 4b. Voiceover (per-scene)--Generate ONE .mp3 file PER SCENE. Do NOT generate a single voiceover file.--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit--# Scene 01-python3 tools/qwen3_tts.py \- --text "The voiceover text for scene one." \- --speaker Ryan --tone warm \- --output projects/PROJECT_NAME/public/audio/scenes/01.mp3 \- --cloud modal--# Scene 02-python3 tools/qwen3_tts.py \- --text "The voiceover text for scene two." \- --speaker Ryan --tone warm \- --output projects/PROJECT_NAME/public/audio/scenes/02.mp3 \- --cloud modal--# ... repeat for each scene-```--**Speakers:** `Ryan`, `Aiden`, `Vivian`, `Serena`, `Uncle_Fu`, `Dylan`, `Eric`, `Ono_Anna`, `Sohee`-**Tones:** `neutral`, `warm`, `professional`, `excited`, `calm`, `serious`, `storyteller`, `tutorial`--For voice cloning (needs a reference recording):-```bash-cd ~/.openclaw/workspace/Codex-video-toolkit-python3 tools/qwen3_tts.py \- --text "Text to speak" \- --ref-audio assets/voices/reference.m4a \- --ref-text "Exact transcript of the reference audio" \- --output projects/PROJECT_NAME/public/audio/scenes/01.mp3 \- --cloud modal-```--#### 4c. Scene Images--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit-python3 tools/flux2.py \- --prompt "Dark tech background with blue geometric grid, cinematic lighting" \- --width 1920 --height 1080 \- --output projects/PROJECT_NAME/public/images/title-bg.png \- --cloud modal-```--Image presets (use `--preset` instead of `--prompt --width --height`):-`title-bg`, `problem`, `solution`, `demo-bg`, `stats-bg`, `cta`, `thumbnail`, `portrait-bg`--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit-python3 tools/flux2.py \- --preset title-bg \- --output projects/PROJECT_NAME/public/images/title-bg.png \- --cloud modal-```--#### 4d. Video Clips — B-Roll & Animated Backgrounds (optional)--Generate AI video clips for b-roll cutaways, animated slide backgrounds, or intro/outro sequences:--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit--# B-roll clip from text-python3 tools/ltx2.py \- --prompt "Aerial drone shot over a European city at golden hour, cinematic wide angle" \- --output projects/PROJECT_NAME/public/videos/broll-europe.mp4 \- --cloud modal--# Animate a slide/screenshot (image-to-video)-python3 tools/ltx2.py \- --prompt "Gentle particle effects, soft ambient light shifts, very slight camera drift" \- --input projects/PROJECT_NAME/public/images/title-bg.png \- --output projects/PROJECT_NAME/public/videos/animated-title.mp4 \- --cloud modal--# Abstract intro/outro background-python3 tools/ltx2.py \- --prompt "Dark moody abstract background with flowing blue light streaks, bokeh particles, cinematic" \- --output projects/PROJECT_NAME/public/videos/intro-bg.mp4 \- --cloud modal-```--Use in Remotion compositions with `<OffthreadVideo>`:-```tsx-<OffthreadVideo src={staticFile('videos/broll-europe.mp4')} />-```--**LTX-2 rules:**-- Max ~8 seconds per clip (193 frames at 24fps). Default is ~5s (121 frames).-- Width/height must be divisible by 64. Default: 768x512.-- ~$0.20-0.25 per clip, ~2.5 min generation time.-- Cold start ~60-90s. Subsequent clips on warm GPU are faster.-- Generated audio is ambient only — use voiceover/music tools for speech and music.-- ~30% of generations may have training data artifacts (logos/text). Re-run with `--seed` to vary.--#### 4e. Talking Head Narrator (optional)--Generate a presenter portrait, then animate per-scene clips:--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit--# 1. Generate portrait-python3 tools/flux2.py \- --prompt "Professional presenter portrait, clean style, dark background, facing camera, upper body" \- --width 1024 --height 576 \- --output projects/PROJECT_NAME/public/images/presenter.png \- --cloud modal--# 2. Generate per-scene narrator clips (one per scene, NOT one long video)-python3 tools/sadtalker.py \- --image projects/PROJECT_NAME/public/images/presenter.png \- --audio projects/PROJECT_NAME/public/audio/scenes/01.mp3 \- --preprocess full --still --expression-scale 0.8 \- --output projects/PROJECT_NAME/public/narrator-01.mp4 \- --cloud modal--# Repeat for each scene that needs a narrator-```--**SadTalker rules — follow these exactly:**-- **ALWAYS** use `--preprocess full` (default `crop` outputs a square, wrong aspect ratio)-- **ALWAYS** use `--still` (reduces head movement, looks professional)-- **ALWAYS** generate per-scene clips (6-15s each), NEVER one long video-- Processing: ~3-4 min per 10s of audio on Modal A10G-- `--expression-scale 0.8` keeps expressions subtle (range 0.0-1.5)--#### 4e. Image Editing (optional)--Create scene variants from existing images:--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit-python3 tools/image_edit.py \- --input projects/PROJECT_NAME/public/images/title-bg.png \- --prompt "Make it darker with red tones, more ominous" \- --output projects/PROJECT_NAME/public/images/problem-bg.png \- --cloud modal-```--#### 4f. Upscaling (optional)--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit-python3 tools/upscale.py \- --input projects/PROJECT_NAME/public/images/some-image.png \- --output projects/PROJECT_NAME/public/images/some-image-4x.png \- --scale 4 --cloud modal-```--### Step 5: Sync Timing--**ALWAYS do this after generating voiceover.** Audio duration differs from estimates.--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit-for f in projects/PROJECT_NAME/public/audio/scenes/*.mp3; do- echo "$(basename $f): $(ffprobe -v error -show_entries format=duration -of csv=p=0 "$f")s"-done-```--Update each scene's `durationSeconds` in `demo-config.ts` to: `ceil(actual_audio_duration + 2)`.--Example: if `01.mp3` is 6.8s, set scene 1 `durationSeconds` to `9` (ceil(6.8 + 2) = 9).--### Step 6: Review Still Frames--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit/projects/PROJECT_NAME-npx remotion still src/index.ts ProductDemo --frame=100 --output=/tmp/review-scene1.png-npx remotion still src/index.ts ProductDemo --frame=400 --output=/tmp/review-scene2.png-```--Check: text truncation, animation timing, narrator PiP positioning, background contrast.--### Step 7: Render--```bash-cd ~/.openclaw/workspace/Codex-video-toolkit/projects/PROJECT_NAME-npm run render-```--**Output:** `out/ProductDemo.mp4`-------## Composition Patterns--### Per-Scene Audio--Use per-scene audio with a 1-second delay (`from={30}` = 30 frames = 1s at 30fps):--```tsx-<Sequence from={30}>- <Audio src={staticFile('audio/scenes/01.mp3')} volume={1} />-</Sequence>-```--### Per-Scene Narrator PiP--```tsx-<Sequence from={30}>- <OffthreadVideo- src={staticFile('narrator-01.mp4')}- style={{ width: 320, height: 180, objectFit: 'cover' }}- muted- />-</Sequence>-```--**ALWAYS use `<OffthreadVideo>`, NEVER `<video>`.** Remotion requires its own component for frame-accurate rendering.--### Transitions--```tsx-import { TransitionSeries, linearTiming } from '@remotion/transitions';-import { fade } from '@remotion/transitions/fade';-import { glitch } from '../../../lib/transitions/presentations/glitch';-import { lightLeak } from '../../../lib/transitions/presentations/light-leak';-```--**NEVER import from `lib/transitions` barrel** — import custom transitions from `lib/transitions/presentations/` directly.-------## Error Recovery--| Problem | Solution |-|---------|----------|-| Tool command fails with "No module named..." | Run `pip3 install --break-system-packages -r tools/requirements.txt` from toolkit root |-| "MODAL_*_ENDPOINT_URL not configured" | Check `.env` has the endpoint URL. Run `python3 tools/verify_setup.py` |-| SadTalker output is square/cropped | You forgot `--preprocess full`. Re-run with that flag |-| Audio too short/long for scene | Re-run Step 5 (sync timing) and update config |-| `npm run render` fails | Make sure you're in the project dir, not toolkit root. Run `npm install` first |-| "Cannot find module" in Remotion | Check import paths. Custom components use `../../../lib/` relative paths |-| Cold start timeout on Modal | First call after idle takes 30-120s. Retry once — second call uses warm GPU |-------## Cost Estimates (Modal)--| Tool | Typical Cost | Notes |-|------|-------------|-------|-| Qwen3-TTS | ~$0.01/scene | ~20s per scene on warm GPU |-| FLUX.2 | ~$0.01/image | ~3s warm, ~30s cold |-| ACE-Step | ~$0.02-0.05 | Depends on duration |-| SadTalker | ~$0.05-0.20/scene | ~3-4 min per 10s audio |-| Qwen-Edit | ~$0.03-0.15 | ~8 min cold start (25GB model) |-| RealESRGAN | ~$0.005/image | Very fast |-| LTX-2.3 | ~$0.20-0.25/clip | ~2.5 min per 5s clip, A100-80GB |--**Total for a 60s video:** ~$1-3 depending on scenes and narrator clips.--Modal Starter plan: $30/month free compute. Apps scale to zero when idle.diff --git a/diagram.png b/diagram.pngindex 408bf71c..2f38f343 100644Binary files a/diagram.png and b/diagram.png differdiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 3261146c..47194168 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -398,16 +398,16 @@ All config is validated via Pydantic models in `lib/config_model.py`.| `VIDEO_GEN_LOCAL_ENABLED` | local video tools | Enable local GPU generation || `VIDEO_GEN_LOCAL_MODEL` | wan, hunyuan, ltx, cogvideo | Select local model |-Kling Official Phase 2 adds deeper Omni reference support inside the existing-`kling_official_video` and `kling_official_image` providers. Elements and Account-Usage live under `tools/_kling/` as internal helpers for element ID references and-low-frequency account diagnostics; they are not separate pipeline stages,-selectors, or generated-asset capabilities.+Kling Official support stays inside the existing provider and capability model.+`kling_official_video` and `kling_official_image` handle Classic, Turbo, and Omni+request shapes, while Elements and Account Usage live under `tools/_kling/` as+internal helpers for element ID references and low-frequency account diagnostics;+they are not separate pipeline stages, selectors, or generated-asset capabilities.-Kling Official Phase 3 adds provider tools only where OpenMontage already has a+Kling Official also adds provider tools only where OpenMontage already has amatching capability slot: `kling_tts` for `tts`, plus `kling_avatar` and`kling_lip_sync` for `avatar`. Official Kling audio effects and video effects are-not registered as tools yet because current pipelines do not define stable+not registered as tools because current pipelines do not define stable`sound_effects` or `video_effects` capability routing.---diff --git a/docs/kling-official-integration-plan.md b/docs/kling-official-integration-plan.mddeleted file mode 100644index 4ee82eda..00000000--- a/docs/kling-official-integration-plan.md+++ /dev/null@@ -1,1133 +0,0 @@-# 可灵官方 API 全项目集成实施计划--状态:实施指导文档;阶段 1、阶段 2 和阶段 3 的 OpenMontage provider 接入已按本文边界落地,真实 API 验证仍需显式 live QA 或人工端到端测试。--最后核验日期:2026-07-03。--## 0. 结论--本计划的目标不是只新增一个视频工具,而是把可灵官方 API 作为 OpenMontage 的一组正式 provider 接入。实现可以分阶段,但设计必须覆盖完整官方能力族,并明确哪些能力第一阶段进入代码、哪些能力进入后续阶段。--当前已经达到指导后续实现的条件:--- 官方 API 的核心接口、模型枚举、请求字段、任务状态和结果路径已经从可灵当前官方文档 bundle 中抽取核对。-- OpenMontage 的切入点已经明确:新增 provider tool 自动接入 selector/registry,不需要重写 pipeline。-- fal.ai 现有 `kling_video` 的可复用边界已经明确:复用 OpenMontage 工具契约和落盘模式,不复用 fal.ai 队列协议。-- 分阶段实施范围、文件清单、测试门槛和验收标准已列出。--但实施前有三项硬门槛,不能作为后续 TODO 留到代码之后:--1. 重新抽取当前官方 schema chunk,并把关键字段固化为 fixture。官方文档是 SPA,同一个 build id 下资源文件名也可能漂移;本计划中的 chunk 表是核验记录,不是实现时唯一来源。-2. 所有官方可灵 provider 的 `agent_skills` 必须挂上新建的 `kling-official` skill。否则 OpenMontage 的 Layer 3 读取链路不会自动加载官方直连鉴权、任务协议、错误处理和参数注意事项。-3. 所有付费官方可灵工具必须实现非默认的成本估算策略。不能继承 `BaseTool.estimate_cost()` 的 `0.0` 默认值,让 proposal/preflight 误以为官方付费调用免费。--第一阶段建议交付:--1. 共享可灵官方 client 与任务解析器。-2. `tools/video/kling_official_video.py`:官方直连视频生成 provider。-3. `tools/graphics/kling_official_image.py`:官方直连图像生成 provider。-4. 配套 skill、provider 文档、环境变量、契约测试。--第二阶段交付 Omni/Element/Account Usage/Callback 增强;第三阶段交付音效、TTS、数字人、口型和视频特效。--阶段拆分状态:--- 阶段 1 已拆分到 `docs/kling-official-phase-1-core.md`。-- 阶段 2 已拆分到 `docs/kling-official-phase-2-omni-operations.md`,对应现有 `kling_official_video` / `kling_official_image` provider 的 Omni 深度接入、Elements helper、Account Usage helper 和 callback 透传。-- 阶段 3 已拆分到 `docs/kling-official-phase-3-media-avatar-effects.md`,并已接入 `kling_tts`、`kling_avatar`、`kling_lip_sync`;音效和视频特效保留为有记录的不接入端点。--## 1. 资料来源与核验方式--### 1.1 外部来源--- GitHub issue:`https://github.com/calesthio/OpenMontage/issues/249`-- GitHub issue comment:`https://github.com/calesthio/OpenMontage/issues/249#issuecomment-4859448877`-- 可灵鉴权:`https://kling.ai/document-api/api/get-started/authentication`-- 可灵错误码:`https://kling.ai/document-api/api/get-started/error-codes`-- 可灵并发规则:`https://kling.ai/document-api/api/get-started/concurrency-rules`-- 可灵 Callback:`https://kling.ai/document-api/api/get-started/callbacks`-- 可灵 3.0 Turbo 文生视频:`https://kling.ai/document-api/api/video/3-0-turbo/text-to-video`-- 可灵 3.0 Turbo 图生视频:`https://kling.ai/document-api/api/video/3-0-turbo/image-to-video`-- 可灵 3.0/Omni 文生视频:`https://kling.ai/document-api/api/video/3-0-omni/text-to-video`-- 可灵 3.0/Omni 图生视频:`https://kling.ai/document-api/api/video/3-0-omni/image-to-video`-- 可灵 Video Omni:`https://kling.ai/document-api/api/video/3-0-omni/video-omni`-- 可灵图像生成:`https://kling.ai/document-api/api/image/3-0-omni/image-generation`-- 可灵 Image Omni:`https://kling.ai/document-api/api/image/3-0-omni/image-omni`-- 可灵音效:`https://kling.ai/document-api/api/video/audio-generation/text-to-audio`-- 可灵数字人:`https://kling.ai/document-api/api/video/avatar`-- 可灵口型:`https://kling.ai/document-api/api/video/lip-sync`-- 可灵账户用量:`https://kling.ai/document-api/api/assets/account-usage`--### 1.2 本地仓库来源--- `tools/base_tool.py`:BaseTool 契约、依赖检查、ToolResult。-- `tools/tool_registry.py`:自动发现、capability/provider catalog、setup offer。-- `tools/video/video_selector.py`:视频 provider 自动选择与 reference image 传参。-- `tools/graphics/image_selector.py`:图像 provider 自动选择与 edit/generate 参数透传。-- `tools/video/kling_video.py`:现有 fal.ai Kling provider,不能覆盖。-- `tools/video/_shared.py`:视频探测、部分下载/上传辅助。-- `tools/audio/tts_selector.py`、`tools/audio/music_gen.py`、`tools/avatar/talking_head.py`、`tools/avatar/lip_sync.py`:后续音频、TTS、数字人、口型能力槽位。-- `.agents/skills/ai-video-gen/SKILL.md`、`skills/creative/video-gen-prompting.md`、`docs/PROVIDERS.md`、`docs/ARCHITECTURE.md`、`README.md`:需要同步的文档和 agent 知识。--### 1.3 官方文档 bundle 核验--可灵文档是 SPA,页面正文和 OpenAPI schema 被拆成懒加载 chunk。2026-07-02 首次核验、2026-07-03 复核时:--- 文档站 build id:`97252498`。-- 静态资源前缀:`https://s15-kling.klingai.com/kos/s101/nlav112918/api-doc/assets/`。-- OpenAPI 渲染器:`OpenApi-BGkF3Bnu.js`。-- 路由 chunk:`DocumentNavigation-DJ6d14u_.js`。--已抽取并核验的核心 schema chunk:--| 能力 | 官方 api chunk |-|------|----------------|-| 3.0 Turbo 文生视频 | `api-87SY-xdC.js` |-| 3.0 Turbo 图生视频 | `api-BaOnwzhN.js` |-| Classic/3.0 文生视频 | `api-qwrrg0NE.js` |-| Classic/3.0 图生视频 | `api-Bg8QrOwF.js` |-| Video Omni | `api-IkDT7j6i.js` |-| 图像生成 | `api-CvIMUKGk.js` |-| Image Omni | `api-Dri5nsY7.js` |-| 文生音效 | `api-CO4SG6Ul.js` |-| 视频生音效 | `api-yfdpaPQb.js` |-| 数字人 | `api-CV_RG5n5.js` |-| TTS | `api-I0zriKMl.js` |-| 口型 | `api-VYP3S4bE.js` |-| 账户用量 | `api-CjZSPO13.js` |-| 视频特效 | `api-CE_k4fTW.js` |-| 高级元素 | `api-Bgnhdwj2.js` |--后续实现时,应把这些 schema 的关键字段固化为测试 fixture;如果可灵文档 build id 改变,先重新抽取 schema,再更新测试。--补充约束:--- 该 chunk 表只作为 2026-07-03 的审计记录。实施前必须从当前 HTML 重新定位主入口、导航 chunk 和 OpenAPI schema chunk。-- 2026-07-03 复核时,页面仍显示 `buildId=97252498`,但当前 HTML 中的导航资源名为 `document-navigation-nxVgwiS5.js`,与早先记录的 `DocumentNavigation-DJ6d14u_.js` 不一致。这说明不能只以 build id 或本表文件名判断 schema 未变化。-- P0 阶段应输出或更新 schema fixture,至少记录 `build_id`、`source_urls`、`chunk_names`、`extracted_at`、核心字段枚举和任务状态枚举。没有刷新 fixture,不进入 P1 实现。--### 1.4 范围边界--GitHub issue #249 同时提到 Kling official API 和 Volcengine Jimeng official API,维护者评论也说 “these two” 都有价值。当前用户要求是“整个项目集成可灵官方 API”,因此本文件只覆盖 Kling official API。--Jimeng/即梦需要独立计划处理,不能混进本计划:--- 鉴权不同,Jimeng 需要 Volcengine AK/SK 签名。-- provider 命名、环境变量、签名 client、模型枚举都应独立。-- 如后续实现 issue #249 的另一个 provider,应新增单独的 Jimeng 计划或 PR。--## 2. 官方 API 事实--### 2.1 鉴权与域名--官方当前文档提供两类鉴权:--| 方式 | 适用范围 | Header | 本项目决策 |-|------|----------|--------|------------|-| API Key | 文档标注适用于所有模型 | `Authorization: Bearer <API Key>` | 第一阶段采用 |-| AK/SK JWT | 文档标注适用于 3.0 及更早模型 | `Authorization: Bearer <JWT>` | 暂不实现;仅当用户账号必须使用旧鉴权时再补 |--默认环境变量:--```bash-KLING_API_KEY=...-KLING_API_BASE_URL=https://api-singapore.klingai.com-```--`KLING_API_BASE_URL` 可选。默认使用 Singapore 域名;中国大陆服务器用户可覆盖为 `https://api-beijing.klingai.com`。--所有官方直连工具都应声明:--```python-dependencies = ["env:KLING_API_KEY"]-```--这样 `provider_menu_summary()` 才能自动提示配置 `KLING_API_KEY`。--### 2.2 错误与并发--官方错误码中需要重点处理:--| HTTP | 业务码 | 含义 | 实现要求 |-|------|--------|------|----------|-| 401 | 1000-1004 | 鉴权失败或 token 无效 | 返回清晰的 `KLING_API_KEY`/Authorization 错误 |-| 429 | 1101/1102 | 欠费、资源包耗尽或过期 | 不自动重试;提示账户/资源包 |-| 403 | 1103 | 接口或模型无权限 | 不自动重试;提示模型权限 |-| 400 | 1200/1201 | 参数非法 | 暴露官方 message,便于修 prompt 或参数 |-| 404 | 1202/1203 | method/resource/model 无效 | 标记为实现或模型配置问题 |-| 429 | 1302 | 请求过快 | 可退避重试 |-| 429 | 1303 | 并发或 QPS 超资源包限制 | 可退避重试,错误文案必须说明并发槽 |-| 400 | 1301 | 内容安全策略 | 不自动重试;提示修改输入 |-| 500/503/504 | 5000-5002 | 服务端错误/维护/积压超时 | 可有限退避重试 |--并发规则要点:--- 限制作用在任务创建接口,不作用在查询接口。-- 视频任务每个任务占用 1 个并发槽。-- 任务从 `submitted` 到终态期间占用并发。-- `code=1303` 示例 message 为 `parallel task over resource pack limit`。--### 2.3 两套任务协议--可灵官方视频 API 当前至少有两套任务协议,必须分开建 parser。--| 协议 | 创建端点 | 查询端点 | 创建 ID | 成功状态 | 结果路径 |-|------|----------|----------|---------|----------|----------|-| Classic | `/v1/videos/*`, `/v1/images/*`, `/v1/audio/*` 等 | `GET /.../{id}` | `data.task_id` | `succeed` | `data.task_result.videos/images/audios[]` |-| 3.0 Turbo | `/text-to-video/kling-3.0-turbo`, `/image-to-video/kling-3.0-turbo` | `GET /tasks?task_ids=...` | `data.id` | `succeeded` | `data[0].outputs[]` |--Classic 状态值:`submitted`, `processing`, `succeed`, `failed`。--Turbo 状态值:`submitted`, `processing`, `succeeded`, `failed`。--实现上建议:--- `_parse_classic_created(data) -> task_id`-- `_parse_classic_polled(data, result_key)`-- `_parse_turbo_created(data) -> id`-- `_parse_turbo_polled(data) -> outputs`-- `_wait_for_task(...)` 根据协议选择终态和查询路径。--不要写“猜字段”的通用解析器;这会把 `task_id/id`、`succeed/succeeded`、`task_result/outputs` 混淆。--## 3. 核心 API 合约--### 3.1 Classic 文生视频--端点:--```text-POST /v1/videos/text2video-GET /v1/videos/text2video/{id}-GET /v1/videos/text2video?pageNum=1&pageSize=30-```--创建字段:--| 字段 | 类型 | 必填 | 值/说明 |-|------|------|------|---------|-| `model_name` | string | 否 | `kling-v1`, `kling-v1-6`, `kling-v2-master`, `kling-v2-1-master`, `kling-v2-5-turbo`, `kling-v2-6`, `kling-v3` |-| `multi_shot` | boolean | 否 | 默认 `false`;为 true 时 `prompt` 无效 |-| `shot_type` | string | 条件 | `customize`, `intelligence`;`multi_shot=true` 时必填 |-| `prompt` | string | 条件 | 普通生成时使用 |-| `multi_prompt` | array | 条件 | 多镜头分镜 |-| `negative_prompt` | string | 否 | 负向提示 |-| `sound` | string | 否 | `on`, `off`,默认 `off` |-| `cfg_scale` | float | 否 | 默认 `0.5` |-| `mode` | string | 否 | `std`, `pro`, `4k`,默认 `std` |-| `camera_control.type` | string | 否 | `simple`, `down_back`, `forward_up`, `right_turn_forward`, `left_turn_forward` |-| `aspect_ratio` | string | 否 | `16:9`, `9:16`, `1:1`,默认 `16:9` |-| `duration` | string | 否 | `"3"` 到 `"15"`,默认 `"5"` |-| `watermark_info` | object | 否 | 至少支持 `enabled` |-| `callback_url` | string | 否 | 任务回调 |-| `external_task_id` | string | 否 | 同账号唯一 |--结果路径:`data.task_result.videos[]`,每个 video 至少含 `id`, `url`, `watermark_url`, `duration`。--### 3.2 Classic 图生视频--端点:--```text-POST /v1/videos/image2video-GET /v1/videos/image2video/{id}-GET /v1/videos/image2video?pageNum=1&pageSize=30-```--创建字段:--| 字段 | 类型 | 必填 | 值/说明 |-|------|------|------|---------|-| `model_name` | string | 否 | `kling-v1`, `kling-v1-5`, `kling-v1-6`, `kling-v2-master`, `kling-v2-1`, `kling-v2-1-master`, `kling-v2-5-turbo`, `kling-v2-6`, `kling-v3` |-| `image` | string | 条件 | 图片 URL 或 raw base64;base64 不带 `data:image/...` 前缀 |-| `image_tail` | string | 否 | 尾帧,模型支持范围需按能力地图限制 |-| `prompt` | string | 否 | 文本提示 |-| `multi_shot`, `shot_type`, `multi_prompt` | mixed | 否/条件 | 同文生视频 |-| `negative_prompt` | string | 否 | 负向提示 |-| `element_list[].element_id` | long | 否 | 高级元素 |-| `voice_list` | array | 否 | 高级语音能力 |-| `sound` | string | 否 | `on`, `off` |-| `mode` | string | 否 | `std`, `pro`, `4k` |-| `static_mask`, `dynamic_masks` | string/array | 否 | 运动控制能力 |-| `camera_control` | object | 否 | 同文生视频 |-| `duration` | string | 否 | `"3"` 到 `"15"` |-| `watermark_info`, `callback_url`, `external_task_id` | mixed | 否 | 通用任务字段 |--结果路径:`data.task_result.videos[]`。--### 3.3 3.0 Turbo 文生视频--端点:--```text-POST /text-to-video/kling-3.0-turbo-GET /tasks?task_ids=<id>-POST /tasks-```--创建字段:--| 字段 | 类型 | 必填 | 值/说明 |-|------|------|------|---------|-| `prompt` | string | 是 | 文本提示 |-| `settings.resolution` | string | 否 | `720p`, `1080p`,默认 `720p` |-| `settings.aspect_ratio` | string | 否 | `16:9`, `9:16`, `1:1`,默认 `16:9` |-| `settings.duration` | int | 否 | `3` 到 `15`,默认 `5` |-| `options.callback_url` | string | 否 | 回调 |-| `options.external_task_id` | string | 否 | 同账号唯一 |-| `options.watermark_info.enabled` | boolean | 否 | 默认 `false` |--创建响应:`data.id`。--查询响应:`data[]`,结果路径 `data[0].outputs[]`。--列表查询:`POST /tasks`,可按 `status` 和 `product_type` 过滤,响应路径 `data.result[]`。--### 3.4 3.0 Turbo 图生视频--端点:--```text-POST /image-to-video/kling-3.0-turbo-GET /tasks?task_ids=<id>-POST /tasks-```--创建字段:--| 字段 | 类型 | 必填 | 值/说明 |-|------|------|------|---------|-| `contents[]` | array | 是 | 内容块 |-| `contents[].type` | string | 是 | `prompt`, `first_frame` |-| `contents[].text` | string | 否 | prompt 内容块使用 |-| `contents[].url` | string | 否 | first frame 内容块使用 |-| `settings.resolution` | string | 否 | `720p`, `1080p` |-| `settings.duration` | int | 否 | `3` 到 `15` |-| `options.callback_url`, `external_task_id`, `watermark_info.enabled` | mixed | 否 | 通用任务字段 |--创建响应:`data.id`。--查询响应:`data[]`,结果路径 `data[0].outputs[]`。--### 3.5 Video Omni--端点:--```text-POST /v1/videos/omni-video-GET /v1/videos/omni-video/{id}-GET /v1/videos/omni-video?pageNum=1&pageSize=30-```--创建字段:--| 字段 | 类型 | 必填 | 值/说明 |-|------|------|------|---------|-| `model_name` | string | 否 | `kling-video-o1`, `kling-v3-omni`,默认 `kling-video-o1` |-| `prompt` | string | 条件 | 可包含正负向描述 |-| `multi_shot`, `shot_type`, `multi_prompt` | mixed | 否/条件 | 多镜头 |-| `image_list[].image_url` | string | 否 | 图片参考 |-| `image_list[].type` | string | 否 | `first_frame`, `end_frame` |-| `element_list[].element_id` | long | 否 | 元素参考 |-| `video_list[].video_url` | string | 否 | 视频参考 |-| `video_list[].refer_type` | string | 否 | `feature`, `base`,默认 `base` |-| `video_list[].keep_original_sound` | string | 否 | `yes`, `no` |-| `sound` | string | 否 | `on`, `off` |-| `mode` | string | 否 | `std`, `pro`, `4k`,默认 `pro` |-| `aspect_ratio` | string | 否 | `16:9`, `9:16`, `1:1` |-| `duration` | string | 否 | `"3"` 到 `"15"` |-| `watermark_info`, `callback_url`, `external_task_id` | mixed | 否 | 通用任务字段 |--结果路径:`data.task_result.videos[]`。--### 3.6 图像生成--端点:--```text-POST /v1/images/generations-GET /v1/images/generations/{id}-GET /v1/images/generations?pageNum=1&pageSize=30-```--创建字段:--| 字段 | 类型 | 必填 | 值/说明 |-|------|------|------|---------|-| `model_name` | string | 否 | `kling-v1`, `kling-v1-5`, `kling-v2`, `kling-v2-new`, `kling-v2-1`, `kling-v3` |-| `prompt` | string | 是 | 正向提示,最大 2500 字符 |-| `negative_prompt` | string | 否 | 负向提示 |-| `image` | string | 否 | 参考图 URL 或 raw base64 |-| `image_reference` | string | 否 | `subject`, `face` |-| `image_fidelity` | float | 否 | 默认 `0.5` |-| `human_fidelity` | float | 否 | 默认 `0.45` |-| `element_list[].element_id` | long | 否 | 元素参考 |-| `resolution` | string | 否 | `1k`, `2k`,默认 `1k` |-| `n` | int | 否 | 默认 `1` |-| `aspect_ratio` | string | 否 | `16:9`, `9:16`, `1:1`, `4:3`, `3:4`, `3:2`, `2:3`, `21:9` |-| `watermark_info`, `callback_url`, `external_task_id` | mixed | 否 | 通用任务字段 |--结果路径:`data.task_result.images[]`,每个 image 至少含 `url`。--### 3.7 Image Omni--端点:--```text-POST /v1/images/omni-image-GET /v1/images/omni-image/{id}-GET /v1/images/omni-image?pageNum=1&pageSize=30-```--创建字段:--| 字段 | 类型 | 必填 | 值/说明 |-|------|------|------|---------|-| `model_name` | string | 否 | `kling-image-o1`, `kling-v3-omni`,默认 `kling-image-o1` |-| `prompt` | string | 是 | 可通过 `<<<image_1>>>` 等格式引用图片 |-| `image_list[].image` | string | 否 | 图片 URL 或 raw base64 |-| `element_list[].element_id` | long | 否 | 元素参考 |-| `resolution` | string | 否 | `1k`, `2k`, `4k` |-| `result_type` | string | 否 | `single`, `series` |-| `n` | int | 否 | 默认 `1` |-| `series_amount` | int/string | 否 | `2` 到 `9` 或 `auto` |-| `aspect_ratio` | string | 否 | `16:9`, `9:16`, `1:1`, `4:3`, `3:4`, `3:2`, `2:3`, `21:9`, `auto` |-| `watermark_info`, `callback_url`, `external_task_id` | mixed | 否 | 通用任务字段 |--结果路径:`data.task_result.images[]`。--### 3.8 音效、TTS、数字人、口型、特效--这些能力不进入第一阶段的核心交付,但需要在架构中预留映射,避免后面返工。--| 能力 | 端点 | 主要字段 | 结果路径 | OpenMontage 映射 |-|------|------|----------|----------|------------------|-| 文生音效 | `POST /v1/audio/text-to-audio` | `prompt`, `duration` | `data.task_result.audios[]` | 新增 `tools/audio/kling_audio.py`,能力可归 `music_generation` 或新增 `sound_effects` |-| 视频生音效 | `POST /v1/audio/video-to-audio` | `video_id` 或 `video_url`, `sound_effect_prompt`, `bgm_prompt`, `asmr_mode` | `data.task_result.audios[]`,并可能返回 videos | `tools/audio/kling_audio.py`,适合后期配音效 |-| TTS | `POST /v1/audio/tts` | `text`, `voice_id`, `voice_language`=`zh/en`, `voice_speed` | `data.task_result.audios[]` | 新增 `tools/audio/kling_tts.py`,接入 `tts_selector` |-| 数字人 | `POST /v1/videos/avatar/image2video` | `image`, `audio_id` 或 `sound_file`, `prompt`, `mode`=`std/pro` | `data.task_result.videos[]` | 新增 `tools/avatar/kling_avatar.py` |-| 口型识别 | `POST /v1/videos/identify-face` | `video_id` 或 `video_url` | `data.session_id`, face 信息 | `tools/avatar/kling_lip_sync.py` 的前置步骤 |-| 口型生成 | `POST /v1/videos/advanced-lip-sync` | `session_id`, `face_choose[]`, `audio_id` 或 `sound_file` | `data.task_result.videos[]` | 新增 `tools/avatar/kling_lip_sync.py` |-| 视频特效 | `POST /v1/videos/effects` | `effect_scene`, `input.image/images` | `data.task_result.videos[]` | 新增 `tools/video/kling_effects.py`,不要混入通用视频生成 |-| 账户用量 | `GET /account/costs` | `start_time`, `end_time`, `resource_pack_name` | `data.resource_pack_subscribe_infos[]` | 新增诊断工具或 setup preflight |-| 高级元素 | `/v1/general/advanced-*elements` | 元素创建、查询、删除 | element/task 信息 | 新增 `tools/kling_elements.py` 或 client 管理接口 |--## 4. OpenMontage 切入点--### 4.1 不改 pipeline,优先新增 provider--OpenMontage 的 selector 已经按 capability 自动发现 provider:--- 视频:`tools/video/video_selector.py` 调 `registry.get_by_capability("video_generation")`。-- 图像:`tools/graphics/image_selector.py` 调 `registry.get_by_capability("image_generation")`。-- TTS:`tools/audio/tts_selector.py` 调 `registry.get_by_capability("tts")`。--因此官方可灵第一阶段只需要新增具体 BaseTool 子类,不需要改 pipeline manifest。--### 4.2 命名规则--不能覆盖现有 `tools/video/kling_video.py`。--现有工具:--| 文件 | tool name | provider | API |-|------|-----------|----------|-----|-| `tools/video/kling_video.py` | `kling_video` | `kling` | fal.ai |--新增官方工具建议:--| 文件 | tool name | provider | capability |-|------|-----------|----------|------------|-| `tools/video/kling_official_video.py` | `kling_official_video` | `kling_official` | `video_generation` |-| `tools/graphics/kling_official_image.py` | `kling_official_image` | `kling_official` | `image_generation` |-| `tools/audio/kling_tts.py` | `kling_tts` | `kling_official` | `tts` |-| `tools/audio/kling_audio.py` | `kling_audio` | `kling_official` | `music_generation` 或新 `sound_effects` |-| `tools/avatar/kling_avatar.py` | `kling_avatar` | `kling_official` | `avatar` |-| `tools/avatar/kling_lip_sync.py` | `kling_lip_sync` | `kling_official` | `avatar` |-| `tools/video/kling_effects.py` | `kling_effects` | `kling_official` | `video_generation` 或 `video_post`,建议独立讨论 |--`provider="kling_official"` 是为了避免和 fal.ai 版 `provider="kling"` 冲突。selector 的 `preferred_provider` 是按 provider 字符串匹配的;如果两个视频工具都叫 `kling`,用户无法稳定指定官方直连还是 fal.ai 网关。--### 4.3 共享 client 位置--建议新增:--```text-tools/_kling/-├── __init__.py-├── client.py-├── schemas.py-├── media.py-└── errors.py-```--职责:--- `client.py`- - 读取 `KLING_API_KEY`、`KLING_API_BASE_URL`。- - 统一 `Authorization: Bearer ...` 和 JSON headers。- - `post_json`, `get_json`, `download_url`。- - `create_task`, `poll_classic_task`, `poll_turbo_task`。-- `schemas.py`- - 模型枚举、协议枚举、状态常量。- - `ClassicTaskResult`, `TurboTaskResult` 这类轻量 dataclass。-- `media.py`- - 本地图片转 raw base64,去掉 data URI 前缀。- - URL/base64 输入标准化。- - 下载图片/音频/视频到 output_path。-- `errors.py`- - `KlingAPIError`,包含 `code`, `message`, `request_id`, `http_status`。- - `is_retryable_kling_error()`。--不建议把这些放在 `tools/video/_shared.py`,因为图像、音频、TTS、头像也会使用。--### 4.4 fal.ai 现有 Kling 的复用边界--结论:具备抽离、复用一部分代码的可能,但只能复用 OpenMontage 层的 provider 骨架,不能复用 fal.ai 协议层。--可复用:--- `BaseTool` 契约字段:`name`, `version`, `capability`, `provider`, `dependencies`, `input_schema`, `supports`, `best_for`, `fallback_tools`。-- `ResourceProfile`, `RetryPolicy`, `idempotency_key_fields`, `side_effects`, `user_visible_verification`。-- `ToolResult` 返回结构:`data.output`, `data.output_path`, `artifacts`, `cost_usd`, `duration_seconds`, `model`。-- `tools/video/_shared.py::probe_output()`。-- output_path 的目录创建、下载落盘、artifact 返回模式。-- selector 传参语义:`prompt`, `operation`, `duration`, `aspect_ratio`, `reference_image_url`, `reference_image_path`。-- provider 文档/agent skill 的组织方式。--不可复用:--- `Authorization: Key {FAL_KEY}`;官方是 `Authorization: Bearer {KLING_API_KEY}`。-- `https://queue.fal.run/fal-ai/...`。-- fal.ai `status_url` / `response_url`。-- fal.ai 状态 `COMPLETED`, `FAILED`, `CANCELLED`。-- fal.ai 结果路径 `data["video"]["url"]`。-- fal.ai endpoint path:`kling-video/{variant}/{operation}`。-- `upload_image_fal()`,官方可直接接收图片 URL 或 raw base64。-- fal.ai 成本估算。--建议抽离的 provider-neutral helper:--| helper | 建议位置 | 复用方 |-|--------|----------|--------|-| `download_binary(url, output_path, timeout)` | `tools/_media/download.py` 或 `tools/_kling/media.py` 第一阶段局部实现 | 官方视频、图像、音频 |-| `ensure_parent(output_path)` | 同上 | 所有 API provider |-| `image_file_to_raw_base64(path)` | `tools/_kling/media.py` | 官方 I2V、Image、Avatar |-| `strip_data_uri_prefix(value)` | `tools/_kling/media.py` | 所有图片/音频 base64 输入 |--短期为了降低改动面,可以先在 `tools/_kling/media.py` 实现,不改现有 fal.ai 工具。等官方可灵、后续其它 provider 都稳定后,再考虑抽到更通用的 `tools/_media/`。--### 4.5 selector 参数注意事项--`video_selector.py` 有一个重要行为:--```python-if operation == "image_to_video" and reference_image_path:- if "image_url" in selected_tool.input_schema.properties:- upload_image_fal(reference_image_path)-```--因此官方视频工具第一阶段不要在 input_schema 暴露顶层 `image_url` 字段,否则 selector 会误以为需要 fal.ai 上传。--建议 schema:--- 暴露 `reference_image_url`-- 暴露 `reference_image_path`-- 内部把 `reference_image_path` 转成 raw base64 填入官方 `image`-- 内部把 `reference_image_url` 直接填入官方 `image`-- 需要尾帧时使用 `reference_tail_image_url/path` 或 `image_tail_url/path`--图像 selector 没有 fal.ai 自动上传逻辑,可以暴露 `image_url`, `image_path`, `image_urls`, `image_paths`,但官方工具内部仍应统一转换为官方字段 `image` 或 `image_list`。--## 5. 第一阶段实现方案--### 5.1 共享 client--新增 `tools/_kling/client.py`。--最低接口:--```python-class KlingClient:- def __init__(self, api_key=None, base_url=None, session=None): ...- def post(self, path: str, payload: dict[str, Any]) -> dict[str, Any]: ...- def get(self, path: str, params: dict[str, Any] | None = None) -> dict[str, Any]: ...- def download(self, url: str, output_path: Path, timeout: int = 180) -> Path: ...-```--任务接口:--```python-def create_classic_task(path: str, payload: dict[str, Any]) -> str-def poll_classic(path: str, task_id: str, result_key: str, timeout_seconds: int, poll_interval: float) -> list[dict]-def create_turbo(path: str, payload: dict[str, Any]) -> str-def poll_turbo(task_id: str, timeout_seconds: int, poll_interval: float) -> list[dict]-```--错误规则:--- HTTP 非 2xx:读取 JSON 中 `code/message/request_id`;如果不是 JSON,也保留响应文本片段。-- 业务 `code != 0`:抛 `KlingAPIError`。-- `code=1303`:错误 message 必须包含“并发/资源包限制”。-- `code in {1302,1303,5000,5001,5002}` 可有限退避重试。--### 5.2 官方视频 provider--新增 `tools/video/kling_official_video.py`。--基础契约:--```python-class KlingOfficialVideo(BaseTool):- name = "kling_official_video"- version = "0.1.0"- tier = ToolTier.GENERATE- capability = "video_generation"- provider = "kling_official"- stability = ToolStability.EXPERIMENTAL- execution_mode = ExecutionMode.SYNC- determinism = Determinism.STOCHASTIC- runtime = ToolRuntime.API- dependencies = ["env:KLING_API_KEY"]- agent_skills = ["ai-video-gen", "kling-official"]-```--第一阶段支持操作:--| OpenMontage operation | provider 参数 | 官方协议 | 端点 |-|-----------------------|---------------|----------|------|-| `text_to_video` | `api_family=classic` | Classic | `/v1/videos/text2video` |-| `image_to_video` | `api_family=classic` | Classic | `/v1/videos/image2video` |-| `text_to_video` | `api_family=turbo` | Turbo | `/text-to-video/kling-3.0-turbo` |-| `image_to_video` | `api_family=turbo` | Turbo | `/image-to-video/kling-3.0-turbo` |-| `text_to_video` | `api_family=omni` | Classic Omni | `/v1/videos/omni-video` |-| `image_to_video` | `api_family=omni` | Classic Omni | `/v1/videos/omni-video` |-| `reference_to_video` | `api_family=omni` | Classic Omni | `/v1/videos/omni-video` |--`video_selector` 当前的标准 operation 只有 `text_to_video`、`image_to_video`、`reference_to_video`、`rank`。因此 Turbo 和 Omni 都不应设计成 selector 层的新 operation;应由官方 provider 的 `api_family` 选择协议。--如果直接调用 `kling_official_video`,可以额外接受 provider-specific 的 `operation="omni_video"` 作为别名;但 selector 路径必须保持标准 operation。--建议 input_schema:--```python-{- "required": ["prompt"],- "properties": {- "prompt": {"type": "string"},- "operation": {- "enum": [- "text_to_video",- "image_to_video",- "reference_to_video"- ],- "default": "text_to_video"- },- "api_family": {- "enum": ["classic", "turbo", "omni"],- "default": "classic",- "description": "Official Kling protocol family. Selector-compatible operations stay text_to_video/image_to_video; this field chooses Classic, Turbo, or Omni."- },- "model_name": {- "enum": [- "kling-v1",- "kling-v1-5",- "kling-v1-6",- "kling-v2-master",- "kling-v2-1",- "kling-v2-1-master",- "kling-v2-5-turbo",- "kling-v2-6",- "kling-v3",- "kling-video-o1",- "kling-v3-omni"- ],- "default": "kling-v3"- },- "duration": {"enum": ["3","4","5","6","7","8","9","10","11","12","13","14","15"], "default": "5"},- "aspect_ratio": {"enum": ["16:9","9:16","1:1"], "default": "16:9"},- "resolution": {"enum": ["720p","1080p"], "default": "720p"},- "mode": {"enum": ["std","pro","4k"], "default": "std"},- "sound": {"enum": ["on","off"], "default": "off"},- "negative_prompt": {"type": "string"},- "reference_image_url": {"type": "string"},- "reference_image_path": {"type": "string"},- "reference_tail_image_url": {"type": "string"},- "reference_tail_image_path": {"type": "string"},- "image_list": {"type": "array"},- "video_list": {"type": "array"},- "element_list": {"type": "array"},- "camera_control": {"type": "object"},- "watermark": {"type": "boolean", "default": False},- "callback_url": {"type": "string"},- "external_task_id": {"type": "string"},- "output_path": {"type": "string"}- }-}-```--注意:--- `supports` 至少声明 `{"text_to_video": True, "image_to_video": True, "reference_to_video": True, "reference_image": True, "negative_prompt": True, "aspect_ratio": True}`。这样 selector 和 scoring 不需要只靠 schema 字段猜能力。-- 顶层不要暴露 `image_url`,避免触发 `video_selector` 的 fal.ai 自动上传。-- `model_variant` 可兼容老 fal.ai 工具,但官方工具内部主字段应是 `model_name`。-- 对 OpenMontage 传入的 `duration` 字符串,Turbo payload 需要转成 int。-- Classic 默认建议 `model_name="kling-v3"`,Turbo 不需要 `model_name`。-- `aspect_ratio` 只发送给官方 schema 支持的端点:Classic 文生视频、Turbo 文生视频、Video Omni。Classic 图生视频和 Turbo 图生视频当前 schema 未列出 `aspect_ratio`,不要盲目发送。-- `operation=image_to_video` 如果没有 reference image,应返回参数错误,不要退回文生视频。-- P1 应同步在 `video_selector.input_schema` 增加可选透传字段 `api_family`, `model_name`, `mode`, `sound`, `watermark`。selector 当前不会剥离未知字段,但 schema 不声明会降低 agent 可发现性,也不利于后续 contract 测试。-- `agent_skills` 必须同时包含 `ai-video-gen` 和 `kling-official`。前者提供通用视频生成提示结构,后者提供官方直连 API 的鉴权、任务协议、错误码、字段限制和成本治理注意事项。-- 必须重写 `estimate_cost()`。如果官方价格无法稳定映射到美元,仍要返回保守估算并在结果或 dry-run metadata 中标明 `cost_estimate_confidence="low"`;禁止静默返回 `0.0`。--输出:--- 下载第一个无水印 `url` 到 `output_path`。-- 返回 `provider="kling_official"`、`model=model_name 或 kling-3.0-turbo`、`task_id`、`operation`、`output_path`。-- 视频调用 `probe_output(output_path)`。--### 5.3 官方图像 provider--新增 `tools/graphics/kling_official_image.py`。--基础契约:--```python-class KlingOfficialImage(BaseTool):- name = "kling_official_image"- version = "0.1.0"- tier = ToolTier.GENERATE- capability = "image_generation"- provider = "kling_official"- runtime = ToolRuntime.API- dependencies = ["env:KLING_API_KEY"]- agent_skills = ["kling-official"]-```--第一阶段支持:--| image_selector 语义 | provider 参数 | 官方端点 |-|--------------------|---------------|----------|-| `generation_mode=generate` | `api_family=generation` | `/v1/images/generations` |-| `generation_mode=edit` 或有 `image_url/image_path` | `api_family=generation` | `/v1/images/generations`,填 `image` + `image_reference` |-| `generation_mode=generate/edit` | `api_family=omni` | `/v1/images/omni-image` |--`image_selector` 当前 `operation` 只有 `generate` 和 `rank`,编辑语义由 `generation_mode=edit` 和图片输入触发。因此不要把 `operation="omni"` 作为 selector 层约定;Omni 应由 `api_family=omni` 表达。直接调用 provider 时可以兼容 `operation="omni"`,但 selector 文档和测试应使用 `api_family`。--建议 input_schema:--```python-{- "required": ["prompt"],- "properties": {- "prompt": {"type": "string"},- "negative_prompt": {"type": "string"},- "operation": {"enum": ["generate"], "default": "generate"},- "generation_mode": {"enum": ["generate", "edit"], "default": "generate"},- "api_family": {"enum": ["generation", "omni"], "default": "generation"},- "model_name": {- "enum": ["kling-v3", "kling-v2-1", "kling-v2-new", "kling-image-o1", "kling-v3-omni"],- "default": "kling-v3"- },- "image_url": {"type": "string"},- "image_path": {"type": "string"},- "image_urls": {"type": "array", "items": {"type": "string"}},- "image_paths": {"type": "array", "items": {"type": "string"}},- "image_reference": {"enum": ["subject", "face"]},- "image_fidelity": {"type": "number", "default": 0.5},- "human_fidelity": {"type": "number", "default": 0.45},- "resolution": {"enum": ["1k", "2k", "4k"], "default": "1k"},- "aspect_ratio": {"enum": ["16:9","9:16","1:1","4:3","3:4","3:2","2:3","21:9","auto"], "default": "16:9"},- "n": {"type": "integer", "default": 1},- "result_type": {"enum": ["single", "series"], "default": "single"},- "series_amount": {"type": "string"},- "element_list": {"type": "array"},- "watermark": {"type": "boolean", "default": False},- "callback_url": {"type": "string"},- "external_task_id": {"type": "string"},- "output_path": {"type": "string"}- }-}-```--输出:--- `supports` 至少声明 `{"text_to_image": True, "image_edit": True, "negative_prompt": True, "aspect_ratio": True}`,并在 `best_for` 中说明官方 Kling 适合角色/主体一致性和 Omni 多参考图。-- 下载 `data.task_result.images[]` 中的图片。-- 如果 `n > 1` 或 `result_type=series`,`artifacts` 返回全部图片路径,`data.output_path` 指向第一张。-- 统一返回 `format`,根据 URL 或响应 Content-Type 判断扩展名,默认 `.png`。-- P1 应同步在 `image_selector.input_schema` 增加可选透传字段 `api_family`, `model_name`, `image_reference`, `image_fidelity`, `human_fidelity`, `result_type`, `series_amount`, `watermark`。否则 selector 仍能透传未知字段,但 agent 从 schema 看不到这些官方能力。-- `agent_skills` 必须包含 `kling-official`。不要只依赖现有 FLUX/BFL 图像 skill,因为官方可灵图像生成的鉴权、任务轮询、参考图字段和结果路径不同。-- 必须重写 `estimate_cost()`,并在 contract 测试中防止继承 `BaseTool` 的免费默认值。--### 5.4 文档和 skill 更新--第一阶段必须同步:--- `.env.example`- - 增加 `KLING_API_KEY=`- - 增加 `KLING_API_BASE_URL=`-- `README.md`- - provider key 列表加入官方可灵。- - 明确 fal.ai Kling 和 official Kling 是两个路径。-- `docs/PROVIDERS.md`- - 新增 “Kling Official” 小节。- - provider summary 表加入 `KLING_API_KEY`。-- `docs/ARCHITECTURE.md`- - API key 映射表加入官方可灵。-- `.agents/skills/ai-video-gen/SKILL.md`- - metadata `env_any` 加入 `KLING_API_KEY`。- - provider 表加入官方可灵直连。- - 提示:fal.ai Kling 和 official Kling 不同。-- `skills/creative/video-gen-prompting.md`- - 加入官方可灵适用场景和参数注意事项。-- `skills/INDEX.md`- - 在视频/图像生成相关说明中标出 `kling-official` 作为官方直连 Layer 3 skill。-- 新增 `.agents/skills/kling-official/SKILL.md`- - 包含 prompt、模型、参数、官方任务状态、错误处理注意事项。- - 后续 `kling_official_video`、`kling_official_image` 可引用它。--### 5.5 付费成本治理--官方可灵是付费 API,P1 不能让成本治理依赖人工记忆。--实现要求:--- `kling_official_video.estimate_cost()` 和 `kling_official_image.estimate_cost()` 必须显式实现,不能继承 `BaseTool` 的 `0.0` 默认值。-- 如果官方价格随资源包、区域、模型权限变化,工具应采用保守估算,并在 `dry_run()` 或成功结果 `data` 中记录 `cost_estimate_confidence` 和估算依据。-- `ToolResult.cost_usd` 应来自同一估算函数或官方返回的实际计费信息;如果后续 Account Usage 接入能拿到实际用量,应优先用实际用量 reconciled cost。-- proposal/preflight 中展示成本时必须说明官方可灵为 paid API;默认不启用 `4k`、声音、多结果或批量生成。-- contract 测试必须断言默认视频/图像输入的 `estimate_cost()` 不是静默 `0.0`,除非该工具明确返回可审计的免费额度/未知成本标记。--## 6. 第二阶段实现方案--第二阶段做增强能力,不阻塞基础视频/图像 provider。--### 6.1 Callback 支持--目标:--- 允许工具透传 `callback_url`。-- 若 OpenMontage 后续有本地/远端 callback receiver,再把 task state 写入 project artifacts。--当前没有 callback receiver 时:--- 工具仍以 polling 为主。-- `callback_url` 只是透传给官方 API。-- 文档必须说明 callback 是可选高级功能。--### 6.2 Account Usage 诊断--新增诊断工具候选:--```text-tools/kling_account_usage.py-```--或放在:--```text-tools/_kling/account.py-```--端点:`GET /account/costs`。--字段:`start_time`, `end_time`, `resource_pack_name`。--用途:--- setup preflight:检查资源包余额。-- 错误 `1101/1102` 后给出更清楚的诊断。--注意:官方说明该接口 QPS <= 1,应做本地节流。--### 6.3 Elements 管理--端点:--- `POST /v1/general/advanced-custom-elements`-- `GET /v1/general/advanced-custom-elements/{id}`-- `GET /v1/general/advanced-custom-elements`-- `GET /v1/general/advanced-presets-elements`-- `POST /v1/general/delete-elements`--建议不做成常规生成 provider,而是做“资源管理工具”:--```text-tools/kling_elements.py-```--用途:--- 创建并查询自定义角色/物体/声音元素。-- 为 Video Omni 和 Image Omni 提供 `element_id`。-- 把生成的 element metadata 写入项目 artifacts,便于复用。--### 6.4 Omni 深度接入--第一阶段 `api_family=omni` 的视频/图像路径可以只支持基础字段。--第二阶段补:--- `image_list` 多图引用。-- `video_list` 视频引用。-- `element_list` 元素引用。-- prompt 中 `<<<image_1>>>` 这类引用规则的 helper。-- 多镜头 `multi_prompt` schema。-- 结果中多媒体类型筛选。--## 7. 第三阶段实现方案--### 7.1 可灵 TTS--新增 `tools/audio/kling_tts.py`:--- capability:`tts`-- provider:`kling_official`-- 端点:`POST /v1/audio/tts`-- 字段:`text`, `voice_id`, `voice_language`, `voice_speed`-- 结果:`data.task_result.audios[]`--接入后 `tts_selector` 自动发现;需要测试 provider ranking 和 preferred_provider。--### 7.2 可灵音效--新增 `tools/audio/kling_audio.py`:--- `text_to_audio`:`POST /v1/audio/text-to-audio`-- `video_to_audio`:`POST /v1/audio/video-to-audio`--能力归属需要实施前定一次:--- 如果只做短音效,建议新增 capability `sound_effects` 并同步 skill index。-- 如果要快速接入,可暂归 `music_generation`,但必须在 `best_for/not_good_for` 说明它不是长音乐生成。--### 7.3 可灵数字人--新增 `tools/avatar/kling_avatar.py`:--- capability:`avatar`-- provider:`kling_official`-- 端点:`POST /v1/videos/avatar/image2video`-- 字段:`image`, `audio_id` 或 `sound_file`, `prompt`, `mode`-- 结果:`data.task_result.videos[]`--与本地 `talking_head.py` 并存。官方工具适合云端高质量数字人;本地工具适合无 API 成本和可控离线运行。--### 7.4 可灵口型--新增 `tools/avatar/kling_lip_sync.py`:--流程:--1. `POST /v1/videos/identify-face`,输入 `video_id` 或 `video_url`。-2. 用户或自动策略选择 `face_id`。-3. `POST /v1/videos/advanced-lip-sync`,输入 `session_id`, `face_choose[]`。-4. 轮询 `/v1/videos/advanced-lip-sync/{id}`。-5. 下载 `data.task_result.videos[]`。--注意:face 选择可能需要人工确认;默认可选择最大/最居中的 face,但计划中要保留人工选择出口。--### 7.5 可灵视频特效--新增 `tools/video/kling_effects.py`:--- 端点:`POST /v1/videos/effects`-- 字段:`effect_scene`, `input.image/images`-- 结果:`data.task_result.videos[]`--该能力不是通用视频生成,不应让 `video_selector` 在普通 text_to_video 场景误选。建议:--- capability 使用 `video_post` 或新增 `video_effects`。-- 如果必须挂在 `video_generation`,则 `_tool_selectable` 需要按 operation 严格过滤。--## 8. 测试计划--第一阶段最低测试:--### 8.1 client 单元测试--新增 `tests/contracts/test_kling_official_client.py`。--覆盖:--- 未设置 `KLING_API_KEY` 时工具不可用。-- 设置 `KLING_API_KEY` 后 headers 是 `Authorization: Bearer ...`。-- base URL 默认 `https://api-singapore.klingai.com`。-- `KLING_API_BASE_URL` 可覆盖。-- `code != 0` 抛 `KlingAPIError`,保留 `code/message/request_id`。-- `code=1303` 被识别为可重试并发错误。-- Classic create 解析 `data.task_id`。-- Classic poll 成功解析 `data.task_result.videos/images/audios[]`。-- Turbo create 解析 `data.id`。-- Turbo poll 成功解析 `data[0].outputs[]`。-- schema fixture 包含 `build_id`、`source_urls`、`chunk_names`、`extracted_at` 和核心枚举;如果当前官方 HTML 的 build id 或 chunk 名与 fixture 不一致,测试应提示先刷新 fixture。--### 8.2 视频 provider 测试--新增 `tests/contracts/test_kling_official_video.py`。--覆盖:--- registry 能发现 `kling_official_video`。-- `capability="video_generation"`,`provider="kling_official"`。-- input_schema 不包含顶层 `image_url`。-- `operation=text_to_video, api_family=classic` 构造 `/v1/videos/text2video` payload。-- `operation=image_to_video, api_family=classic` 使用 `reference_image_url/path` 构造官方 `image` 字段。-- `operation=text_to_video, api_family=turbo` 构造 `prompt/settings/options`。-- `operation=image_to_video, api_family=turbo` 构造 `contents[]`。-- `operation=reference_to_video, api_family=omni` 构造 `video_list[]` 或多参考输入。-- 成功后下载视频、返回 artifact、调用 `probe_output`。-- `video_selector` 用 `preferred_provider="kling_official"` 能选中官方工具。-- `reference_image_path` 不触发 `upload_image_fal()`。-- `video_selector.input_schema` 暴露 `api_family` 等官方透传字段,且不会破坏其它 provider。-- `agent_skills` 包含 `kling-official`。-- `estimate_cost()` 对默认 paid 输入不返回静默 `0.0`,并记录估算置信度或依据。--### 8.3 图像 provider 测试--新增 `tests/contracts/test_kling_official_image.py`。--覆盖:--- registry 能发现 `kling_official_image`。-- `capability="image_generation"`,`provider="kling_official"`。-- generate payload 使用 `/v1/images/generations`。-- edit payload 将 `image_path` 转 raw base64。-- `api_family=omni` payload 使用 `/v1/images/omni-image` 和 `image_list[]`。-- 多图片结果全部写入 artifacts。-- `image_selector` 用 `preferred_provider="kling_official"` 能选中官方工具。-- `image_selector.input_schema` 暴露 `api_family` 等官方透传字段,且不会破坏其它 provider。-- `agent_skills` 包含 `kling-official`。-- `estimate_cost()` 对默认 paid 输入不返回静默 `0.0`,并记录估算置信度或依据。--### 8.4 文档/skill 测试--若仓库已有 contract 测试:--- provider catalog 包含 `kling_official`。-- docs provider table 包含 `KLING_API_KEY`。-- `.agents/skills/ai-video-gen/SKILL.md` metadata `env_any` 包含 `KLING_API_KEY`。-- `.agents/skills/kling-official/SKILL.md` 存在,且官方可灵 provider 的 `agent_skills` 引用它。-- `skills/INDEX.md` 或等价索引能让后续 agent 发现官方直连 skill。-- `docs/kling-official-integration-plan.md` 中列出的模型枚举与测试 fixture 保持一致。--### 8.5 付费 API 测试--默认不在 CI 中打真实可灵 API。--可选新增手工 QA:--```bash-RUN_KLING_LIVE_TESTS=1 KLING_API_KEY=... pytest tests/qa/test_kling_official_live.py-```--真实调用只做低成本 smoke:--- 文生图 1 张。-- 文生视频最短时长 3s 或 5s。-- 不跑批量、不跑 4k、不默认开声音。--## 9. 实施顺序--### P0:准备与保护--1. 创建分支。-2. 确认工作区未覆盖用户改动。-3. 安装/确认 Python 依赖,尤其是 `requests`。-4. 重新抽取当前官方 schema chunk,新建或更新官方 schema fixture。-5. 写 client/parser 测试,先红后绿。--### P1:核心视频与图像--1. 新增 `tools/_kling/` client、media、errors。-2. 新增 `kling_official_video`。-3. 新增 `kling_official_image`。-4. 补 selector/registry contract 测试。-5. 补 docs 和 skill。-6. 跑相关 contract 测试。--### P2:Omni、元素、账户、callback--1. 强化 Omni payload builder。-2. 新增 elements 管理。-3. 新增 account usage 查询。-4. 增加 callback_url 透传文档和 artifacts 记录。--### P3:音频、TTS、数字人、口型、特效--1. 新增 `kling_tts` 并接入 `tts_selector`。-2. 新增 `kling_audio`。-3. 新增 `kling_avatar`。-4. 新增 `kling_lip_sync`。-5. 新增 `kling_effects` 或明确不纳入 selector。-6. 为每个工具补 skill 和 contract 测试。--## 10. 验收标准--第一阶段完成标准:--- `registry.support_envelope()` 能看到 `kling_official_video` 和 `kling_official_image`。-- 未设置 `KLING_API_KEY` 时两个工具状态为 `UNAVAILABLE`,setup offer 指向 `KLING_API_KEY`。-- 设置 `KLING_API_KEY` 时两个工具状态为 `AVAILABLE`。-- `video_selector` 可通过 `preferred_provider="kling_official"` 选中官方视频工具。-- `image_selector` 可通过 `preferred_provider="kling_official"` 选中官方图像工具。-- `kling_video` fal.ai 版本行为不变。-- 官方视频工具没有顶层 `image_url` schema,避免 fal.ai 上传误触发。-- Classic/Turbo 两套任务 parser 均有 fixture 覆盖。-- schema fixture 已按当前官方 HTML/chunk 重新抽取;不能只沿用本计划中的旧 chunk 文件名。-- 两个官方 provider 的 `agent_skills` 都包含 `kling-official`。-- 两个官方 provider 都实现非默认 `estimate_cost()`,不会把 paid API 静默报告为 `0.0` 成本。-- 图像结果、多结果 artifacts 有测试覆盖。-- README、docs、skill 中明确 fal.ai Kling 与 official Kling 的差异。--全项目集成完成标准:--- 官方可灵每个主要能力族都有明确实现或明确不接入理由。-- 视频、图像、TTS、音效、数字人、口型、特效、元素、账户用量均有对应设计和测试策略。-- selector 不会在不适合的 operation 中误选特效、口型、音效工具。-- 付费调用默认不进 CI;live QA 需要显式环境变量开启。-- 所有新增工具都遵守 OpenMontage 的 BaseTool 契约、artifact 路径和项目目录约定。--## 11. 风险与处理--| 风险 | 影响 | 处理 |-|------|------|------|-| 官方文档 schema 更新 | 字段/模型变化 | schema fixture 固化;实现前重新抽取 build chunk |-| fal.ai 与 official provider 名称混淆 | selector 误选 | official provider 固定 `kling_official` |-| `reference_image_path` 被上传到 fal.ai | 错误依赖 `FAL_KEY` | 官方视频 schema 不暴露顶层 `image_url` |-| 图片/音频 URL 30 天清理 | artifact 失效 | 生成后立即下载到项目目录 |-| 账户无模型权限 | 真实调用失败 | 错误 `1103` 明确提示模型权限 |-| 并发槽耗尽 | 任务创建失败 | `1303` 退避和明确错误 |-| 4k/声音/Omni 成本高 | 费用不可控 | 默认不开高成本能力;执行前按 AGENT_GUIDE 宣告工具/模型/成本 |-| 口型 face 选择不准 | 输出错误人物 | 保留人工选择或至少返回 face list |--## 12. 立即可执行的开发清单--推荐从这些文件开始:--```text-tools/_kling/__init__.py-tools/_kling/client.py-tools/_kling/errors.py-tools/_kling/media.py-tools/_kling/schemas.py-tools/video/kling_official_video.py-tools/graphics/kling_official_image.py-tests/contracts/test_kling_official_client.py-tests/contracts/test_kling_official_video.py-tests/contracts/test_kling_official_image.py-.agents/skills/kling-official/SKILL.md-```--随后更新:--```text-.env.example-README.md-docs/PROVIDERS.md-docs/ARCHITECTURE.md-.agents/skills/ai-video-gen/SKILL.md-skills/creative/video-gen-prompting.md-```--本计划到这里已经足以指导第一阶段代码实现;第二、三阶段也有明确能力边界和接口入口,可以按同一 client/parser 体系继续扩展。diff --git a/docs/kling-official-phase-1-core.md b/docs/kling-official-phase-1-core.mddeleted file mode 100644index 51e40a6d..00000000--- a/docs/kling-official-phase-1-core.md+++ /dev/null@@ -1,784 +0,0 @@-# 可灵官方 API 集成阶段 1:核心视频与图像 Provider--状态:实施指导文档。--来源:从 `docs/kling-official-integration-plan.md` 拆分而来。本阶段合并原计划中的 P0「准备与保护」和 P1「核心视频与图像」。--执行顺序:必须先完成本文件,再进入 `docs/kling-official-phase-2-omni-operations.md`。--## 1. 阶段目标--本阶段的目标是让可灵官方 API 以正式 provider 形式接入 OpenMontage 的工具系统,先交付两个可用能力:--| 能力 | 文件 | tool name | provider | capability |-|------|------|-----------|----------|------------|-| 官方视频生成 | `tools/video/kling_official_video.py` | `kling_official_video` | `kling_official` | `video_generation` |-| 官方图像生成 | `tools/graphics/kling_official_image.py` | `kling_official_image` | `kling_official` | `image_generation` |--本阶段完成后,OpenMontage 应能通过 registry 自动发现这两个工具,并通过 `video_selector` / `image_selector` 在用户指定 `preferred_provider="kling_official"` 时选中官方直连路径。--本阶段不要求完整接入音频、TTS、数字人、口型、视频特效、元素管理和账户用量。这些能力只在后续阶段评估;只有能自然落入现有 OpenMontage capability 或作为 provider 内部 helper 的部分才接入。--本阶段是 provider 接入,不是新增 OpenMontage 功能面。现有 pipeline、stage director、selector、artifact schema 和 checkpoint 规则保持不变。--## 2. 不可变规则--实施时必须遵守以下规则:--- 本阶段只覆盖 Kling official API。Volcengine Jimeng/即梦不属于本计划;Jimeng 的鉴权、provider 命名、环境变量、签名 client 和模型枚举都必须单独设计,不能混进这些可灵官方工具。-- 不改 pipeline 体系。官方可灵第一阶段只新增 BaseTool provider,不新增 pipeline,不重写已有 pipeline manifest。-- 不改 pipeline stage 顺序,不新增 canonical artifact,不新增 orchestrator 状态。-- 不覆盖 `tools/video/kling_video.py`。该文件是现有 fal.ai Kling provider,行为必须保持不变。-- 官方 provider 必须统一使用 `provider="kling_official"`,不能复用 `provider="kling"`,否则 selector 无法稳定区分 fal.ai 网关和官方直连。-- 第一阶段只实现 API Key 鉴权:`Authorization: Bearer <KLING_API_KEY>`。AK/SK JWT 不进入本阶段。-- 所有官方可灵工具都必须声明 `dependencies = ["env:KLING_API_KEY"]`,使 `provider_menu_summary()` 能自动生成 setup offer。-- `KLING_API_BASE_URL` 是可选覆盖项,默认值应为 `https://api-singapore.klingai.com`。-- 所有付费官方可灵 provider 必须重写 `estimate_cost()`,不能继承 `BaseTool.estimate_cost()` 的 `0.0` 默认值。-- 所有官方可灵 provider 的 `agent_skills` 必须包含新建的 `kling-official` skill。视频工具还必须保留通用视频提示 skill,例如 `ai-video-gen`。-- 实施前必须重新抽取当前官方文档 schema chunk,并固化为测试 fixture。不能直接把原总计划中的 chunk 文件名当作当前事实。-- 官方视频工具的 input schema 不得暴露顶层 `image_url` 字段,避免 `video_selector` 误触发 fal.ai 的图片上传逻辑。-- 所有远端生成结果必须下载到 OpenMontage 的输出路径或项目 artifacts 中,不能只返回官方临时 URL。-- CI 默认不能打真实可灵付费 API。真实调用必须通过显式环境变量开启。--## 3. Pipeline 调用链--本阶段必须接入现有调用链,而不是创造新的编排路径:--```text-pipeline stage director--> selector tool(video_selector / image_selector)--> registry.get_by_capability(...)--> kling_official_* provider--> tools/_kling client/parser/media helper--> Kling official API--> ToolResult + artifacts--> stage canonical artifact--> checkpoint-```--实施含义:--- pipeline 只看到 `video_generation` / `image_generation` capability,不感知官方可灵协议细节。-- stage director 仍按现有方式调用 selector 或具体 tool,不写可灵专用编排。-- selector 只做 provider selection 和通用参数转发,不承担可灵 payload 构造。-- 官方 API 协议差异只存在于 `kling_official_video`、`kling_official_image` 和 `tools/_kling/` helper。-- 所有生成文件仍写入 stage 传入的 `output_path` 或项目目录,不写 repo root。-- 如果用户选择官方可灵,proposal/preflight 只说明 provider/model/cost,不改变 pipeline。--## 4. 准备与保护--开始写代码前先完成这些检查:--1. 创建实现分支,建议使用 `codex/` 前缀,例如 `codex/kling-official-phase-1`。-2. 查看工作区状态,确认不会覆盖用户已有改动。-3. 确认 Python 依赖可用,尤其是 HTTP 客户端依赖。优先复用仓库现有依赖;若新增依赖,必须同步依赖文件和文档。-4. 阅读这些本地文件以确认当前实现契约:- - `tools/base_tool.py`- - `tools/tool_registry.py`- - `tools/video/video_selector.py`- - `tools/graphics/image_selector.py`- - `tools/video/kling_video.py`- - `tools/video/_shared.py`-5. 不开始实现 provider,直到 schema fixture 刷新完成。--## 5. 官方 Schema Fixture--官方文档是 SPA,正文和 OpenAPI schema 会被拆进懒加载 chunk。同一个 build id 下资源文件名也可能变化,因此必须在实施时重新定位当前文档资源。--建议新增 fixture 路径:--```text-tests/fixtures/kling_official/schema_snapshot.json-```--fixture 至少包含:--```json-{- "build_id": "...",- "source_urls": ["..."],- "chunk_names": ["..."],- "extracted_at": "YYYY-MM-DDTHH:MM:SSZ",- "endpoints": {},- "models": {},- "task_statuses": {},- "result_paths": {},- "core_field_enums": {}-}-```--必须固化的核心信息:--- API base URL 默认值和可覆盖环境变量。-- Classic 任务状态:`submitted`、`processing`、`succeed`、`failed`。-- Turbo 任务状态:`submitted`、`processing`、`succeeded`、`failed`。-- Classic 创建 ID 路径:`data.task_id`。-- Turbo 创建 ID 路径:`data.id`。-- Classic 结果路径:`data.task_result.videos[]`、`data.task_result.images[]`。-- Turbo 结果路径:`data[0].outputs[]`。-- 第一阶段要支持的视频模型枚举。-- 第一阶段要支持的图像模型枚举。-- `aspect_ratio`、`duration`、`resolution`、`mode`、`sound` 等核心字段枚举。--测试要求:--- 如果当前官方 HTML 的 build id、入口 chunk 或核心 schema 与 fixture 不一致,测试应提示先刷新 fixture。-- 测试不应依赖原计划中的旧 chunk 文件名。-- fixture 是实现依据之一,不是替代错误处理和 runtime 验证的借口。--## 6. 共享可灵 Client--新增目录:--```text-tools/_kling/-├── __init__.py-├── client.py-├── errors.py-├── media.py-└── schemas.py-```--### 6.1 `client.py`--最低接口:--```python-class KlingClient:- def __init__(self, api_key=None, base_url=None, session=None): ...- def post(self, path: str, payload: dict[str, Any]) -> dict[str, Any]: ...- def get(self, path: str, params: dict[str, Any] | None = None) -> dict[str, Any]: ...- def download(self, url: str, output_path: Path, timeout: int = 180) -> Path: ...-```--任务接口:--```python-def create_classic_task(path: str, payload: dict[str, Any]) -> str: ...-def poll_classic(path: str, task_id: str, result_key: str, timeout_seconds: int, poll_interval: float) -> list[dict]: ...-def create_turbo(path: str, payload: dict[str, Any]) -> str: ...-def poll_turbo(task_id: str, timeout_seconds: int, poll_interval: float) -> list[dict]: ...-```--实现规则:--- 从 `KLING_API_KEY` 读取默认 API Key。-- 从 `KLING_API_BASE_URL` 读取可选 base URL;未设置时使用 `https://api-singapore.klingai.com`。-- 所有请求都发送 `Authorization: Bearer <key>`。-- 所有 JSON 请求都发送明确的 JSON headers。-- HTTP 非 2xx 时尝试解析 JSON 中的 `code`、`message`、`request_id`;如果不是 JSON,保留响应文本片段。-- 业务 `code != 0` 时抛出 `KlingAPIError`。-- 下载方法负责创建父目录,返回最终 `Path`。--### 6.2 `errors.py`--新增:--```python-class KlingAPIError(Exception):- code: str | int | None- message: str- request_id: str | None- http_status: int | None-```--新增:--```python-def is_retryable_kling_error(error: KlingAPIError) -> bool: ...-```--错误处理规则:--| HTTP | 业务码 | 含义 | 行为 |-|------|--------|------|------|-| 401 | 1000-1004 | 鉴权失败或 token 无效 | 不重试,提示 `KLING_API_KEY` / Authorization |-| 429 | 1101/1102 | 欠费、资源包耗尽或过期 | 不重试,提示账户或资源包 |-| 403 | 1103 | 接口或模型无权限 | 不重试,提示模型权限 |-| 400 | 1200/1201 | 参数非法 | 不重试,暴露官方 message |-| 404 | 1202/1203 | method/resource/model 无效 | 不重试,标记实现或模型配置问题 |-| 429 | 1302 | 请求过快 | 可有限退避重试 |-| 429 | 1303 | 并发或 QPS 超资源包限制 | 可有限退避重试,错误文案必须说明并发槽 |-| 400 | 1301 | 内容安全策略 | 不重试,提示修改输入 |-| 500/503/504 | 5000-5002 | 服务端错误、维护、积压超时 | 可有限退避重试 |--退避规则:--- 只对 `1302`、`1303`、`5000`、`5001`、`5002` 做有限重试。-- 不对鉴权、余额、权限、参数、安全策略错误重试。-- 重试耗尽后保留最后一次官方错误信息。--### 6.3 `schemas.py`--放置轻量常量和 dataclass:--- Classic/Turbo 协议枚举。-- Classic/Turbo 状态常量。-- 第一阶段模型枚举。-- `ClassicTaskResult`、`TurboTaskResult` 等轻量解析结果。--不要写“猜字段”的通用任务解析器。Classic 和 Turbo 的字段名、状态值、结果路径不同,必须分开解析。--### 6.4 `media.py`--实现:--- `strip_data_uri_prefix(value)`:去掉 `data:image/...;base64,` 等前缀。-- `image_file_to_raw_base64(path)`:本地图片转 raw base64。-- `normalize_image_input(url=None, path=None)`:URL 直接返回 URL,本地路径转 raw base64。-- 下载图片/音频/视频到 output path 的共用 helper。--第一阶段可以先把这些 helper 放在 `tools/_kling/media.py`。不要为了抽象过早修改现有 fal.ai 工具。--## 7. 官方视频 Provider--新增:--```text-tools/video/kling_official_video.py-```--基础契约:--```python-class KlingOfficialVideo(BaseTool):- name = "kling_official_video"- version = "0.1.0"- tier = ToolTier.GENERATE- capability = "video_generation"- provider = "kling_official"- stability = ToolStability.EXPERIMENTAL- execution_mode = ExecutionMode.SYNC- determinism = Determinism.STOCHASTIC- runtime = ToolRuntime.API- dependencies = ["env:KLING_API_KEY"]- agent_skills = ["ai-video-gen", "kling-official"]-```--### 7.1 支持范围--| OpenMontage operation | `api_family` | 官方协议 | 端点 |-|-----------------------|--------------|----------|------|-| `text_to_video` | `classic` | Classic | `/v1/videos/text2video` |-| `image_to_video` | `classic` | Classic | `/v1/videos/image2video` |-| `text_to_video` | `turbo` | Turbo | `/text-to-video/kling-3.0-turbo` |-| `image_to_video` | `turbo` | Turbo | `/image-to-video/kling-3.0-turbo` |-| `text_to_video` | `omni` | Classic Omni | `/v1/videos/omni-video` |-| `image_to_video` | `omni` | Classic Omni | `/v1/videos/omni-video` |-| `reference_to_video` | `omni` | Classic Omni | `/v1/videos/omni-video` |--`video_selector` 的标准 operation 仍是 `text_to_video`、`image_to_video`、`reference_to_video`、`rank`。Turbo 和 Omni 不应变成 selector 层的新 operation,而应通过 `api_family` 选择。--直接调用 provider 时可以兼容 `operation="omni_video"` 作为别名,但 selector 路径不要依赖这个别名。--### 7.2 Input Schema 规则--建议字段:--```python-{- "required": ["prompt"],- "properties": {- "prompt": {"type": "string"},- "operation": {"enum": ["text_to_video", "image_to_video", "reference_to_video"], "default": "text_to_video"},- "api_family": {"enum": ["classic", "turbo", "omni"], "default": "classic"},- "model_name": {- "enum": [- "kling-v1",- "kling-v1-5",- "kling-v1-6",- "kling-v2-master",- "kling-v2-1",- "kling-v2-1-master",- "kling-v2-5-turbo",- "kling-v2-6",- "kling-v3",- "kling-video-o1",- "kling-v3-omni"- ],- "default": "kling-v3"- },- "duration": {"enum": ["3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"], "default": "5"},- "aspect_ratio": {"enum": ["16:9", "9:16", "1:1"], "default": "16:9"},- "resolution": {"enum": ["720p", "1080p"], "default": "720p"},- "mode": {"enum": ["std", "pro", "4k"], "default": "std"},- "sound": {"enum": ["on", "off"], "default": "off"},- "negative_prompt": {"type": "string"},- "reference_image_url": {"type": "string"},- "reference_image_path": {"type": "string"},- "reference_tail_image_url": {"type": "string"},- "reference_tail_image_path": {"type": "string"},- "image_list": {"type": "array"},- "video_list": {"type": "array"},- "element_list": {"type": "array"},- "camera_control": {"type": "object"},- "watermark": {"type": "boolean", "default": False},- "callback_url": {"type": "string"},- "external_task_id": {"type": "string"},- "output_path": {"type": "string"}- }-}-```--强制规则:--- 不暴露顶层 `image_url`。-- 使用 `reference_image_url` / `reference_image_path` 表达首帧。-- 使用 `reference_tail_image_url` / `reference_tail_image_path` 表达尾帧。-- `reference_image_path` 在工具内部转 raw base64,不能走 fal.ai 上传。-- `model_variant` 可以兼容老参数,但内部主字段应是 `model_name`。-- `model_name` enum 必须来自当前 schema fixture。上面的枚举是阶段 1 初始范围;如果官方 schema 更新,先更新 fixture 和 contract 测试,再更新 input schema。-- `supports` 至少声明:--```python-{- "text_to_video": True,- "image_to_video": True,- "reference_to_video": True,- "reference_image": True,- "negative_prompt": True,- "aspect_ratio": True-}-```--### 7.3 Payload Builder 规则--Classic 文生视频:--- 端点:`POST /v1/videos/text2video`-- 发送 `model_name`、`prompt`、`negative_prompt`、`sound`、`cfg_scale`、`mode`、`camera_control`、`aspect_ratio`、`duration`、`watermark_info`、`callback_url`、`external_task_id` 等官方支持字段。-- 默认 `model_name` 建议为 `kling-v3`。--Classic 图生视频:--- 端点:`POST /v1/videos/image2video`-- 必须有 `reference_image_url` 或 `reference_image_path`。-- 将输入转换成官方字段 `image`。-- 支持尾帧时使用官方字段 `image_tail`。-- 不要盲目发送 `aspect_ratio`,除非当前 schema 明确支持。--Turbo 文生视频:--- 端点:`POST /text-to-video/kling-3.0-turbo`-- payload 结构为 `prompt`、`settings`、`options`。-- `duration` 必须从字符串转成 int。-- `settings.resolution` 支持 `720p` / `1080p`。-- `settings.aspect_ratio` 支持 `16:9` / `9:16` / `1:1`。--Turbo 图生视频:--- 端点:`POST /image-to-video/kling-3.0-turbo`-- payload 使用 `contents[]`。-- prompt 用 `{ "type": "prompt", "text": "..." }`。-- 首帧 URL 用 `{ "type": "first_frame", "url": "..." }`。-- 如果本地图片转成 raw base64 后当前官方 schema 不支持,必须给出清晰错误或先上传到可访问 URL;不要静默走 fal.ai。-- 不要盲目发送 `aspect_ratio`,除非当前 schema 明确支持。--Video Omni:--- 端点:`POST /v1/videos/omni-video`-- 第一阶段只要求基础 `prompt`、`image_list`、`video_list`、`element_list`、`sound`、`mode`、`aspect_ratio`、`duration` 可用。-- 深度多参考、多镜头 helper 放到第二阶段。--### 7.4 输出规则--成功后:--- 下载第一个无水印 `url` 到 `output_path`。-- 返回 `provider="kling_official"`。-- 返回 `model`,Classic/Omni 用 `model_name`,Turbo 可用 `kling-3.0-turbo`。-- 返回 `task_id`、`operation`、`api_family`、`output_path`。-- 将远端 URL、下载路径、任务 ID 放入 `artifacts` 或 `data`,便于复现。-- 对视频调用 `tools/video/_shared.py::probe_output(output_path)`。--失败时:--- 参数错误返回可理解的 ToolResult error,不要让 KeyError、IndexError 泄漏。-- 官方错误要保留 `code`、`message`、`request_id`。-- `1303` 并发错误文案必须包含“并发/资源包限制”。--### 7.5 成本估算--必须实现:--```python-def estimate_cost(self, params: dict[str, Any]) -> float: ...-```--要求:--- 默认 paid 输入不能返回静默 `0.0`。-- 如果官方价格无法稳定映射美元,返回保守估算,并在 dry-run 或结果 metadata 中写入 `cost_estimate_confidence="low"`。-- 成功的 paid ToolResult 必须写入 `cost_usd`。`cost_usd` 应来自同一个 `estimate_cost()` 逻辑;如果后续 Account Usage 能提供实际用量,可在阶段 2 以后用实际用量校正。-- 默认不启用 `4k`、`sound="on"`、批量、多结果等高成本能力。-- proposal/preflight 展示成本时必须说明官方可灵是 paid API。--### 7.6 Registry Metadata--视频 provider 必须补齐 registry/provider menu 可见的元数据:--- `best_for`:说明官方可灵直连适合哪些视频生成场景。-- `not_good_for`:说明不适合的场景,例如本地离线、免费生成、非可灵模型能力。-- `install_instructions`:说明配置 `KLING_API_KEY`,不要硬编码过期 URL。-- `fallback_tools`:列出可替代的视频 provider,例如现有 fal.ai Kling 或其它视频生成工具;只作为候选,不允许静默切换。-- `supports`:至少包含文生视频、图生视频、参考输入、负向提示、宽高比能力。-- `resource_profile` / `retry_policy`:如果 BaseTool 契约已有对应字段,按 API 远端生成和长轮询任务填写。-- `idempotency_key_fields`:至少考虑 `prompt`、`operation`、`api_family`、`model_name`、`reference_image_url/path`、`duration`、`aspect_ratio`。-- `side_effects`:标记为 paid remote generation,避免 proposal/preflight 把调用当作免费本地操作。--## 8. 官方图像 Provider--新增:--```text-tools/graphics/kling_official_image.py-```--基础契约:--```python-class KlingOfficialImage(BaseTool):- name = "kling_official_image"- version = "0.1.0"- tier = ToolTier.GENERATE- capability = "image_generation"- provider = "kling_official"- runtime = ToolRuntime.API- dependencies = ["env:KLING_API_KEY"]- agent_skills = ["kling-official"]-```--### 8.1 支持范围--| image_selector 语义 | `api_family` | 官方端点 |-|--------------------|--------------|----------|-| `generation_mode=generate` | `generation` | `/v1/images/generations` |-| `generation_mode=edit` 或有图片输入 | `generation` | `/v1/images/generations`,填 `image` 和 `image_reference` |-| `generation_mode=generate/edit` | `omni` | `/v1/images/omni-image` |--`image_selector` 的标准 operation 仍是 `generate` 和 `rank`。Omni 不应变成 selector 层的新 operation,应通过 `api_family=omni` 表达。--### 8.2 Input Schema 规则--建议字段:--```python-{- "required": ["prompt"],- "properties": {- "prompt": {"type": "string"},- "negative_prompt": {"type": "string"},- "operation": {"enum": ["generate"], "default": "generate"},- "generation_mode": {"enum": ["generate", "edit"], "default": "generate"},- "api_family": {"enum": ["generation", "omni"], "default": "generation"},- "model_name": {- "enum": [- "kling-v1",- "kling-v1-5",- "kling-v2",- "kling-v2-new",- "kling-v2-1",- "kling-v3",- "kling-image-o1",- "kling-v3-omni"- ],- "default": "kling-v3"- },- "image_url": {"type": "string"},- "image_path": {"type": "string"},- "image_urls": {"type": "array", "items": {"type": "string"}},- "image_paths": {"type": "array", "items": {"type": "string"}},- "image_reference": {"enum": ["subject", "face"]},- "image_fidelity": {"type": "number", "default": 0.5},- "human_fidelity": {"type": "number", "default": 0.45},- "resolution": {"enum": ["1k", "2k", "4k"], "default": "1k"},- "aspect_ratio": {"enum": ["16:9", "9:16", "1:1", "4:3", "3:4", "3:2", "2:3", "21:9", "auto"], "default": "16:9"},- "n": {"type": "integer", "default": 1},- "result_type": {"enum": ["single", "series"], "default": "single"},- "series_amount": {"type": "string"},- "element_list": {"type": "array"},- "watermark": {"type": "boolean", "default": False},- "callback_url": {"type": "string"},- "external_task_id": {"type": "string"},- "output_path": {"type": "string"}- }-}-```--图像工具可以暴露 `image_url` / `image_path`,因为 `image_selector` 没有 fal.ai 自动上传逻辑。--`model_name` enum 必须来自当前 schema fixture。上面的枚举覆盖普通图像生成和 Image Omni 的第一阶段范围;如果官方 schema 更新,先更新 fixture 和 contract 测试,再更新 input schema。--`supports` 至少声明:--```python-{- "text_to_image": True,- "image_edit": True,- "negative_prompt": True,- "aspect_ratio": True-}-```--### 8.3 Payload Builder 规则--图像生成:--- 端点:`POST /v1/images/generations`-- 必填 `prompt`。-- 支持 `negative_prompt`、`image`、`image_reference`、`image_fidelity`、`human_fidelity`、`element_list`、`resolution`、`n`、`aspect_ratio`。-- `prompt` 长度要遵守官方限制;超限应在调用前报参数错误。--图像编辑:--- 当 `generation_mode=edit` 或存在 `image_url` / `image_path` 时走同一 generation 端点。-- `image_url` 直接填官方 `image`。-- `image_path` 转 raw base64 后填官方 `image`。-- `image_reference` 只允许官方枚举,例如 `subject`、`face`。--Image Omni:--- 端点:`POST /v1/images/omni-image`-- 支持 `image_list`、`element_list`、`resolution`、`result_type`、`n`、`series_amount`、`aspect_ratio`。-- 第一阶段只要求基础可用;复杂多图引用 helper 放到第二阶段。--### 8.4 输出规则--成功后:--- 下载 `data.task_result.images[]` 中的图片。-- `data.output_path` 指向第一张图片。-- 如果 `n > 1` 或 `result_type="series"`,`artifacts` 必须返回全部图片路径。-- 根据响应 Content-Type 或 URL 推断扩展名;无法判断时默认 `.png`。-- 返回 `provider`、`model`、`task_id`、`api_family`、`output_path`。--失败时:--- 保留官方 `code`、`message`、`request_id`。-- 参数错误应清楚说明是 prompt、参考图、分辨率、数量还是权限问题。--### 8.5 成本估算--同视频 provider:--- 必须重写 `estimate_cost()`。-- 默认 paid 输入不能静默返回 `0.0`。-- `n > 1`、`2k/4k`、`series` 应提高估算。-- 估算不确定时记录 `cost_estimate_confidence="low"`。-- 成功的 paid ToolResult 必须写入 `cost_usd`。`cost_usd` 应来自同一个 `estimate_cost()` 逻辑;如果后续 Account Usage 能提供实际用量,可在阶段 2 以后用实际用量校正。--### 8.6 Registry Metadata--图像 provider 必须补齐 registry/provider menu 可见的元数据:--- `best_for`:说明官方可灵适合主体一致性、角色参考、Omni 多参考图等场景。-- `not_good_for`:说明不适合的场景,例如本地离线、免费生成、非可灵模型能力。-- `install_instructions`:说明配置 `KLING_API_KEY`,不要硬编码过期 URL。-- `fallback_tools`:列出可替代图像 provider;只作为候选,不允许静默切换。-- `supports`:至少包含文生图、图像编辑、负向提示、宽高比能力。-- `resource_profile` / `retry_policy`:如果 BaseTool 契约已有对应字段,按 API 远端生成和长轮询任务填写。-- `idempotency_key_fields`:至少考虑 `prompt`、`api_family`、`model_name`、`image_url/path`、`aspect_ratio`、`resolution`、`n`。-- `side_effects`:标记为 paid remote generation,避免 proposal/preflight 把调用当作免费本地操作。--## 9. Selector 衔接--原则:新增官方可灵 provider 不应要求重写 selector。`video_selector` 和 `image_selector` 已经通过 registry 自动发现 provider,本阶段优先只新增 provider 和 contract 测试。--不要为了可灵专用字段改 selector 的核心选择逻辑。只有当字段属于跨 provider 的通用参数,且现有 selector 会丢弃该字段时,才允许补充 selector schema 或透传列表。--`video_selector` 当前应继续使用这些通用字段:--- `prompt`-- `operation`-- `preferred_provider`-- `allowed_providers`-- `aspect_ratio`-- `duration`-- `reference_image_path`-- `reference_image_url`-- `output_path`--`image_selector` 当前应继续使用这些通用字段:--- `prompt`-- `negative_prompt`-- `generation_mode`-- `image_url`-- `image_path`-- `image_urls`-- `image_paths`-- `preferred_provider`-- `allowed_providers`-- `aspect_ratio`-- `resolution`-- `n`-- `output_path`--要求:--- `api_family`、`model_name`、`sound`、`watermark`、`image_reference` 等可灵专用参数优先放在 provider input_schema 中,通过直接调用 provider 或 selector 的普通透传进入 provider。-- 如果 selector 当前已经透传未知字段,不要仅为“可发现性”改 selector。-- 如果必须改 selector,只能做 provider-neutral 的最小透传;不得加入可灵专用分支。-- 不能破坏其他 provider 的选择和调用。-- `video_selector` 用 `preferred_provider="kling_official"` 时必须选中官方视频工具。-- `image_selector` 用 `preferred_provider="kling_official"` 时必须选中官方图像工具。-- `reference_image_path` 不能触发 `upload_image_fal()`。--## 10. 文档和 Skill 更新--本阶段必须同步更新:--```text-.env.example-README.md-docs/PROVIDERS.md-docs/ARCHITECTURE.md-.agents/skills/ai-video-gen/SKILL.md-skills/creative/video-gen-prompting.md-skills/INDEX.md-.agents/skills/kling-official/SKILL.md-```--具体要求:--- `.env.example` 增加 `KLING_API_KEY=` 和 `KLING_API_BASE_URL=`。-- `README.md` provider key 列表加入官方可灵。-- `docs/PROVIDERS.md` 新增 “Kling Official” 小节。-- `docs/PROVIDERS.md` 明确 fal.ai Kling 和 official Kling 是两个路径。-- `docs/ARCHITECTURE.md` API key 映射表加入 `KLING_API_KEY`。-- `.agents/skills/ai-video-gen/SKILL.md` metadata `env_any` 加入 `KLING_API_KEY`。-- `skills/creative/video-gen-prompting.md` 增加官方可灵适用场景和参数注意事项。-- `skills/INDEX.md` 让后续 agent 能发现 `kling-official`。-- 新增 `.agents/skills/kling-official/SKILL.md`,覆盖鉴权、任务协议、错误处理、参数、成本治理和提示注意事项。--## 11. 测试要求--新增或更新以下测试。--### 11.1 Client 测试--建议文件:--```text-tests/contracts/test_kling_official_client.py-```--覆盖:--- 未设置 `KLING_API_KEY` 时工具不可用。-- 设置 `KLING_API_KEY` 后 headers 是 `Authorization: Bearer ...`。-- base URL 默认 `https://api-singapore.klingai.com`。-- `KLING_API_BASE_URL` 可以覆盖。-- `code != 0` 抛 `KlingAPIError`,保留 `code`、`message`、`request_id`。-- `code=1303` 被识别为可重试并发错误。-- Classic create 解析 `data.task_id`。-- Classic poll 成功解析 `data.task_result.videos/images/audios[]`。-- Turbo create 解析 `data.id`。-- Turbo poll 成功解析 `data[0].outputs[]`。-- schema fixture 包含必需字段。--### 11.2 视频 Provider 测试--建议文件:--```text-tests/contracts/test_kling_official_video.py-```--覆盖:--- registry 能发现 `kling_official_video`。-- `capability="video_generation"`。-- `provider="kling_official"`。-- input schema 不包含顶层 `image_url`。-- `operation=text_to_video, api_family=classic` 构造 `/v1/videos/text2video` payload。-- `operation=image_to_video, api_family=classic` 使用 `reference_image_url/path` 构造官方 `image` 字段。-- `operation=text_to_video, api_family=turbo` 构造 `prompt/settings/options`。-- `operation=image_to_video, api_family=turbo` 构造 `contents[]`。-- `operation=reference_to_video, api_family=omni` 构造 `video_list[]` 或基础参考输入。-- 成功后下载视频、返回 artifact、调用 `probe_output`。-- `video_selector` 用 `preferred_provider="kling_official"` 能选中官方工具。-- `reference_image_path` 不触发 `upload_image_fal()`。-- `agent_skills` 包含 `kling-official`。-- 默认 paid 输入的 `estimate_cost()` 不返回静默 `0.0`。--### 11.3 图像 Provider 测试--建议文件:--```text-tests/contracts/test_kling_official_image.py-```--覆盖:--- registry 能发现 `kling_official_image`。-- `capability="image_generation"`。-- `provider="kling_official"`。-- generate payload 使用 `/v1/images/generations`。-- edit payload 将 `image_path` 转 raw base64。-- `api_family=omni` payload 使用 `/v1/images/omni-image` 和 `image_list[]`。-- 多图片结果全部写入 artifacts。-- `image_selector` 用 `preferred_provider="kling_official"` 能选中官方工具。-- `agent_skills` 包含 `kling-official`。-- 默认 paid 输入的 `estimate_cost()` 不返回静默 `0.0`。--### 11.4 文档和 Skill 测试--若仓库已有相关 contract 测试,补充:--- provider catalog 包含 `kling_official`。-- docs provider table 包含 `KLING_API_KEY`。-- `.agents/skills/ai-video-gen/SKILL.md` metadata `env_any` 包含 `KLING_API_KEY`。-- `.agents/skills/kling-official/SKILL.md` 存在。-- 官方可灵 provider 的 `agent_skills` 引用 `kling-official`。--### 11.5 Live QA--真实调用只允许显式开启:--```bash-RUN_KLING_LIVE_TESTS=1 KLING_API_KEY=... pytest tests/qa/test_kling_official_live.py-```--live smoke 限制:--- 文生图 1 张。-- 文生视频最短时长 3s 或 5s。-- 不跑批量。-- 不跑 4k。-- 不默认开声音。--## 12. 阶段验收清单--阶段 1 完成前逐项确认:--- `registry.support_envelope()` 能看到 `kling_official_video`。-- `registry.support_envelope()` 能看到 `kling_official_image`。-- 未设置 `KLING_API_KEY` 时两个工具状态为 `UNAVAILABLE`。-- setup offer 指向 `KLING_API_KEY`。-- 设置 `KLING_API_KEY` 时两个工具状态为 `AVAILABLE`。-- `video_selector` 可通过 `preferred_provider="kling_official"` 选中官方视频工具。-- `image_selector` 可通过 `preferred_provider="kling_official"` 选中官方图像工具。-- selector 没有新增可灵专用选择分支;如有 selector 改动,必须是 provider-neutral 的最小透传。-- `tools/video/kling_video.py` fal.ai 版本行为不变。-- 官方视频工具没有顶层 `image_url` schema。-- Classic 和 Turbo 两套 parser 均有 fixture 覆盖。-- schema fixture 已按当前官方 HTML/chunk 重新抽取。-- 两个官方 provider 的 `agent_skills` 都包含 `kling-official`。-- 两个官方 provider 都实现非默认 `estimate_cost()`。-- 两个官方 provider 的 paid 成功结果都写入 `ToolResult.cost_usd`。-- 两个官方 provider 都补齐 `best_for`、`not_good_for`、`install_instructions`、`fallback_tools`、`supports` 等 registry metadata。-- 图像多结果 artifacts 有测试覆盖。-- README、docs、skill 明确 fal.ai Kling 与 official Kling 的差异。-- 相关 contract 测试通过。--## 13. 完成后进入下一阶段--只有当本阶段验收清单全部完成后,才能进入第二阶段:--```text-docs/kling-official-phase-2-omni-operations.md-```--第二阶段会在本阶段 client、parser、provider 基础上增强 Omni、Elements、Account Usage 和 Callback。diff --git a/docs/kling-official-phase-2-omni-operations.md b/docs/kling-official-phase-2-omni-operations.mddeleted file mode 100644index bd56b0ae..00000000--- a/docs/kling-official-phase-2-omni-operations.md+++ /dev/null@@ -1,464 +0,0 @@-# 可灵官方 API 集成阶段 2:Omni、Elements、账户用量与 Callback--状态:实施指导文档。--来源:从 `docs/kling-official-integration-plan.md` 拆分而来。本阶段对应原计划中的 P2「Omni、元素、账户、callback」。--执行顺序:必须在 `docs/kling-official-phase-1-core.md` 完成并验收后执行。本阶段完成后再进入 `docs/kling-official-phase-3-media-avatar-effects.md`。--## 1. 阶段目标--本阶段不再解决“官方可灵能否被 OpenMontage 调用”的基础问题,而是在阶段 1 的视频、图像 provider 和共享 client 基础上增强同一个可灵官方 provider:--- 深化 Video Omni / Image Omni 支持。-- 增加 Elements 引用能力,但默认作为 `kling_official_video` / `kling_official_image` 的内部 helper,不新增 OpenMontage 管理功能。-- 增加 Account Usage 账户用量读取能力,但默认作为 provider preflight/错误诊断 helper,不新增常规 pipeline 工具。-- 规范 callback 透传和 artifacts 记录。--这些能力提高的是官方可灵 provider 的参数覆盖和诊断质量,不应该改变 OpenMontage 现有 pipeline、selector、stage artifact 或 checkpoint 流程。--## 2. 进入条件--开始本阶段前必须确认:--- 阶段 1 验收清单已完成。-- `tools/_kling/` client、errors、media、schemas 已存在并有测试覆盖。-- `kling_official_video` 和 `kling_official_image` 已能被 registry 发现。-- `preferred_provider="kling_official"` 对视频和图像 selector 均可用。-- schema fixture 已按当前官方文档刷新。-- 付费成本估算不再静默返回 `0.0`。-- fal.ai 版 `kling_video` 行为未被改变。--如果上述任一条件不满足,先回到阶段 1 修复。--## 3. 不可变规则--本阶段必须遵守:--- 不新增 pipeline。仍通过现有 provider/selector/capability 体系接入。-- 不新增 OpenMontage capability。阶段 2 的能力都挂在阶段 1 已有的 `video_generation` / `image_generation` provider 内部。-- 不更改 `provider="kling_official"` 命名。-- 不把 Elements 做成普通生成 provider,也不新增 `asset_management` capability。-- 不把 callback 作为默认执行路径。当前仍以 polling 为主,callback 是高级透传能力。-- Account Usage 不进入生产 pipeline stage,不进 selector;它只是 `tools/_kling` 下的可选诊断 helper。官方 QPS 限制为低频接口,必须做本地节流或缓存。-- Omni 深度能力必须建立在阶段 1 的 `api_family=omni` 上,不新增 selector 层 operation。-- 高成本 Omni、多参考、多元素调用必须进入成本估算。-- Omni 付费调用的成功 ToolResult 必须继续写入 `cost_usd`。如果 Account Usage 能返回可核对的实际用量,应把估算成本和实际用量的校正结果记录到 ToolResult data 或项目 artifacts。-- 所有远端结果、元素 ID、任务 ID、引用关系必须写入 artifacts 或 ToolResult data,便于复现。-- 如果官方 schema 有变化,先更新 fixture 和测试,再改实现。--## 4. 工作流 A:Omni 深度接入--阶段 1 只要求基础 Omni 可用。本阶段要让 Omni 能真正承担复杂参考输入。--### 4.1 Video Omni 增强范围--目标端点:--```text-POST /v1/videos/omni-video-GET /v1/videos/omni-video/{id}-GET /v1/videos/omni-video?pageNum=1&pageSize=30-```--增强字段:--- `image_list[].image_url`-- `image_list[].type`,例如 `first_frame`、`end_frame`-- `video_list[].video_url`-- `video_list[].refer_type`,例如 `feature`、`base`-- `video_list[].keep_original_sound`-- `element_list[].element_id`-- `multi_shot`-- `shot_type`-- `multi_prompt`-- `sound`-- `mode`-- `aspect_ratio`-- `duration`--实现要求:--- 在 `kling_official_video` 中把 Omni payload builder 拆成独立 helper,避免塞进 `execute()`。-- 支持 URL 和本地文件输入的标准化。本地图片仍由 `tools/_kling/media.py` 转换;本地视频如果官方只接受 URL,必须明确报错或要求用户提供可访问 URL,不能静默上传到 fal.ai。-- `operation=reference_to_video` 时,必须明确要求至少一种参考输入:图片、视频或 element。-- `video_list` 中的 `refer_type` 必须保留官方枚举,不要随意翻译成内部枚举后丢失原值。-- `keep_original_sound` 默认应保守设置为 `no` 或不发送,避免无意保留参考视频声音。-- `sound="on"` 属于高成本/高差异输出能力,默认不启用。-- `mode="4k"` 默认不启用。--### 4.2 Image Omni 增强范围--目标端点:--```text-POST /v1/images/omni-image-GET /v1/images/omni-image/{id}-GET /v1/images/omni-image?pageNum=1&pageSize=30-```--增强字段:--- `image_list[].image`-- `element_list[].element_id`-- `resolution`-- `result_type`-- `n`-- `series_amount`-- `aspect_ratio`-- prompt 中的 `<<<image_1>>>` 引用语法--实现要求:--- 提供 prompt reference helper,把用户输入的多图参考稳定映射为 `<<<image_1>>>`、`<<<image_2>>>` 等。-- helper 必须返回映射 metadata,例如第几个引用对应哪个 URL/path。-- 如果用户 prompt 已经包含 `<<<image_1>>>`,不要重复插入;应校验引用数量和 `image_list` 是否一致。-- `result_type="series"` 和 `series_amount` 必须进入成本估算。-- `resolution="4k"` 默认不启用。-- `aspect_ratio="auto"` 只在官方当前 schema 支持时发送。--### 4.3 多镜头 `multi_prompt`--多镜头能力要做成明确结构,不要把用户自然语言拆分后随意发送。--建议 schema:--```python-"multi_prompt": {- "type": "array",- "items": {- "type": "object",- "properties": {- "prompt": {"type": "string"},- "duration": {"type": "string"},- "camera_control": {"type": "object"},- "image_refs": {"type": "array"},- "element_refs": {"type": "array"}- },- "required": ["prompt"]- }-}-```--规则:--- `multi_shot=true` 时,普通 `prompt` 是否生效以官方 schema 为准;如果官方标注无效,不要同时依赖它。-- `shot_type` 必须为官方枚举,例如 `customize` 或 `intelligence`。-- 多镜头 payload builder 要有单元测试覆盖。-- 多镜头默认不在 selector 自动路径启用,除非用户明确传入。--### 4.4 Omni 输出处理--输出规则:--- 仍下载最终媒体到本地 output path。-- 如果官方返回多个媒体,全部写入 artifacts。-- ToolResult data 至少包含:- - `task_id`- - `api_family="omni"`- - `operation`- - `model`- - `output_path`- - `remote_outputs`- - `references_used`- - `element_ids`-- 对视频继续调用 `probe_output()`。-- 对图像继续推断文件扩展名,默认 `.png`。--## 5. 工作流 B:Elements 引用 Helper--Elements 是 Video Omni 和 Image Omni 的官方参数能力。本阶段只把它作为官方可灵 provider 的内部引用 helper,目的是让 `element_list[].element_id` 可以被视频/图像 provider 正确传入和记录。--不要在本阶段把 Elements 产品化成独立 OpenMontage 管理功能。--### 5.1 建议文件--建议只新增底层 helper:--```text-tools/_kling/elements.py-```--不建议新增 `tools/kling_elements.py`。只有当已有 pipeline 或用户工作流明确需要独立元素管理入口时,才另开设计文档讨论。--### 5.2 支持范围--本阶段的 Elements 范围只服务 `element_list[].element_id` 引用、校验和 metadata 记录。允许封装的端点应保持只读或引用校验:--```text-GET /v1/general/advanced-custom-elements/{id}-GET /v1/general/advanced-custom-elements-GET /v1/general/advanced-presets-elements-```--明确不在本阶段实现:--```text-POST /v1/general/advanced-custom-elements-POST /v1/general/delete-elements-```--原因:创建/删除 element 是素材管理功能,不是“新增可灵官方供应商”的必要路径。若后续确实需要元素生命周期管理,必须单独设计用户入口、权限、artifact 生命周期和 pipeline 使用方式,不能混在本阶段 provider 增强里。--### 5.3 Helper 契约--helper 不继承 `BaseTool`,不进入 registry,不进入 selector。--建议函数:--| helper | 用途 |-|--------|------|-| `normalize_element_list(...)` | 校验并标准化传给视频/图像 provider 的 `element_list` |-| `get_custom_element(...)` | 可选查询单个自定义元素,用于校验用户传入的 element id |-| `list_preset_elements(...)` | 可选列出官方预设元素,供诊断或文档使用 |--输入规则:--- provider 接收 `element_list` 时,只负责校验结构、透传给官方 API、记录 metadata。-- 不在默认路径创建或删除 element。-- 如果后续确实需要创建/删除 element,必须单独设计,不混在本阶段 provider 接入里。-- 对 preset elements 只读。--输出规则:--- 在 ToolResult data 中记录本次使用的 `element_ids`。-- 如查询过 element 详情,将 element metadata 写入项目 artifacts,便于复现。-- 如果官方查询响应是异步任务,使用共享 Classic parser 或新增专用 parser,不要猜字段。--### 5.4 Artifacts 约定--建议在项目中记录:--```text-projects/<project-name>/artifacts/kling_elements.json-```--结构建议:--```json-{- "provider": "kling_official",- "elements": [- {- "element_id": 123,- "kind": "character",- "name": "main-presenter",- "source": "...",- "created_at": "...",- "task_id": "...",- "reusable": true- }- ]-}-```--## 6. 工作流 C:Account Usage 诊断--Account Usage 用于官方可灵 provider 的 setup/preflight 和错误诊断,不是生产生成能力,不进入 pipeline stage。--### 6.1 建议文件--建议只新增底层 helper:--```text-tools/_kling/account.py-```--不建议新增 `tools/kling_account_usage.py`。如果后续需要用户显式运行账户诊断,再单独设计工具入口。--### 6.2 支持端点--目标端点:--```text-GET /account/costs-```--字段:--- `start_time`-- `end_time`-- `resource_pack_name`--### 6.3 使用场景--必须支持:--- provider setup/preflight 中检查资源包或余额可见性。-- 捕获 `1101` / `1102` 后提供更清楚的账户诊断。-- 在用户要求排查“为什么可灵不能生成”时提供低成本诊断。--不要求:--- 每次生成前都调用账户用量接口。-- 在 CI 中调用真实账户接口。--### 6.4 节流和缓存--规则:--- 官方 Account Usage QPS 低,必须本地节流。-- 同一进程内相同参数短时间重复查询应使用缓存。-- 如果被节流,返回“最近一次缓存结果”或清楚说明需要稍后重试。-- 不允许为了诊断在短时间内循环打账户接口。--### 6.5 输出--如果 helper 被 provider 调用,ToolResult data 建议包含:--- `resource_pack_subscribe_infos`-- `queried_range`-- `cached`-- `throttle_status`-- `provider="kling_official"`-- 如果用于校正生成成本,记录 `reconciled_cost_usd`、`cost_source` 和关联的 `task_id` 或时间窗口。--如果官方返回余额结构随资源包变化,保留原始字段,并给出轻量归一化摘要。--## 7. 工作流 D:Callback 支持--阶段 2 只要求 callback 透传和记录,不要求实现完整 callback receiver。--### 7.1 Provider 参数--视频、图像、Omni、后续音频工具都应接受:--```python-"callback_url": {"type": "string"}-```--并按官方 schema 放入对应字段:--- Classic:顶层 `callback_url`。-- Turbo:`options.callback_url`。-- 其他端点按当前 fixture 确认。--### 7.2 默认执行模式--默认仍然是 polling:--- 工具创建任务。-- 工具轮询任务到终态。-- 工具下载结果。-- 工具返回 ToolResult。--即使传入 `callback_url`,当前工具也不应立即假设 callback receiver 会写入 artifacts,除非 receiver 已明确存在并通过测试。--### 7.3 Artifacts 记录--如果传入 callback,ToolResult data 应记录:--- `callback_url`-- `callback_requested=true`-- `polling_used=true`-- `task_id`--如果后续实现 receiver,可追加:--- `callback_received_at`-- `callback_payload_path`-- `callback_status`--### 7.4 失败处理--- callback URL 无效时,优先在调用前做基本 URL 校验。-- 官方 callback 投递失败不应影响 polling 结果,只要 polling 成功。-- 如果 polling 失败但 callback 成功,必须能从 artifacts 找到 callback payload。--## 8. 文档和 Skill 更新--本阶段更新:--```text-docs/PROVIDERS.md-docs/ARCHITECTURE.md-.agents/skills/kling-official/SKILL.md-skills/INDEX.md-docs/kling-official-integration-plan.md-```--要求:--- `docs/PROVIDERS.md` 增加 Omni 深度能力、Elements、Account Usage 的说明。-- `docs/ARCHITECTURE.md` 标明 Elements 和 Account Usage 只是可灵官方 provider 的内部引用/helper 与诊断能力,不是生成 pipeline 或独立产品功能。-- `.agents/skills/kling-official/SKILL.md` 增加 Omni 引用语法、多参考输入、元素 ID 引用和 callback 注意事项。-- `skills/INDEX.md` 仅标出 Elements/Account Usage 作为 `kling_official` helper 的用途,不新增 capability 分类。-- 原总计划如果继续保留,应标注阶段 2 已拆分到本文件。--## 9. 测试要求--### 9.1 Omni 测试--覆盖:--- Video Omni 多 `image_list` payload。-- Video Omni `video_list` payload。-- Video Omni `element_list` payload。-- `reference_to_video` 无参考输入时报参数错误。-- `multi_prompt` payload。-- `sound="on"`、`mode="4k"` 成本估算提高或标记高成本。-- Image Omni 多图引用 prompt helper。-- prompt 中已有 `<<<image_1>>>` 时不重复插入。-- `result_type="series"` 多结果 artifacts。--### 9.2 Elements 测试--覆盖:--- Elements helper 不进入 registry。-- Elements helper 不挂到普通 `video_generation` / `image_generation` selector 路径。-- `element_list` 标准化和校验。-- 查询元素 payload。-- preset list payload。-- 默认路径不创建/删除 element。-- element metadata 写入 artifacts。--### 9.3 Account Usage 测试--覆盖:--- endpoint、参数和 Authorization header。-- QPS 节流。-- 相同查询缓存。-- `1101` / `1102` 错误后能触发诊断 helper 或输出建议。-- Account Usage helper 不进入 registry/selector。-- CI 默认不打真实账户接口。--### 9.4 Callback 测试--覆盖:--- Classic callback_url 顶层透传。-- Turbo callback_url 放入 `options.callback_url`。-- ToolResult 记录 `callback_requested` 和 `polling_used`。-- callback URL 基本校验。--## 10. 阶段验收清单--阶段 2 完成前逐项确认:--- Video Omni 支持多图、多视频、元素引用。-- Image Omni 支持多图引用和 series 输出。-- Omni prompt reference helper 有测试覆盖。-- 多镜头 `multi_prompt` 有测试覆盖。-- Elements helper 存在并能记录 element metadata。-- Elements helper 不进入 registry/selector。-- Account Usage helper 存在。-- Account Usage helper 不进入 registry/selector。-- Account Usage 有节流和缓存测试。-- callback_url 能在 Classic/Turbo/Omni 路径正确透传。-- callback 当前仍以 polling 为默认执行路径。-- 成本估算覆盖多参考、多结果、4k、声音等高成本参数。-- Omni paid 成功结果继续写入 `ToolResult.cost_usd`,Account Usage 可用时能记录校正信息。-- 文档和 `kling-official` skill 已更新。-- 阶段 1 的视频/图像基础测试仍通过。--## 11. 完成后进入下一阶段--只有当本阶段验收清单全部完成后,才能进入第三阶段:--```text-docs/kling-official-phase-3-media-avatar-effects.md-```--第三阶段会评估可灵官方在现有 OpenMontage capability 中还能补哪些 provider。没有现有 capability 或 pipeline 消费路径的端点默认不接。diff --git a/docs/kling-official-phase-3-media-avatar-effects.md b/docs/kling-official-phase-3-media-avatar-effects.mddeleted file mode 100644index 6eb7a8d0..00000000--- a/docs/kling-official-phase-3-media-avatar-effects.md+++ /dev/null@@ -1,561 +0,0 @@-# 可灵官方 API 集成阶段 3:TTS、音效、数字人、口型与视频特效--状态:已按本阶段边界完成 OpenMontage provider 接入;真实可灵 API 调用仍需显式 live QA 或人工端到端测试。--来源:从 `docs/kling-official-integration-plan.md` 拆分而来。本阶段对应原计划中的 P3「音频、TTS、数字人、口型、特效」。--执行顺序:必须在以下两个阶段完成后执行:--1. `docs/kling-official-phase-1-core.md`-2. `docs/kling-official-phase-2-omni-operations.md`--## 1. 阶段目标--本阶段目标是在已有 OpenMontage capability 中继续增加 `kling_official` provider 覆盖,而不是新增产品功能:--- 可灵 TTS:接入现有 `tts` capability 和 `tts_selector`。-- 可灵数字人:作为可选 provider 工具接入现有 `avatar` capability,不自动替代 `talking_head.py`。-- 可灵口型:作为可选 provider 工具接入现有 `avatar` capability,与已有 `lip_sync.py` 并存,不自动替代本地口型工具。-- 可灵音效:仅当能自然映射到现有 `music_generation` 或已有音频后期流程时才接;默认不新增 `sound_effects` capability。-- 可灵视频特效:默认不接入普通 `video_generation`,除非已有 pipeline 明确消费该类 operation;默认不新增 `video_effects` capability。--本阶段的重点是“给已有槽位增加可灵官方供应商”,不是把官方 API 的所有端点都产品化。--当前实现记录:--- 已新增 `tools/audio/kling_tts.py`,注册到 `tts` capability,并可由 `tts_selector` 通过 `preferred_provider="kling_official"` 选中。-- 已新增 `tools/avatar/kling_avatar.py`,注册到 `avatar` capability,与本地 `talking_head.py` 并存。-- 已新增 `tools/avatar/kling_lip_sync.py`,注册到 `avatar` capability,与本地 `lip_sync.py` 并存,并保留多人脸人工确认出口。-- 未新增 `kling_audio` 或 `kling_effects`,避免为当前 pipeline 引入未设计的 `sound_effects` / `video_effects` 能力面。-- 已更新 `docs/PROVIDERS.md`、`docs/ARCHITECTURE.md`、`README.md`、`skills/INDEX.md`、`.agents/skills/kling-official/SKILL.md` 和 contract tests。--注意:仓库当前只有 `tts_selector`、`image_selector`、`video_selector` 三类 selector;没有 `avatar_selector`。`avatar-spokesperson` 和 `localization-dub` pipeline 目前通过 manifest/director 显式列出 `talking_head` / `lip_sync`。因此 `kling_avatar` / `kling_lip_sync` 被 registry 发现并不等于现有 avatar pipeline 会自动消费它们。如需让现有 pipeline 使用,只能在对应 pipeline 的 `tools_available`、`optional_tools` 和 stage director tool plan 中做最小供应商选项更新,不新增 stage、canonical artifact 或新的 selector。--## 2. 进入条件--开始前必须确认:--- 阶段 1 的官方视频和图像 provider 已完成并验收。-- 阶段 2 的 Omni、Elements helper、Account Usage helper、Callback 已完成并验收。-- `tools/_kling/` client 能复用到音频、头像、口型和特效端点。-- `kling-official` skill 已覆盖任务协议、错误处理、成本治理和 Omni 引用。-- 当前官方 schema fixture 已刷新,并包含本阶段端点的核心字段。-- CI 仍默认不打真实可灵 API。--## 3. 全局规则--本阶段新增的每个工具都必须遵守:--- 继承 `BaseTool`。-- 使用 `provider="kling_official"`。-- 声明 `dependencies = ["env:KLING_API_KEY"]`。-- 声明 `runtime = ToolRuntime.API`。-- `agent_skills` 至少包含 `kling-official`,并按能力补充对应 Layer 3 skill。-- 显式实现 `estimate_cost()`,不能静默返回 `0.0`。-- 成功的 paid ToolResult 必须写入 `cost_usd`。如果阶段 2 的 Account Usage 能提供实际用量,可记录估算成本和实际用量的校正信息。-- 所有远端结果必须下载到本地 output path 或项目 artifacts。-- ToolResult 必须包含 `task_id`、`provider`、`model`、`operation`、`output_path` 或等价字段。-- 官方错误必须保留 `code`、`message`、`request_id`。-- 真实 API 测试必须由显式环境变量开启。--Selector 规则:--- TTS 可以接入 `tts_selector`。-- 音效不要伪装成长音乐生成,除非 capability 暂时只能挂到 `music_generation`,且 `best_for/not_good_for` 必须写清楚。-- 数字人和口型可以挂到 `avatar` capability,但仓库当前没有 `avatar_selector`。现有 avatar pipeline 是显式工具槽位模式,不能假设新增 provider 会自动被 pipeline 选择。-- 如果要让 `avatar-spokesperson` 或 `localization-dub` 使用 `kling_avatar` / `kling_lip_sync`,必须按现有 pipeline 规范显式更新 manifest 和 director skill 的工具选择规则;这只能是供应商选项更新,不能新增流程。-- 视频特效不应挂到普通 `video_generation` 自动选择路径。-- 本阶段默认不新增 capability。若确实需要 `sound_effects`、`video_effects` 这类新 capability,必须另写设计文档,并说明对应 pipeline、selector、artifact 和用户入口;不能混在“新增可灵供应商”任务里。--## 4. 工作流 A:可灵 TTS--### 4.1 建议文件--```text-tools/audio/kling_tts.py-```--### 4.2 Tool 契约--建议:--```python-class KlingTTS(BaseTool):- name = "kling_tts"- version = "0.1.0"- tier = ToolTier.GENERATE- capability = "tts"- provider = "kling_official"- runtime = ToolRuntime.API- dependencies = ["env:KLING_API_KEY"]- agent_skills = ["kling-official", "text-to-speech"]-```--### 4.3 API 范围--目标端点:--```text-POST /v1/audio/tts-GET /v1/audio/tts/{id}-```--核心字段:--- `text`-- `voice_id`-- `voice_language`,例如 `zh`、`en`-- `voice_speed`--结果路径:--```text-data.task_result.audios[]-```--### 4.4 实现要求--- 接入 `tts_selector`,确保 `preferred_provider="kling_official"` 可选中。-- `text` 必填,并在调用前做长度校验。-- `voice_language` 使用官方枚举,不要用自由文本。-- `voice_speed` 做范围校验。-- 如果没有传 `voice_id`,要么使用官方默认,要么返回清晰错误;不要硬编码不存在的 voice。-- 输出音频必须下载到 `output_path`。-- 如果返回多个音频,全部写入 artifacts,`data.output_path` 指向第一条。-- 记录 `voice_id`、`voice_language`、`voice_speed`。--### 4.5 测试--覆盖:--- registry 能发现 `kling_tts`。-- `capability="tts"`。-- `provider="kling_official"`。-- `tts_selector` 可通过 `preferred_provider="kling_official"` 选中。-- payload 字段正确。-- 成功结果下载音频。-- `agent_skills` 包含 `kling-official`。-- `estimate_cost()` 不静默返回 `0.0`。--## 5. 工作流 B:可灵音效--### 5.1 建议文件--```text-tools/audio/kling_audio.py-```--### 5.2 Capability 决策--实施前必须做一次“是否接入现有能力槽位”的决策:--| 选择 | 适用情况 | 要求 |-|------|----------|------|-| 接入 `music_generation` | 官方返回内容能满足现有音乐/音频生成 stage 的消费方式 | `best_for/not_good_for` 必须写明它偏音效,不是长音乐生成 |-| 暂不接入 | 端点更像短音效或视频后期声音,不符合现有 pipeline 消费方式 | 只在 `kling-official` skill 和后续计划中记录,不新增工具 |--推荐:默认暂不接入,除非现有 pipeline 明确需要该 provider。不要在本阶段新增 `sound_effects` capability。--### 5.3 API 范围--文生音效:--```text-POST /v1/audio/text-to-audio-GET /v1/audio/text-to-audio/{id}-```--核心字段:--- `prompt`-- `duration`--视频生音效:--```text-POST /v1/audio/video-to-audio-GET /v1/audio/video-to-audio/{id}-```--核心字段:--- `video_id` 或 `video_url`-- `sound_effect_prompt`-- `bgm_prompt`-- `asmr_mode`--结果路径:--```text-data.task_result.audios[]-```--视频生音效也可能返回 videos,必须按当前 schema fixture 处理。--### 5.4 实现要求--- 使用 `operation` 区分 `text_to_audio` 和 `video_to_audio`。-- 如果接入 `music_generation`,必须保证现有音乐 stage 能消费输出;否则不要接入 registry,只保留在官方 skill/后续计划里。-- `text_to_audio` 必须有 `prompt`。-- `video_to_audio` 必须有 `video_id` 或 `video_url`。-- 如果输入本地视频而官方只接受 URL,必须明确要求 URL 或先实现官方支持的上传路径;不能静默使用其它 provider。-- 输出音频必须下载到本地。-- 如果返回视频,也要下载并放入 artifacts。-- `duration` 必须进入成本估算。-- `asmr_mode`、bgm、长时长属于更高成本/更强效果差异参数,默认不启用。--### 5.5 测试--覆盖:--- 如果接入现有 capability,registry 能发现音效 provider。-- 如果暂不接入,文档明确“不接入当前 registry”的理由。-- `text_to_audio` payload。-- `video_to_audio` payload。-- 无必需输入时报参数错误。-- 多音频 artifacts。-- 如返回视频,视频 artifacts。-- 不被普通 TTS 或普通音乐流程误选;如果无法保证,则不接入 registry。-- `estimate_cost()` 不静默返回 `0.0`。--## 6. 工作流 C:可灵数字人--### 6.1 建议文件--```text-tools/avatar/kling_avatar.py-```--### 6.2 Tool 契约--建议:--```python-class KlingAvatar(BaseTool):- name = "kling_avatar"- version = "0.1.0"- tier = ToolTier.GENERATE- capability = "avatar"- provider = "kling_official"- runtime = ToolRuntime.API- dependencies = ["env:KLING_API_KEY"]- agent_skills = ["kling-official", "avatar-video"]-```--### 6.3 API 范围--目标端点:--```text-POST /v1/videos/avatar/image2video-GET /v1/videos/avatar/image2video/{id}-```--核心字段:--- `image`-- `audio_id` 或 `sound_file`-- `prompt`-- `mode`,例如 `std`、`pro`--结果路径:--```text-data.task_result.videos[]-```--### 6.4 实现要求--- 与本地 `talking_head.py` 并存,不替代本地工具。-- 官方工具适合云端高质量数字人;本地工具适合无 API 成本、离线可控。-- 不修改 `talking_head.py` 的行为,不把 `kling_avatar` 包装成 `talking_head` 的内部分支。-- 如果需要在 `avatar-spokesperson` 中启用,只在现有 pipeline 的工具列表和 director 决策里增加一个可选供应商路径;不改变 scene_plan、asset_manifest 或 checkpoint 契约。-- 输入头像图片可接受 URL 或本地路径;本地路径按官方要求转 raw base64 或报清晰错误。-- 音频可以使用 `audio_id` 或 `sound_file`,具体字段按当前 schema fixture。-- `mode="pro"` 进入成本估算。-- 输出视频必须下载到本地,并调用 `probe_output()`。-- ToolResult 记录头像来源、音频来源、模式、任务 ID。--### 6.5 测试--覆盖:--- registry 能发现 `kling_avatar`。-- `capability="avatar"`。-- payload 使用头像和音频字段。-- 缺少头像或音频时报参数错误。-- 成功后下载视频并 probe。-- 与本地 `talking_head.py` 不冲突。-- 若更新了 `avatar-spokesperson`,测试或文档必须证明它是显式选择 `kling_avatar`,不是靠 registry 自动替换 `talking_head`。-- `estimate_cost()` 不静默返回 `0.0`。--## 7. 工作流 D:可灵口型--### 7.1 建议文件--```text-tools/avatar/kling_lip_sync.py-```--### 7.2 流程--口型生成至少分两步:--1. 识别人脸:--```text-POST /v1/videos/identify-face-```--输入:--- `video_id` 或 `video_url`--输出:--- `data.session_id`-- face 信息列表--2. 生成口型:--```text-POST /v1/videos/advanced-lip-sync-GET /v1/videos/advanced-lip-sync/{id}-```--输入:--- `session_id`-- `face_choose[]`-- `audio_id` 或 `sound_file`--输出:--```text-data.task_result.videos[]-```--### 7.3 Tool 契约--建议:--```python-class KlingLipSync(BaseTool):- name = "kling_lip_sync"- version = "0.1.0"- tier = ToolTier.GENERATE- capability = "avatar"- provider = "kling_official"- runtime = ToolRuntime.API- dependencies = ["env:KLING_API_KEY"]- agent_skills = ["kling-official", "avatar-video"]-```--### 7.4 人脸选择规则--口型 face 选择可能影响输出人物,必须保留人工确认出口。--规则:--- 如果用户明确传入 `face_id` 或 `face_choose`,直接使用。-- 如果未传入,工具可以返回 face list 并要求上层确认。-- 如果实现自动选择,只能作为显式参数启用,例如 `auto_select_face=True`。-- 自动策略应选择最大或最居中的 face,并在 ToolResult 中记录选择理由。-- 不允许在多人视频中静默选择第一张脸。--### 7.5 Artifacts--建议记录:--```text-projects/<project-name>/artifacts/kling_lip_sync_faces.json-```--内容:--- `session_id`-- face list-- 每个 face 的位置、大小、置信度等官方字段-- 选中的 face-- 选择方式:`user_selected` 或 `auto_selected`--### 7.6 实现要求--- 识别人脸和生成口型可以是同一个工具的不同 operation,也可以拆 helper。-- `identify_face` operation 可以只返回 face list,不生成视频。-- `advanced_lip_sync` operation 必须有 `session_id` 和音频输入。-- 一站式 operation 可以执行识别、选择、生成,但多人场景必须遵守人工确认规则。-- 不修改 `lip_sync.py` 的行为,不把 `kling_lip_sync` 包装成 `lip_sync` 的内部分支。-- 如果需要在 `localization-dub` 或 `avatar-spokesperson` 中启用,只在现有 pipeline 的工具列表和 director 决策里增加一个可选供应商路径;不改变 artifact schema 或 stage 顺序。-- 输出视频下载到本地,并调用 `probe_output()`。-- 成本估算要覆盖识别和生成两个步骤。--### 7.7 测试--覆盖:--- `identify_face` payload。-- face list 解析。-- 无 face 时报清晰错误。-- 多 face 未启用自动选择时不静默继续。-- `auto_select_face=True` 时记录选择理由。-- `advanced_lip_sync` payload。-- 成功后下载视频并 probe。-- 若更新了 `localization-dub` 或 `avatar-spokesperson`,测试或文档必须证明它是显式选择 `kling_lip_sync`,不是靠 registry 自动替换 `lip_sync`。-- `estimate_cost()` 不静默返回 `0.0`。--## 8. 工作流 E:可灵视频特效--### 8.1 建议文件--```text-tools/video/kling_effects.py-```--### 8.2 Capability 决策--视频特效不是普通 text-to-video,也不是通用 image-to-video。--本阶段默认不接入 `kling_effects`,原因是现有 `video_selector` 的标准 operation 是 `text_to_video`、`image_to_video`、`reference_to_video`、`rank`,视频特效没有稳定的 pipeline 消费路径。--只有满足以下条件时才允许接入:--- 已有 pipeline 或 stage 明确需要视频特效 operation。-- 已定义该 operation 如何进入 stage artifact。-- 不新增普通视频生成选择分支。-- 不让 `video_selector` 在 `text_to_video` / `image_to_video` / `reference_to_video` 中自动选择它。--不要在本阶段新增 `video_effects` capability。若确实需要,应另写设计文档。--### 8.3 API 范围--目标端点:--```text-POST /v1/videos/effects-GET /v1/videos/effects/{id}-```--核心字段:--- `effect_scene`-- `input.image`-- `input.images`--结果路径:--```text-data.task_result.videos[]-```--### 8.4 实现要求--默认不实现。若满足上面的接入条件:--- 使用 `operation="video_effect"` 或更具体的 effect operation。-- `effect_scene` 必须是官方枚举或 fixture 中记录的有效值。-- 必须有输入图片,除非官方某个 effect 明确不需要。-- 支持单图和多图输入。-- 本地图片转 raw base64 或按官方要求处理。-- 输出视频下载到本地,并调用 `probe_output()`。-- `best_for` 写清楚它适合特效模板,不适合普通视频生成。-- `not_good_for` 写清楚不要用于普通叙事视频、解释器视频、连续镜头生成。--### 8.5 测试--覆盖:--- 如果实现,registry 路由方式被文档和测试固化。-- 如果不实现,阶段验收中明确记录“不接入当前 registry”的理由。-- 普通 `video_selector` text_to_video 不会误选 `kling_effects`。-- effect payload。-- 缺少图片或 effect_scene 时报参数错误。-- 成功后下载视频并 probe。-- `estimate_cost()` 不静默返回 `0.0`。--## 9. 文档和 Skill 更新--本阶段更新:--```text-docs/PROVIDERS.md-docs/ARCHITECTURE.md-README.md-skills/INDEX.md-.agents/skills/kling-official/SKILL.md-```--要求:--- `docs/PROVIDERS.md` 增加已接入的 TTS、数字人、口型 provider;音效和特效若不接入,只记录为官方 API 未映射端点。-- `docs/ARCHITECTURE.md` 只标明现有 capability 的 provider 扩展;不要描述未落地的新 capability。-- `README.md` provider key 列表不重复,只保留 `KLING_API_KEY` / `KLING_API_BASE_URL` 说明。-- `skills/INDEX.md` 能让 agent 发现对应能力。-- 若让现有 avatar pipeline 消费 `kling_avatar` / `kling_lip_sync`,对应 `pipeline_defs/` 和 `skills/pipelines/...` 只记录供应商选择规则,不新增 pipeline 阶段或 canonical artifact。-- `.agents/skills/kling-official/SKILL.md` 增加:- - TTS voice 参数注意事项。- - 音效 prompt 注意事项,以及默认不新增 `sound_effects` capability 的原因。- - 数字人头像/音频输入注意事项。- - 口型 face 选择规则。- - 视频特效默认不接入普通 `video_generation` 的警告。--## 10. 测试总要求--新增或更新:--```text-tests/contracts/test_kling_tts.py-tests/contracts/test_kling_avatar.py-tests/contracts/test_kling_lip_sync.py-```--可选测试:--- 如果 `kling_audio` 接入现有 capability,新增 `tests/contracts/test_kling_audio.py`。-- 如果 `kling_effects` 有明确 pipeline 消费路径并被实现,新增 `tests/contracts/test_kling_effects.py`。--本阶段默认不新增 capability。如果后续单独设计了新 capability,该设计必须自带 registry、provider menu、selector 或非 selector 路由测试。--Live QA 必须显式开启:--```bash-RUN_KLING_LIVE_TESTS=1 KLING_API_KEY=... pytest tests/qa/test_kling_official_live.py-```--live smoke 限制:--- 每类能力只跑最小调用。-- 不跑批量。-- 不默认使用高成本模式。-- 不在 CI 默认开启。--## 11. 阶段验收清单--阶段 3 完成前逐项确认:--- `kling_tts` 存在并接入 `tts_selector`。-- `kling_audio` 只有在能映射到现有 capability 时才存在;否则验收记录为“暂不接入,避免新增功能面”。-- `kling_avatar` 存在,并与本地 `talking_head.py` 并存;除非现有 pipeline 显式加入它,否则不要求 pipeline 自动消费。-- `kling_lip_sync` 存在,并保留 face 人工选择出口;除非现有 pipeline 显式加入它,否则不要求 pipeline 自动消费。-- `kling_effects` 默认不存在;若存在,必须证明不会被普通视频生成误选,并说明对应 pipeline 消费路径。-- 每个新增工具都声明 `provider="kling_official"`。-- 每个新增工具都声明 `dependencies = ["env:KLING_API_KEY"]`。-- 每个新增工具都包含 `agent_skills = ["kling-official", ...]` 或等价配置。-- 每个新增工具都实现非默认 `estimate_cost()`。-- 每个新增 paid 工具的成功 ToolResult 都写入 `cost_usd`。-- 每个新增工具都有 contract 测试。-- 真实 API 测试默认不进 CI。-- 文档、skill、provider table 已更新。-- 阶段 1 和阶段 2 的测试仍通过。--## 12. 全项目完成标准--三阶段全部完成后,OpenMontage 的可灵官方 API 集成应达到:--- 官方可灵每个主要能力族都有明确实现或不接入理由。-- 视频、图像和已接入现有 OpenMontage capability 的 TTS、数字人、口型等能力有实现和测试;未接入端点有清楚的不接入理由。-- selector 或现有 stage routing 不会在不适合的 operation 中误选特效、口型、音效工具。-- 付费调用默认不进 CI,live QA 需要显式环境变量开启。-- 所有新增工具遵守 OpenMontage 的 BaseTool 契约、artifact 路径和项目目录约定。-- fal.ai Kling 和 official Kling 在 provider 命名、文档、skill 和 selector 使用上清楚分离。-- 未新增 pipeline、stage、canonical artifact 或未设计的新 capability。diff --git a/tests/contracts/test_kling_official_core.py b/tests/contracts/test_kling_official_core.pyindex a215b9ef..7e38708b 100644--- a/tests/contracts/test_kling_official_core.py+++ b/tests/contracts/test_kling_official_core.py@@ -371,7 +371,7 @@ def test_architecture_env_mapping_includes_kling_official():assert "`KLING_API_BASE_URL` | kling_official_video, kling_official_image, kling_tts, kling_avatar, kling_lip_sync" in architectureassert "Elements and Account" in architectureassert "not separate pipeline stages" in architecture- assert "Kling Official Phase 3 adds provider tools only where OpenMontage already has a" in architecture+ assert "Kling Official also adds provider tools only where OpenMontage already has a" in architecturedef test_ai_video_skill_metadata_and_new_skill_link():