Skill: zoucdr/feed-designs-you-video-gen (version 1.0.0)

--- name: feed-designs-you-video-gen version: 1.0.0 description: "Create vertical algorithm-control shorts: five equal caption beats across the runtime, UI/data-stream montage (WeryAI). Use for attention-economy critique, doomscroll hooks, or feed-steering rhetoric. Use when the user says the app chooses for them. SEO: algorithm control video; feed manipulation video." tags: [algorithm, social-media, tech, psychology, hooks, subtitles, short-video, video-gen] metadata: { "openclaw": { "emoji": "📱", "primaryEnv": "WERYAI_API_KEY", "paid": true, "network_required": true, "requires": { "env": ["WERYAI_API_KEY"], "bins": ["node"], "node": ">=18" } } } user-invocable: true --- # You’re being designed (scroll → log → steer) **Template (five equal segments; list exact seconds for the chosen `duration`, e.g. 10 → 2s each, 15 → 3s each):** - **Segment 1** — *YOU THINK YOU’RE SCROLLING* (or *YOU’RE NOT REALLY CHOOSING*). - **Segment 2** — *THE FEED IS SCROLLING YOU* (or equivalent flip). - **Segment 3** — *EVERY PAUSE GETS LOGGED*. - **Segment 4** — *LAYOUT NUDGES YOU*. - **Segment 5** — *THEY STEER WHAT YOU SEE*. User may **swap wording** but **must keep five windows** unless they explicitly compress (then show **full** custom schedule in confirmation). Default **`duration`** is **10** when unspecified. **Dependencies:** `WERYAI_API_KEY` + Node.js 18+. **`{baseDir}/scripts/video_gen.js`** + **[`WERYAI_VIDEO_API.md`](resources/WERYAI_VIDEO_API.md)**. **No other Cursor skills required.** ## Prerequisites - `WERYAI_API_KEY` **must be set**; Node **18+**; `https` images only. - Non-empty `model`. ## Security, secrets, and API hosts - **`WERYAI_API_KEY`**: Secret; **`requires.env`** / **`primaryEnv`**. - **API hosts** fixed in `video_gen.js`. ## Prompt expansion (mandatory) - **Duration:** Default **10**; **5** or **15** when allowed and requested. For **five equal beats**, each caption span = **`duration / 5`** seconds (state numeric ranges explicitly in the prompt). - **Timeline scaling:** If merging to fewer than five lines, list **new non-overlapping** windows in the confirmation table. **Visuals:** Thumb on glass, **tiles exploding** into **data streams**, **recommendation grid**, **heatmap vibe**, **dark mode neon** accents, **glitch** tastefully; **hook in the first segment** must be **visually loud**. **Typography:** Bold sans, white + black outline, lower third, **no overlap** between the five lines. **Motion:** **Continuous**—scroll inertia, parallax UI, particles. **Audio:** Sub pulse, digital risers if `generate_audio` true. **Negatives (Kling):** illegible HUD text, watermark, crowded captions. **Language:** **English** on screen unless user requests otherwise. **Confirmation:** Full expanded `prompt` with **explicit non-overlapping second ranges** for all five lines (derive from `duration`). ### Niche checklist - Reads as **critique of systems**, not attacks on **named individuals**. - Avoid implying **illegal surveillance** claims unless user explicitly frames fiction. ## Workflow 1. Text / image / multi-image (**SEEDANCE_2_0**, ≤3). 2. Collect optional **wording tweaks**; default to template lines if user says “use default.” 3. Expand → validate → confirm → `wait`. 4. **`[Video](url)`** only for links. ## CLI reference ~~~sh node {baseDir}/scripts/video_gen.js wait --json '{"model":"KLING_V3_0_PRO","prompt":"…","duration":10,"aspect_ratio":"9:16","generate_audio":true,"negative_prompt":"illegible text, watermark, garbled captions"}' node {baseDir}/scripts/video_gen.js wait --json '{"model":"SEEDANCE_2_0","prompt":"…","duration":10,"aspect_ratio":"9:16","resolution":"720p","generate_audio":true}' ~~~ **Full reference:** **[`WERYAI_VIDEO_API.md`](resources/WERYAI_VIDEO_API.md)**. ## Definition of done **[Video](url)** or error; **five** timed English lines present in `prompt`, with **numeric second ranges** matching the chosen **`duration`**. ## Boundaries (out of scope) - Not factual **platform internals** documentation—**rhetorical short** only. - **`resources/WERYAI_VIDEO_API.md`** for CLI; no `negative_prompt` on Seedance. - **Multi-image** only **SEEDANCE_2_0**, max **3**. ### Example prompts - `Default five-beat feed paranoia, cyberpunk UI` - `Softer aesthetic: pastel social app, same five captions` - `Screenshot-style image URL → animate with same subtitle schedule` - `Parental controls aesthetic but same five-beat ‘who’s really in control’ lines` --- ## Model and API constraints (frozen for this skill) ### Text-to-video | model_key | durations | aspect_ratios | resolutions | audio | negative_prompt | prompt limit | |-----------|-----------|---------------|-------------|-------|-----------------|--------------| | KLING_V3_0_PRO | 5, 10, 15 | 9:16, 1:1, 16:9 | *(omit)* | yes | yes | 2000 | | KLING_V3_0_STA | 5, 10, 15 | 9:16, 1:1, 16:9 | *(omit)* | yes | yes | 2000 | | SEEDANCE_2_0 | 5, 10, 15 | 9:16, 1:1, 16:9 | 480p, 720p | yes | no | 2000 | ### Image-to-video | model_key | durations | aspect_ratios | resolutions | audio | negative_prompt | image slots | |-----------|-----------|---------------|-------------|-------|-----------------|-------------| | KLING_V3_0_PRO | 5, 10, 15 | 9:16, 16:9, 1:1 | *(omit)* | yes | yes | single `image` | | KLING_V3_0_STA | 5, 10, 15 | 9:16, 16:9, 1:1 | *(omit)* | yes | yes | single `image` | | SEEDANCE_2_0 | 5, 10, 15 | 9:16, 1:1, 16:9 | 480p, 720p | yes | no | up to **3** `images` | ## Recommended models | Tier | model_key | Default duration | |------|-----------|------------------| | ⭐ Best | KLING_V3_0_PRO | 10 | | 👍 Good | KLING_V3_0_STA | 10 | | ⚡ Fast | SEEDANCE_2_0 | 10 (`resolution`: **720p**) | ## Default parameters | Field | Value | |-------|--------| | aspect_ratio | 9:16 | | duration | 10 | | generate_audio | true | | resolution | 720p (Seedance) | | negative_prompt | Kling: `illegible text, garbled captions, watermark, HUD clutter` | ## Text-to-video (primary) Default **five-line** schedule unless user overrides with a written table. ## Image-to-video (optional) Phone UI still → **animate** with parallax + same captions. ## Tips - First **2s** should **sync a hard cut** to the first caption. - Shorter words survive model text rendering better. > Packaged as **`feed-designs-you-video-gen`**.

path: eval.yaml
content: version: "1"
defaults:
  trials: 5
  timeout: 600
  threshold: 0.8
skill: "feed-designs-you-video-gen"
trigger_tests:
  - id: explicit-invoke
    should_trigger: true
    prompt: "Use feed-designs-you-video-gen for a vertical about the algorithm controlling attention—five on-screen lines with exact timing."
  - id: implicit-domain
    should_trigger: true
    prompt: "You’re not choosing—the app is: scrolling phone, data streams, recommendations, English captions on tight beats, 9:16."
  - id: implicit-paraphrase
    should_trigger: true
    prompt: "Doomscroll critique Short: five caption beats dividing total runtime equally, UI montage, no VO script."
  - id: negative-control
    should_trigger: false
    prompt: "Add unit tests for my date parser."
outcome_tests:
  - id: layout
    type: deterministic
    checks:
      - file_exists: "SKILL.md"
      - file_exists: "eval.yaml"
  - id: prompt-expansion-required
    type: llm_rubric
    rubric: |
      SKILL.md must define five-segment caption template derived from duration, mandatory prompt expansion, and confirmation before WeryAI submit.


path: resources/WERYAI_VIDEO_API.md
content: # WeryAI video CLI & JSON (`video_gen.js`)

Shipped at **`{baseDir}/resources/WERYAI_VIDEO_API.md`** (next to `SKILL.md`). Run the CLI from **`{baseDir}/scripts/video_gen.js`**. Node.js **18+** required.

## Environment

- **`WERYAI_API_KEY`** (required for `models`, generation, and `status`, except `--dry-run`): bearer token for HTTPS requests. Never commit the value.
- **No other environment variables** are read by this script. API hosts and poll timing are fixed in `video_gen.js` source.

## API hosts (fixed)

- Video tasks: `https://api.weryai.com`
- Models registry: `https://api-growth-agent.weryai.com`

## `models` — fetch model metadata (JSON on stdout)

Run from the skill root (`{baseDir}`):

```sh
node {baseDir}/scripts/video_gen.js models
node {baseDir}/scripts/video_gen.js models --mode text_to_video
node {baseDir}/scripts/video_gen.js models --mode image_to_video
node {baseDir}/scripts/video_gen.js models --mode multi_image_to_video
```

Typical fields per model (names as returned by the API): `model_key`, `title`, `durations`, `aspect_ratios`, `resolutions`, `has_generate_audio`, `has_negative_prompt`, `prompt_length_limit`; image / multi-image modes may include `support_multiple_images`, `support_first_last_frame`, `upload_image_limit`, etc.

Use this output to fill **`## Model and API constraints`** in the skill’s `SKILL.md`. Do not send fields (e.g. `resolution`, `aspect_ratio`) that the chosen model does not support.

## `wait` — submit and block until done (polls status)

```sh
node {baseDir}/scripts/video_gen.js wait --json '{"model":"KLING_V3_0_PRO","prompt":"...","duration":5,"aspect_ratio":"9:16"}'
node {baseDir}/scripts/video_gen.js wait --json '{"model":"...","prompt":"...","image":"https://...","duration":5}'
node {baseDir}/scripts/video_gen.js wait --json '{"model":"...","prompt":"...","images":["https://..."],"duration":5}'
node {baseDir}/scripts/video_gen.js wait --json '...' --dry-run
```

## `submit-*` — submit only (async; no wait)

```sh
node {baseDir}/scripts/video_gen.js submit-text --json '{"model":"…","prompt":"…","duration":5}'
node {baseDir}/scripts/video_gen.js submit-image --json '{"model":"…","prompt":"…","image":"https://…","duration":5}'
node {baseDir}/scripts/video_gen.js submit-multi-image --json '{"model":"…","prompt":"…","images":["https://…"],"duration":5}'
```

## `status` / `batch-status`

```sh
node {baseDir}/scripts/video_gen.js status --task-id <id>
node {baseDir}/scripts/video_gen.js batch-status --batch-id <id>
```

Task id / batch id can also be passed inside JSON for some flows; see `video_gen.js` usage text.

## Common JSON fields

| Field | Notes |
|--------|--------|
| `model` | Model key; **required** for `wait`, `submit-*`, and for `--dry-run` when `prompt` is present—if omitted or empty, the script returns `MISSING_PARAM` (no default model). **The script does not enforce** per-skill model rules from `SKILL.md`—callers must pass the model required by that skill. |
| `prompt` | Required for `wait` and `submit-*` |
| `duration` | Must be allowed for the model |
| `aspect_ratio` | Only if supported |
| `resolution` | Only if supported |
| `generate_audio` | Only if supported |
| `negative_prompt` | Only if supported |
| `image` | Public **https** URL (single image) |
| `images` | Array of public **https** URLs (multi-image) |

## Status response (conventions)

- HTTP OK with business `status === 0`: query succeeded.
- `data` may be a single object or an array of tasks; the script matches `task_id` or uses the first item.
- In progress: `phase` may be `running`, `inProgress: true`.
- Errors: stdout JSON with `ok: false`, `errorCode`, `errorMessage` (prefers API `message` / `desc`).

## Stdout JSON (generation / wait)

Common keys: `ok`, `phase`, `taskId`, `batchId`, `taskIds`, `videos` (`url`, `cover_url`), `tasks` (batch), `inProgress`, `errorCode`, `errorMessage`.

---

**Per-skill rules** in `SKILL.md` (prompt expansion, confirmation table, niche tables) still apply; this file only documents the **CLI and request shape**.


path: scripts/video_gen.js
content: #!/usr/bin/env node
/**
 * WeryAI 视频生成 — 通用 CLI（零 npm 依赖，需 Node.js 18+）
 *
 * 命令:
 *   wait | submit-text | submit-image | submit-multi-image | status | models
 *
 * 示例:
 *   node video_gen.js models
 *   node video_gen.js models --mode text_to_video
 *   node video_gen.js wait --json '{"model":"WERYAI_VIDEO_1_0","prompt":"...","duration":5}'
 *   node video_gen.js wait --json '...' --dry-run
 *
 * 环境变量:
 *   WERYAI_API_KEY（models / 生成 / status 必填；--dry-run 除外）— 敏感凭据，勿写入仓库；registry 元数据声明见同目录 SKILL.md。
 *   本脚本仅读取上述密钥；API 主机与轮询间隔为固定常量，勿用其他 env 覆盖。
 */

const BASE_URL = 'https://api.weryai.com';
const MODELS_BASE_URL = 'https://api-growth-agent.weryai.com';
const MODELS_API_PATH = '/growthai/v1/video/models';
const POLL_INTERVAL_MS = 6000;
const POLL_TIMEOUT_MS = 600000;

const STATUS_MAP = {
  waiting: 'waiting',
  WAITING: 'waiting',
  pending: 'waiting',
  PENDING: 'waiting',
  processing: 'processing',
  PROCESSING: 'processing',
  succeed: 'completed',
  SUCCEED: 'completed',
  success: 'completed',
  SUCCESS: 'completed',
  failed: 'failed',
  FAILED: 'failed',
};

const ERROR_MESSAGES = {
  400: 'Bad request — check your request parameters.',
  403: 'Invalid API key or IP access denied — verify WERYAI_API_KEY is correct.',
  500: 'WeryAI server error. Please try again later.',
  1001: 'Request rate limit exceeded — slow down and retry after a moment.',
  1002: 'Parameter error — check prompt, image URLs, aspect_ratio, model key, and duration.',
  1003: 'Resource not found — the task_id may not exist or has expired.',
  1006: 'Model not supported — check the model key or try a different model.',
  1007: 'Queue full — the service is busy, please try again later.',
  1011: 'Insufficient credits — recharge at weryai.com.',
  2003: 'Content flagged by safety system — revise your prompt or input image.',
  2004: 'Image format not supported — use jpg, png, or webp.',
  6004: 'Generation failed — please try again later.',
  6010: 'Concurrent task limit reached (max 20) — wait for existing tasks to complete.',
};

function log(msg) {
  process.stderr.write(`[weryai] ${msg}\n`);
}

function sleep(ms) {
  return new Promise((r) => setTimeout(r, ms));
}

async function httpJson(method, fullUrl, body, apiKey) {
  const headers = {
    Authorization: `Bearer ${apiKey}`,
    'Content-Type': 'application/json',
  };
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 30_000);
  try {
    const res = await fetch(fullUrl, {
      method,
      headers,
      body: body != null ? JSON.stringify(body) : undefined,
      signal: controller.signal,
    });
    clearTimeout(timer);
    let data;
    try {
      data = await res.json();
    } catch {
      data = { status: res.status, msg: `Non-JSON response (HTTP ${res.status})` };
    }
    return { httpStatus: res.status, ...data };
  } catch (err) {
    clearTimeout(timer);
    if (err.name === 'AbortError') {
      throw new Error(`Request timeout: ${method} ${fullUrl}`);
    }
    throw err;
  }
}

async function apiRequest(method, path, body, apiKey) {
  return httpJson(method, BASE_URL + path, body, apiKey);
}

async function fetchModelsRegistry(apiKey) {
  return httpJson('GET', MODELS_BASE_URL + MODELS_API_PATH, null, apiKey);
}

function isApiSuccess(res) {
  const httpOk = res.httpStatus >= 200 && res.httpStatus < 300;
  const bodyOk = res.status === 0 || res.status === 200;
  return httpOk && bodyOk;
}

function formatApiError(res) {
  const httpStatus = res.httpStatus || 0;
  const code = res.status;
  const msg = res.msg || '';

  if (httpStatus === 403) {
    return {
      ok: false,
      phase: 'failed',
      errorCode: '403',
      errorMessage: ERROR_MESSAGES[403] + (msg ? ` (${msg})` : ''),
    };
  }
  if (httpStatus === 429) {
    return {
      ok: false,
      phase: 'failed',
      errorCode: 'RATE_LIMIT',
      errorMessage: 'Rate limited by WeryAI API. Please wait and try again.',
    };
  }
  if (httpStatus >= 500) {
    return {
      ok: false,
      phase: 'failed',
      errorCode: '500',
      errorMessage: `${ERROR_MESSAGES[500]} (HTTP ${httpStatus})`,
    };
  }
  if (httpStatus === 400) {
    return {
      ok: false,
      phase: 'failed',
      errorCode: '400',
      errorMessage: ERROR_MESSAGES[400] + (msg ? ` (${msg})` : ''),
    };
  }

  const friendly = ERROR_MESSAGES[code] || '';
  const message =
    friendly && msg
      ? `${friendly} (${msg})`
      : friendly || msg || `API error (status: ${code}, HTTP ${httpStatus})`;

  return {
    ok: false,
    phase: 'failed',
    errorCode: code != null ? String(code) : null,
    errorMessage: message,
  };
}

function detectMode(params) {
  if (Array.isArray(params.images) && params.images.length > 0) return 'multi_image';
  if (typeof params.image === 'string' && params.image) return 'image';
  return 'text';
}

function coerceBool(v, defaultVal = false) {
  if (v == null) return defaultVal;
  if (typeof v === 'boolean') return v;
  return String(v).toLowerCase() === 'true';
}

function hasNonEmptyModel(params) {
  const m = params.model;
  return m != null && String(m).trim() !== '';
}

function buildRequestBody(params) {
  const model = String(params.model).trim();
  const body = {
    prompt: params.prompt,
    model,
    duration: Number(params.duration) || 5,
  };
  if (params.aspect_ratio) body.aspect_ratio = params.aspect_ratio;
  if (params.resolution) body.resolution = params.resolution;
  if (params.generate_audio != null) body.generate_audio = coerceBool(params.generate_audio, false);
  if (params.negative_prompt) body.negative_prompt = params.negative_prompt;
  if (params.image) body.image = params.image;
  if (params.images) body.images = params.images.slice(0, 3);
  return body;
}

async function submitTask(params, apiKey) {
  if (!hasNonEmptyModel(params)) {
    return {
      ok: false,
      phase: 'failed',
      errorCode: 'MISSING_PARAM',
      errorMessage: "'model' is required in JSON parameters (no default model).",
    };
  }
  const mode = detectMode(params);
  const pathMap = {
    text: '/v1/generation/text-to-video',
    image: '/v1/generation/image-to-video',
    multi_image: '/v1/generation/multi-image-to-video',
  };
  const body = buildRequestBody(params);
  let res;
  try {
    res = await apiRequest('POST', pathMap[mode], body, apiKey);
  } catch (err) {
    return {
      ok: false,
      phase: 'failed',
      errorCode: 'NETWORK_ERROR',
      errorMessage: err.message || String(err),
    };
  }

  if (!isApiSuccess(res)) return formatApiError(res);

  const data = res.data || {};
  const taskIds = data.task_ids ?? (data.task_id ? [data.task_id] : []);
  return {
    ok: true,
    phase: 'submitted',
    batchId: data.batch_id ?? null,
    taskIds,
    taskId: taskIds[0] ?? null,
    taskStatus: null,
    videos: null,
    errorCode: null,
    errorMessage: null,
  };
}

function extractVideos(taskData) {
  const tr = taskData.task_result || {};
  const raw = tr.videos || taskData.videos || [];
  return raw.map((v) => {
    if (typeof v === 'string') {
      return { url: v, cover_url: '' };
    }
    return {
      url: v?.url || v?.video_url || '',
      cover_url: v?.cover_image_url || v?.cover_url || '',
    };
  });
}

async function pollUntilDone(taskId, batchId, taskIds, apiKey) {
  const start = Date.now();
  while (true) {
    const elapsed = (Date.now() - start) / 1000;
    if (elapsed * 1000 >= POLL_TIMEOUT_MS) {
      return {
        ok: false,
        phase: 'failed',
        errorCode: 'TIMEOUT',
        errorMessage: `Poll timeout after ${Math.floor(elapsed)}s.`,
        batchId,
        taskIds,
        taskId,
        taskStatus: 'unknown',
        videos: null,
      };
    }

    await sleep(POLL_INTERVAL_MS);

    let res;
    try {
      res = await apiRequest('GET', `/v1/generation/${taskId}/status`, null, apiKey);
    } catch (err) {
      log(`Warning: poll failed (${err.message}), retrying...`);
      continue;
    }

    if (!isApiSuccess(res)) {
      log('Warning: poll returned non-success status, retrying...');
      continue;
    }

    const taskData = res.data || {};
    const rawStatus = taskData.task_status || '';
    const normalized = STATUS_MAP[rawStatus] || 'unknown';
    const elapsedSec = Math.floor((Date.now() - start) / 1000);
    log(`Polling ${taskId}... status: ${rawStatus} (${elapsedSec}s elapsed)`);

    if (normalized === 'completed') {
      const videos = extractVideos(taskData);
      return {
        ok: true,
        phase: 'completed',
        batchId,
        taskIds,
        taskId,
        taskStatus: rawStatus,
        videos: videos.length ? videos : null,
        errorCode: null,
        errorMessage: null,
      };
    }

    if (normalized === 'failed') {
      const tr = taskData.task_result || {};
      const errMsg = tr.message || taskData.msg || 'Task failed';
      return {
        ok: false,
        phase: 'failed',
        batchId,
        taskIds,
        taskId,
        taskStatus: rawStatus,
        videos: null,
        errorCode: 'TASK_FAILED',
        errorMessage: errMsg,
      };
    }
  }
}

async function cmdWait(params, apiKey) {
  const submitResult = await submitTask(params, apiKey);
  if (!submitResult.ok) return submitResult;
  const taskId = submitResult.taskId;
  const batchId = submitResult.batchId;
  const taskIds = submitResult.taskIds || [taskId];
  log(`Submitted task ${taskId}. Polling for completion...`);
  return pollUntilDone(taskId, batchId, taskIds, apiKey);
}

async function cmdStatus(taskId, apiKey) {
  let res;
  try {
    res = await apiRequest('GET', `/v1/generation/${taskId}/status`, null, apiKey);
  } catch (err) {
    return {
      ok: false,
      phase: 'failed',
      errorCode: 'NETWORK_ERROR',
      errorMessage: err.message || String(err),
    };
  }

  if (!isApiSuccess(res)) return formatApiError(res);

  const taskData = res.data || {};
  const rawStatus = taskData.task_status || '';
  const normalized = STATUS_MAP[rawStatus] || 'unknown';
  const videos = extractVideos(taskData);
  const phase =
    normalized === 'completed' ? 'completed' : normalized === 'failed' ? 'failed' : 'running';
  const tr = taskData.task_result || {};
  return {
    ok: phase !== 'failed',
    phase,
    batchId: null,
    taskIds: [taskId],
    taskId,
    taskStatus: rawStatus,
    videos: videos.length ? videos : null,
    errorCode: phase === 'failed' ? 'TASK_FAILED' : null,
    errorMessage: phase === 'failed' ? tr.message || taskData.msg || null : null,
  };
}

const VALID_MODEL_MODES = ['text_to_video', 'image_to_video', 'multi_image_to_video'];

async function cmdModels(modeFilter, apiKey) {
  let res;
  try {
    res = await fetchModelsRegistry(apiKey);
  } catch (err) {
    return {
      ok: false,
      phase: 'failed',
      errorCode: 'NETWORK_ERROR',
      errorMessage: err.message || String(err),
    };
  }

  if (!isApiSuccess(res)) return formatApiError(res);

  const data = res.data || {};
  const out = { ok: true, phase: 'completed' };

  if (modeFilter) {
    if (!VALID_MODEL_MODES.includes(modeFilter)) {
      return {
        ok: false,
        phase: 'failed',
        errorCode: 'VALIDATION',
        errorMessage: `Invalid --mode. Use: ${VALID_MODEL_MODES.join(', ')}`,
      };
    }
    out[modeFilter] = data[modeFilter] || [];
  } else {
    out.text_to_video = data.text_to_video || [];
    out.image_to_video = data.image_to_video || [];
    out.multi_image_to_video = data.multi_image_to_video || [];
  }

  return out;
}

function parseArgs(argv) {
  const cmd = argv[0];
  let jsonStr = null;
  let taskId = null;
  let dryRun = false;
  let modelsMode = null;
  for (let i = 1; i < argv.length; i++) {
    if (argv[i] === '--json') jsonStr = argv[++i];
    else if (argv[i] === '--task-id') taskId = argv[++i];
    else if (argv[i] === '--dry-run') dryRun = true;
    else if (argv[i] === '--mode') modelsMode = argv[++i];
  }
  return { command: cmd, jsonStr, taskId, dryRun, modelsMode };
}

function printJson(obj) {
  process.stdout.write(`${JSON.stringify(obj, null, 2)}\n`);
}

async function main() {
  const argv = process.argv.slice(2);
  const valid = new Set([
    'wait',
    'submit-text',
    'submit-image',
    'submit-multi-image',
    'status',
    'models',
  ]);
  const { command, jsonStr, taskId: cliTaskId, dryRun, modelsMode } = parseArgs(argv);

  if (!command || !valid.has(command)) {
    printJson({
      ok: false,
      phase: 'failed',
      errorCode: 'USAGE',
      errorMessage:
        'Usage: node video_gen.js <wait|submit-text|submit-image|submit-multi-image|status|models> [--json \'...\'] [--task-id id] [--dry-run] [--mode text_to_video|image_to_video|multi_image_to_video]',
    });
    process.exit(1);
  }

  let params = {};
  if (jsonStr) {
    try {
      params = JSON.parse(jsonStr);
    } catch (e) {
      printJson({
        ok: false,
        phase: 'failed',
        errorCode: 'INVALID_JSON',
        errorMessage: `Invalid JSON: ${e.message}`,
      });
      process.exit(1);
    }
  }

  if (command === 'models') {
    const [REDACTED_SECRET] || '').trim();
    if (!apiKey) {
      printJson({
        ok: false,
        phase: 'failed',
        errorCode: 'NO_API_KEY',
        errorMessage: 'Missing WERYAI_API_KEY environment variable.',
      });
      process.exit(1);
    }
    const result = await cmdModels(modelsMode, apiKey);
    printJson(result);
    process.exit(result.ok ? 0 : 1);
  }

  if (dryRun) {
    const mode = detectMode(params);
    const pathMap = {
      text: '/v1/generation/text-to-video',
      image: '/v1/generation/image-to-video',
      multi_image: '/v1/generation/multi-image-to-video',
    };
    if ('prompt' in params && !hasNonEmptyModel(params)) {
      printJson({
        ok: false,
        phase: 'failed',
        errorCode: 'MISSING_PARAM',
        errorMessage: "'model' is required in JSON parameters (no default model).",
      });
      process.exit(1);
    }
    const body = 'prompt' in params ? buildRequestBody(params) : {};
    printJson({
      ok: true,
      phase: 'dry-run',
      dryRun: true,
      requestBody: body,
      requestUrl: BASE_URL + (pathMap[mode] || pathMap.text),
    });
    process.exit(0);
  }

  const [REDACTED_SECRET] || '').trim();
  if (!apiKey) {
    printJson({
      ok: false,
      phase: 'failed',
      errorCode: 'NO_API_KEY',
      errorMessage: 'Missing WERYAI_API_KEY environment variable.',
    });
    process.exit(1);
  }

  let result;
  if (command === 'status') {
    const tid = cliTaskId || params.task_id || params.taskId;
    if (!tid) {
      printJson({
        ok: false,
        phase: 'failed',
        errorCode: 'MISSING_PARAM',
        errorMessage: 'status command requires --task-id <id>',
      });
      process.exit(1);
    }
    result = await cmdStatus(tid, apiKey);
  } else {
    if (!params.prompt) {
      printJson({
        ok: false,
        phase: 'failed',
        errorCode: 'MISSING_PARAM',
        errorMessage: "'prompt' is required in JSON parameters.",
      });
      process.exit(1);
    }
    if (!hasNonEmptyModel(params)) {
      printJson({
        ok: false,
        phase: 'failed',
        errorCode: 'MISSING_PARAM',
        errorMessage: "'model' is required in JSON parameters (no default model).",
      });
      process.exit(1);
    }
    result = command === 'wait' ? await cmdWait(params, apiKey) : await submitTask(params, apiKey);
  }

  printJson(result);
  process.exit(result.ok ? 0 : 1);
}

main().catch((err) => {
  printJson({
    ok: false,
    phase: 'failed',
    errorCode: 'FATAL',
    errorMessage: err.message || String(err),
  });
  process.exit(1);
});


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (MEDIUM)