⏳ This skill is pending AI review.

Scores will appear once the review pipeline completes.

version unknown

runninghub

apizziii@apizziii⭐ 1 stars· last commit 1mo ago· 0 open issues

Generate images, videos, audio, and 3D models via RunningHub API (209 endpoints) and run any RunningHub AI Application (custom ComfyUI workflow) by webappId. Covers text-to-image, image-to-video, text-to-speech, music generation, 3D modeling, image upscaling, AI apps, and more.

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

—/10

// RATINGS

⭐GitHub Stars
⭐ 1 on GitHubGitHub ↗

New / niche

🟢ProSkills Score
—
📍

Not yet listed on ClawHub or SkillsMP

// README

RHClaw — RunningHub Skill for OpenClaw

English

为 OpenClaw 打造的通用多媒体生成技能,由 RunningHub API 驱动。

209 个标准 API 端点 + 无限 AI 应用,覆盖图片、视频、音频、3D 模型生成、多模态文本理解,以及任意用户创建的 AI 应用(ComfyUI 工作流)。

能力一览

类别端点数支持任务
图片47文生图、图生图、图片放大、Midjourney 风格
视频126文生视频、图生视频、首尾帧生成、视频续写/编辑、运动控制、多模态视频
音频8文字转语音、音乐生成、声音克隆
3D12文字转 3D、图片转 3D、多图转 3D
文本16图片理解、视频理解、文本处理
AI 应用无限运行任意 RunningHub AI 应用(自定义 ComfyUI 工作流)

快速开始

安装

在 OpenClaw 对话中发送:

从 https://github.com/HM-RunningHub/OpenClaw_RH_Skills 安装 RunningHub 技能

助手会自动克隆仓库、复制文件到工作区,并引导你完成 API Key 配置。

更新

当技能有新版本时,在 OpenClaw 对话中发送:

从 https://github.com/HM-RunningHub/OpenClaw_RH_Skills 更新 并重新读取@runninghub/SKILL.md

助手会拉取最新代码并重新加载技能配置,无需重新输入 API Key。

前置条件

使用方式

安装完成后,直接用自然语言跟助手对话即可:

  • "帮我画一只在公园里玩耍的小狗"
  • "把这张照片做成视频"
  • "给我的视频配个背景音乐"
  • "把这张图放大到 4K"
  • "把这张图转成 3D 模型"
  • "帮我跑这个 AI 应用 https://www.runninghub.cn/ai-detail/1877265245566922800"
  • "最热门的 AI 应用有哪些?"
  • "推荐一些最新的 AI 应用"

助手会自动选择最合适的 RunningHub 端点来完成你的请求;如果是 AI 应用,则获取应用节点信息、引导你设置参数并运行;还可以浏览推荐、最热、最新的 AI 应用。

视频生成交互

生成视频时,助手会展示 8 个精选模型让你选择:

  1. 🚀 Google Veo 3.1 Fast — 又快效果又好,性价比之王
  2. 🔥 Grok Video — Grok 驱动,画面想象力超强
  3. 🎯 Kling v3.0 Pro — 运动自然,拍人物首选
  4. 🎬 Google Veo 3.1 Pro — 电影感拉满
  5. ✨ Vidu Q3 Pro — 风格化独特
  6. ⭐ Sora — Sora 同款引擎
  7. 🌊 MiniMax Hailuo — 速度快画面细腻
  8. 🌱 超能视频SD2.0 — 效果超赞,最长15秒+自动配音,不适合真人

选个数字就能开始生成,不选默认用 Google Veo 3.1 Fast。

图片生成交互

生成图片时,助手会展示 5 个精选模型让你选择:

  1. 🎨 全能图片PRO — 香蕉Pro同款,默认推荐,综合效果最好
  2. ⚡ 全能图片V2 — 香蕉2同款,最快最便宜
  3. 🎭 悠船 v7 — Midjourney 风格,欧美大片质感
  4. 🌸 悠船 niji7 — 二次元/动漫风格,插画感满满
  5. 📷 Seedream v5 — 字节跳动出品,写实照片感超强

选个数字就能开始生成,不选默认用全能图片PRO。

项目结构

runninghub/
├── SKILL.md                        # OpenClaw 技能定义(路由表 + 示例 + 交互规则)
├── scripts/
│   ├── runninghub.py               # 标准模型 API 客户端(209 端点)
│   ├── runninghub_app.py           # AI 应用客户端(自定义 ComfyUI 工作流)
│   └── build_capabilities.py       # 从 models_registry.json 生成 capabilities.json
└── data/
    └── capabilities.json           # 完整端点目录(自动生成)

脚本模式

标准模型 API(runninghub.py)

模式命令用途
检查--check验证 API Key + 查询余额
列表--list [--type T] [--task T]浏览可用端点
详情--info ENDPOINT查看端点参数
执行--endpoint EP --prompt "..." -o /tmp/out使用指定端点执行
自动--task TASK --prompt "..." -o /tmp/out自动选择最佳端点

AI 应用(runninghub_app.py)

模式命令用途
检查--check验证 API Key + 查询余额
浏览--list [--sort S] [--size N] [--page N]浏览推荐/最热/最新 AI 应用
节点--info WEBAPP_ID查看 AI 应用的可修改节点
执行--run WEBAPP_ID --node ... --file ... -o /tmp/out运行 AI 应用

更新能力目录

当 RunningHub 上线新的 API 端点时,重新生成目录:

python3 scripts/build_capabilities.py \
  --registry /path/to/ComfyUI_RH_OpenAPI/models_registry.json \
  --output data/capabilities.json

许可证

Apache-2.0

// HOW IT'S BUILT

// FILES

12 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • runninghub/SKILL.md6.3 KBd72fd16625d3upstream ↗
    ---
    name: runninghub
    description: "Generate images, videos, audio, and 3D models via RunningHub API (209 endpoints) and run any RunningHub AI Application (custom ComfyUI workflow) by webappId. Covers text-to-image, image-to-video, text-to-speech, music generation, 3D modeling, image upscaling, AI apps, and more."
    homepage: https://www.runninghub.cn
    metadata:
      {
        "openclaw":
          {
            "emoji": "🎬",
            "requires": { "bins": ["python3", "curl"] },
            "primaryEnv": "RUNNINGHUB_API_KEY"
          }
      }
    ---
    
    # RunningHub Skill
    
    Standard API Script: `python3 {baseDir}/scripts/runninghub.py`
    AI App Script: `python3 {baseDir}/scripts/runninghub_app.py`
    Data: `{baseDir}/data/capabilities.json`
    
    ## Persona
    
    You are **RunningHub 小助手** — a multimedia expert who's professional yet warm, like a creative-industry friend. ALL responses MUST follow:
    
    - Speak Chinese. Warm & lively: "搞定啦~"、"来啦!"、"超棒的". Never robotic.
    - Show cost naturally: "花了 ¥0.50" (not "Cost: ¥0.50").
    - Never show endpoint IDs to users — use Chinese model names (e.g. "万相2.6", "可灵").
    - After delivering results, suggest next steps ("要不要做成视频?"、"需要配个音吗?").
    
    ## CRITICAL RULES
    
    1. **ALWAYS use the script** — never curl RunningHub API directly.
    2. **ALWAYS use `-o /tmp/openclaw/rh-output/<name>.<ext>`** with timestamps in filenames.
    3. **Deliver files via `message` tool** — you MUST call `message` tool to send media. Do NOT print file paths as text.
    4. **NEVER show RunningHub URLs** — all `runninghub.cn` URLs are internal. Users cannot open them.
    5. **NEVER use `![](url)` markdown images or print raw file paths** — ONLY the `message` tool can deliver files to users.
    6. **ALWAYS report cost** — if script prints `COST:¥X.XX`, include it in your response as "花了 ¥X.XX".
    7. **ALL video generation** → Read `{baseDir}/references/video-models.md` and follow its complete flow. **ALL image generation** → Read `{baseDir}/references/image-models.md` and follow its complete flow. WAIT for user choice before running any generation script.
    8. **ALWAYS notify before long tasks** — Before running any video, AI app, 3D, or music generation script, you MUST first use the `message` tool to send a progress notification to the user (e.g. "开始生成啦,视频一般需要几分钟,请稍等~ 🎬"). Send this BEFORE calling `exec`. This is critical because these tasks take 1-10+ minutes and the user needs to know the task has started.
    
    ## API Key Setup
    
    When user needs to set up or check their API key →
    Read `{baseDir}/references/api-key-setup.md` and follow its instructions.
    
    Quick check: `python3 {baseDir}/scripts/runninghub.py --check`
    
    ## Routing Table
    
    | Intent | Endpoint | Notes |
    |--------|----------|-------|
    | **Text to video** | **⚠️ Read `{baseDir}/references/video-models.md`** | MUST present model menu first |
    | **Image to video** | **⚠️ Read `{baseDir}/references/video-models.md`** | MUST present model menu first |
    | **Text to image** | **⚠️ Read `{baseDir}/references/image-models.md`** | MUST present model menu first |
    | **Image edit** | **⚠️ Read `{baseDir}/references/image-models.md`** | MUST present model menu first |
    | Image upscale | `topazlabs/image-upscale-standard-v2` | Alt: high-fidelity-v2 |
    | AI image editing | `alibaba/qwen-image-2.0-pro/image-edit` | Qwen-based |
    | Realistic person i2v | `rhart-video-s-official/image-to-video-realistic` | Best for real people |
    | Start+end frame | `rhart-video-v3.1-pro/start-end-to-video` | Two keyframes → video |
    | Video extend | `rhart-video-v3.1-pro-official/video-extend` | |
    | Video editing | `rhart-video-g-official/edit-video` | |
    | Video upscale | `topazlabs/video-upscale` | |
    | Motion control | `kling-v3.0-pro/motion-control` | |
    | Reference video | `kling-video-o3-pro/reference-to-video` | Style/character reference → video. Alt: vidu, wan-2.6, seedance |
    | Multimodal video | `rhart-video/sparkvideo-2.0/multimodal-video` | Mix image+video+audio inputs → new video (超能视频SD2.0). No real people. |
    | TTS (best) | `rhart-audio/text-to-audio/speech-2.8-hd` | HD quality |
    | TTS (fast) | `rhart-audio/text-to-audio/speech-2.8-turbo` | |
    | Music | `rhart-audio/text-to-audio/music-2.5` | |
    | Voice clone | `rhart-audio/text-to-audio/voice-clone` | |
    | Text to 3D | `hunyuan3d-v3.1/text-to-3d` | |
    | Image to 3D | `hunyuan3d-v3.1/image-to-3d` | |
    | Image understand | `rhart-text-g-3-flash-preview/image-to-text` | Preferred. Alt: g-3-pro-preview, g-25-pro, g-25-flash |
    | Video understand | `rhart-text-g-25-pro/video-to-text` | |
    | **AI Application** | **⚠️ Read `{baseDir}/references/ai-application.md`** | User provides webappId or link |
    | **Browse AI Apps** | **⚠️ Read `{baseDir}/references/ai-application.md`** | "有什么应用" / "最热门" / "最新" / "推荐" |
    
    ## AI Application
    
    When user mentions "AI应用", "workflow", "webappId", pastes a RunningHub AI app link,
    or asks to browse/discover apps ("有什么应用", "最热门的", "最新的", "推荐什么") →
    Read `{baseDir}/references/ai-application.md` and follow its complete flow.
    
    ## Script Usage
    
    **Execution flow for ALL generation tasks:**
    1. **Slow tasks (video / 3D / music / AI app):** First send `message` notification → "开始生成啦,一般需要 X 分钟,请稍等~" → then `exec` the script
    2. **Fast tasks (image / TTS / upscale):** Directly `exec` the script (notification optional)
    
    ```bash
    python3 {baseDir}/scripts/runninghub.py \
      --endpoint ENDPOINT \
      --prompt "prompt text" \
      --param key=value \
      -o /tmp/openclaw/rh-output/name_$(date +%s).ext
    ```
    
    Optional flags: `--image PATH`, `--video PATH`, `--audio PATH`, `--param key=value` (repeatable)
    Discovery: `--list [--type T]`, `--info ENDPOINT`
    
    Example — text to image:
    ```bash
    python3 {baseDir}/scripts/runninghub.py \
      --endpoint rhart-image-n-pro/text-to-image \
      --prompt "a cute puppy, 4K cinematic" \
      --param resolution=2k --param aspectRatio=16:9 \
      -o /tmp/openclaw/rh-output/puppy_$(date +%s).png
    ```
    
    ## Output
    
    For media delivery and error handling details → Read `{baseDir}/references/output-delivery.md`.
    
    Key rules (always apply):
    - ALWAYS call `message` tool to deliver media files, then respond `NO_REPLY`.
    - If `message` fails, retry once. If still fails, include `OUTPUT_FILE:<path>` and explain.
    - Print text results directly. Include cost if `COST:` line present.
    
  • runninghub/scripts/build_capabilities.py12 KBc787457dad50upstream ↗
    #!/usr/bin/env python3
    """
    Build capabilities.json from ComfyUI_RH_OpenAPI models_registry.json.
    
    Usage:
        python build_capabilities.py --registry /path/to/models_registry.json --output ../data/capabilities.json
    """
    
    import argparse
    import json
    import re
    import sys
    from datetime import date
    from pathlib import Path
    
    # Popularity overrides: endpoint → rank (1 = most popular).
    # Within each task group, endpoints not listed here get rank 99.
    POPULARITY_OVERRIDES = {
        # Image - text-to-image
        "rhart-image-n-pro/text-to-image": 1,
        "rhart-image-g-1.5/text-to-image": 2,
        "rhart-image-g-3/text-to-image": 3,
        "rhart-image-g-4/text-to-image": 4,
        "rhart-image-n-g31-flash/text-to-image": 5,
        "rhart-image-n-pro-official/text-to-image": 6,
        "rhart-image-n-pro-official/text-to-image-ultra": 7,
        "seedream-v5-lite/text-to-image": 8,
        "seedream-v4.5/text-to-image": 9,
        "seedream-v4/text-to-image": 10,
        "rhart-image-v1/text-to-image": 11,
        "rhart-image-v1-official/text-to-image": 12,
        "rhart-image-g/text-to-image": 13,
        "youchuan/text-to-image-v7": 14,
        "youchuan/text-to-image-niji7": 15,
        "youchuan/text-to-image-v6": 16,
        "youchuan/text-to-image-v61": 17,
        "youchuan/text-to-image-niji6": 18,
        "rhart-image-n-g31-flash-official/text-to-image": 19,
        "rhart-image-g-1.5-official/text-to-image": 20,
    
        # Image - image-to-image / edit
        "rhart-image-n-pro/edit": 1,
        "rhart-image-g-1.5/edit": 2,
        "rhart-image-g-3/image-to-image": 3,
        "rhart-image-g-4/image-to-image": 4,
        "rhart-image-n-g31-flash/image-to-image": 5,
        "rhart-image-n-pro-official/edit": 6,
        "rhart-image-n-pro-official/edit-ultra": 7,
        "seedream-v5-lite/image-to-image": 8,
        "seedream-v4.5/image-to-image": 9,
        "seedream-v4/image-to-image": 10,
        "rhart-image-v1/edit": 11,
        "alibaba/qwen-image-2.0-pro/image-edit": 12,
        "alibaba/qwen-image-2.0/image-edit": 13,
    
        # Image - upscale
        "topazlabs/image-upscale-standard-v2": 1,
        "topazlabs/image-upscale-high-fidelity-v2": 2,
        "topazlabs/image-upscale/low-resolution-v2": 3,
        "topazlabs/image-upscale-cgi": 4,
        "topazlabs/image-upscale-text-refine": 5,
    
        # Video - text-to-video
        "rhart-video-s/text-to-video": 1,
        "rhart-video-s/text-to-video-pro": 2,
        "rhart-video-s-official/text-to-video": 3,
        "rhart-video-s-official/text-to-video-pro": 4,
        "kling-v3.0-pro/text-to-video": 5,
        "kling-v3.0-std/text-to-video": 6,
        "kling-video-o3-pro/text-to-video": 7,
        "kling-video-o3-std/text-to-video": 8,
        "kling-video-o1/text-to-video": 9,
        "kling-v2.6-pro/text-to-video": 10,
        "kling-v2.5-turbo-pro/text-to-video": 11,
        "rhart-video-v3.1-pro/text-to-video": 12,
        "rhart-video-v3.1-fast/text-to-video": 13,
        "rhart-video-v3.1-pro-official/text-to-video": 14,
        "rhart-video-v3.1-fast-official/text-to-video": 15,
        "rhart-video-g/text-to-video": 16,
        "rhart-video-g-official/text-to-video": 17,
        "minimax/hailuo-02/t2v-pro": 18,
        "minimax/hailuo-2.3/t2v-pro": 19,
        "minimax/hailuo-02/t2v-standard": 20,
        "minimax/hailuo-2.3/t2v-standard": 21,
        "vidu/text-to-video-q3-pro": 22,
        "vidu/text-to-video-q3-turbo": 23,
        "vidu/text-to-video": 24,
        "alibaba/wan-2.6/text-to-video": 25,
        "seedance-v1.5-pro/text-to-video": 26,
        "seedance-v1.5-pro/text-to-video-fast": 27,
    
        # Video - image-to-video
        "rhart-video-s/image-to-video": 1,
        "rhart-video-s/image-to-video-pro": 2,
        "rhart-video-s-official/image-to-video": 3,
        "rhart-video-s-official/image-to-video-pro": 4,
        "rhart-video-s-official/image-to-video-realistic": 5,
        "kling-v3.0-pro/image-to-video": 6,
        "kling-v3.0-std/image-to-video": 7,
        "kling-video-o3-pro/image-to-video": 8,
        "kling-video-o3-std/image-to-video": 9,
        "kling-video-o1/image-to-video": 10,
        "kling-v2.6-pro/image-to-video": 11,
        "kling-v2.5-turbo-pro/image-to-video": 12,
        "kling-v2.5-turbo-std/image-to-video": 13,
        "rhart-video-v3.1-pro/image-to-video": 14,
        "rhart-video-v3.1-fast/image-to-video": 15,
        "rhart-video-v3.1-pro-official/image-to-video": 16,
        "rhart-video-v3.1-fast-official/image-to-video": 17,
        "rhart-video-g/image-to-video": 18,
        "rhart-video-g-official/image-to-video": 19,
        "minimax/hailuo-02/i2v-pro": 20,
        "minimax/hailuo-02/i2v-standard": 21,
        "minimax/hailuo-2.3/i2v-standard": 22,
        "minimax/hailuo-2.3/image-to-video-pro": 23,
        "minimax/hailuo-2.3-fast/image-to-video": 24,
        "minimax/hailuo-2.3-fast-pro/image-to-video": 25,
        "vidu/image-to-video-q3-pro": 26,
        "vidu/image-to-video-q3-turbo": 27,
        "vidu/image-to-video-q2-pro": 28,
        "vidu/image-to-video-q2-pro-fast": 29,
        "vidu/image-to-video-q2-turbo": 30,
        "alibaba/wan-2.6/image-to-video": 31,
        "alibaba/wan-2.6/image-to-video-flash": 32,
        "seedance-v1.5-pro/image-to-video": 33,
        "seedance-v1.5-pro/image-to-video-fast": 34,
        "youchuan/image-to-video": 35,
    
        # Audio
        "rhart-audio/text-to-audio/speech-2.8-hd": 1,
        "rhart-audio/text-to-audio/speech-02-hd": 2,
        "rhart-audio/text-to-audio/speech-2.8-turbo": 3,
        "rhart-audio/text-to-audio/speech-02-turbo": 4,
        "rhart-audio/text-to-audio/speech-2.6-hd": 5,
        "rhart-audio/text-to-audio/speech-2.6-turbo": 6,
        "rhart-audio/text-to-audio/music-2.5": 7,
        "rhart-audio/text-to-audio/voice-clone": 8,
    
        # 3D
        "hunyuan3d-v3.1/image-to-3d": 1,
        "hunyuan3d-v3.1/text-to-3d": 2,
    }
    
    
    def extract_task(endpoint: str, output_type: str) -> str:
        """Derive a normalized task name from the endpoint path."""
        parts = endpoint.split("/")
        suffix = parts[-1] if len(parts) > 1 else endpoint
    
        # Normalize common patterns
        if "upscale" in suffix or "upscale" in endpoint:
            if output_type == "video":
                return "video-upscale"
            return "image-upscale"
        if suffix in ("edit", "edit-ultra"):
            return "image-to-image"
        if "image-edit" in suffix:
            return "image-to-image"
        if "image-to-image" in suffix:
            return "image-to-image"
        if "text-to-image" in suffix:
            return "text-to-image"
        if "text-to-video" in suffix or "t2v" in suffix:
            return "text-to-video"
        if "image-to-video" in suffix or "i2v" in suffix:
            return "image-to-video"
        if "start-end" in suffix or "start-to-end" in suffix:
            return "start-end-to-video"
        if "reference-to-video" in suffix or "refrence-to-video" in suffix:
            return "reference-to-video"
        if "video-extend" in suffix:
            return "video-extend"
        if "edit-video" in suffix or "video-edit" in suffix:
            return "video-edit"
        if "motion-control" in suffix:
            return "motion-control"
        if "text-to-3d" in suffix:
            return "text-to-3d"
        if "multi-image-to-3d" in suffix:
            return "multi-image-to-3d"
        if "image-to-3d" in suffix:
            return "image-to-3d"
        if "text-to-text" in suffix:
            return "text-to-text"
        if "image-to-text" in suffix:
            return "image-to-text"
        if "video-to-text" in suffix:
            return "video-to-text"
        if "speech" in suffix or "speech" in endpoint:
            return "text-to-speech"
        if "music" in suffix:
            return "music-generation"
        if "voice-clone" in suffix:
            return "voice-clone"
        if "upload-character" in suffix:
            return "upload-character"
    
        # Fallback: if output_type gives a clue
        if output_type == "video":
            return "video-other"
        if output_type == "image":
            return "image-other"
        if output_type == "audio":
            return "audio-other"
        return "other"
    
    
    def extract_tags(endpoint: str, name_cn: str, output_type: str, task: str) -> list:
        """Generate descriptive tags for routing."""
        tags = []
    
        if "official" in endpoint:
            tags.append("official")
        if "pro" in endpoint.split("/")[-1] or "-pro" in endpoint:
            tags.append("pro")
        if "fast" in endpoint or "turbo" in endpoint or "flash" in endpoint:
            tags.append("fast")
        if "ultra" in endpoint:
            tags.append("ultra-quality")
        if "realistic" in endpoint or "真人" in name_cn:
            tags.append("realistic")
        if "niji" in endpoint:
            tags.append("anime")
        if "youchuan" in endpoint:
            tags.append("midjourney-style")
        if "topazlabs" in endpoint:
            tags.append("enhance")
        if "std" in endpoint.split("/")[-1] or "-std" in endpoint:
            tags.append("standard")
        if "hd" in endpoint.split("/")[-1]:
            tags.append("hd")
    
        return tags
    
    
    def simplify_param(param: dict) -> dict:
        """Extract essential param info for capabilities.json."""
        p = {
            "key": param["fieldKey"],
            "type": param["type"],
            "required": param.get("required", False),
        }
        if param.get("options"):
            p["options"] = [opt["value"] for opt in param["options"]]
        default_val = param.get("defaultValue")
        if default_val is not None and default_val != "":
            if isinstance(default_val, str) and ("Rh-Comfy-Auth=" in default_val or "Rh-Identify=" in default_val):
                pass
            else:
                p["default"] = default_val
        if param.get("multipleInputs"):
            p["multiple"] = True
            if param.get("maxInputNum"):
                p["maxCount"] = param["maxInputNum"]
        if param.get("maxLength"):
            p["maxLength"] = param["maxLength"]
        if param.get("maxSize"):
            p["maxSizeMB"] = param["maxSize"]
        if param.get("min") is not None:
            p["min"] = param["min"]
        if param.get("max") is not None:
            p["max"] = param["max"]
        return p
    
    
    def build_capabilities(registry: list) -> dict:
        """Transform models_registry.json entries into capabilities.json."""
        endpoints = []
    
        for entry in registry:
            ep = entry["endpoint"]
            output_type = entry["output_type"]
            task = extract_task(ep, output_type)
    
            cap = {
                "endpoint": ep,
                "name_cn": entry.get("name_cn", ""),
                "name_en": entry.get("name_en", ""),
                "task": task,
                "output_type": output_type,
                "category": entry.get("category", ""),
                "popularity": POPULARITY_OVERRIDES.get(ep, 99),
                "tags": extract_tags(ep, entry.get("name_cn", ""), output_type, task),
                "params": [simplify_param(p) for p in entry.get("params", [])],
            }
            endpoints.append(cap)
    
        # Sort: by task, then by popularity within each task
        endpoints.sort(key=lambda x: (x["task"], x["popularity"]))
    
        return {
            "version": date.today().isoformat(),
            "total": len(endpoints),
            "endpoints": endpoints,
        }
    
    
    def main():
        parser = argparse.ArgumentParser(description="Build capabilities.json from models_registry.json")
        parser.add_argument("--registry", "-r", required=True, help="Path to models_registry.json")
        parser.add_argument("--output", "-o", required=True, help="Output path for capabilities.json")
        args = parser.parse_args()
    
        registry_path = Path(args.registry)
        if not registry_path.exists():
            print(f"Error: registry not found: {registry_path}", file=sys.stderr)
            sys.exit(1)
    
        with open(registry_path, encoding="utf-8") as f:
            registry = json.load(f)
    
        print(f"Read {len(registry)} entries from {registry_path}")
    
        capabilities = build_capabilities(registry)
    
        output_path = Path(args.output)
        output_path.parent.mkdir(parents=True, exist_ok=True)
        with open(output_path, "w", encoding="utf-8") as f:
            json.dump(capabilities, f, indent=2, ensure_ascii=False)
    
        # Summary
        from collections import Counter
        task_counts = Counter(e["task"] for e in capabilities["endpoints"])
        type_counts = Counter(e["output_type"] for e in capabilities["endpoints"])
    
        print(f"\nGenerated {output_path} with {capabilities['total']} endpoints")
        print(f"\nBy output_type:")
        for t, c in type_counts.most_common():
            print(f"  {t}: {c}")
        print(f"\nBy task:")
        for t, c in task_counts.most_common():
            print(f"  {t}: {c}")
    
        ranked = sum(1 for e in capabilities["endpoints"] if e["popularity"] < 99)
        print(f"\n{ranked} endpoints have explicit popularity rankings")
    
    
    if __name__ == "__main__":
        main()
    
  • runninghub/scripts/runninghub.py27 KB8e0469850dcaupstream ↗
    #!/usr/bin/env python3
    """
    RunningHub universal API client for OpenClaw.
    
    Supports all 209 RunningHub endpoints: image, video, audio, 3D, text understanding.
    Uses only Python stdlib and curl.
    
    Modes:
      --check                          Account health check (key + balance)
      --list [--type T] [--task T]     List available endpoints
      --info ENDPOINT                  Show endpoint details
      --endpoint EP --prompt "..." ... Execute a generation task
      --task TASK --prompt "..."       Auto-select best endpoint for task
    """
    
    from __future__ import annotations
    
    import argparse
    import base64
    import json
    import mimetypes
    import os
    import subprocess
    import sys
    import tempfile
    import time
    from pathlib import Path
    
    BASE_URL = "https://www.runninghub.cn/openapi/v2"
    ACCOUNT_STATUS_URL = "https://www.runninghub.cn/uc/openapi/accountStatus"
    POLL_ENDPOINT = "/query"
    UPLOAD_ENDPOINT = "/media/upload/binary"
    
    MAX_POLL_SECONDS = 1200
    POLL_INTERVAL = 5
    
    SCRIPT_DIR = Path(__file__).resolve().parent
    DATA_DIR = SCRIPT_DIR.parent / "data"
    CAPABILITIES_PATH = DATA_DIR / "capabilities.json"
    
    
    # ---------------------------------------------------------------------------
    # Capabilities catalog
    # ---------------------------------------------------------------------------
    
    _capabilities_cache = None
    
    
    def load_capabilities() -> dict:
        global _capabilities_cache
        if _capabilities_cache is not None:
            return _capabilities_cache
        if not CAPABILITIES_PATH.exists():
            print(f"Error: capabilities.json not found at {CAPABILITIES_PATH}", file=sys.stderr)
            sys.exit(1)
        with open(CAPABILITIES_PATH, encoding="utf-8") as f:
            _capabilities_cache = json.load(f)
        return _capabilities_cache
    
    
    def find_endpoint(endpoint: str) -> dict | None:
        caps = load_capabilities()
        for ep in caps["endpoints"]:
            if ep["endpoint"] == endpoint:
                return ep
        return None
    
    
    def find_best_for_task(task: str) -> dict | None:
        caps = load_capabilities()
        matches = [e for e in caps["endpoints"] if e["task"] == task]
        if not matches:
            return None
        return min(matches, key=lambda x: x["popularity"])
    
    
    # ---------------------------------------------------------------------------
    # API key resolution
    # ---------------------------------------------------------------------------
    
    def read_key_from_openclaw_config() -> str | None:
        cfg_path = Path.home() / ".openclaw" / "openclaw.json"
        if not cfg_path.exists():
            return None
        try:
            cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
        except Exception:
            return None
        entry = cfg.get("skills", {}).get("entries", {}).get("runninghub", {})
        # OpenClaw native: skills.entries.runninghub.apiKey (injected via primaryEnv)
        api_key = entry.get("apiKey")
        if isinstance(api_key, str) and api_key.strip():
            return api_key.strip()
        # Fallback: skills.entries.runninghub.env.RUNNINGHUB_API_KEY
        env_val = entry.get("env", {}).get("RUNNINGHUB_API_KEY")
        if isinstance(env_val, str) and env_val.strip():
            return env_val.strip()
        return None
    
    
    def resolve_api_key(provided_key: str | None) -> str | None:
        """Resolve API key without exiting. Returns None if not found."""
        if provided_key:
            normalized = provided_key.strip()
            placeholders = {
                "your_api_key_here", "<your_api_key>",
                "YOUR_API_KEY", "RUNNINGHUB_API_KEY",
            }
            if normalized and normalized not in placeholders:
                return normalized
    
        env_key = os.environ.get("RUNNINGHUB_API_KEY", "").strip()
        if env_key:
            return env_key
    
        return read_key_from_openclaw_config()
    
    
    def get_key_source(provided_key: str | None) -> str:
        if provided_key:
            normalized = provided_key.strip()
            placeholders = {"your_api_key_here", "<your_api_key>", "YOUR_API_KEY", "RUNNINGHUB_API_KEY"}
            if normalized and normalized not in placeholders:
                return "cli"
        env_key = os.environ.get("RUNNINGHUB_API_KEY", "").strip()
        if env_key:
            return "env"
        cfg_key = read_key_from_openclaw_config()
        if cfg_key:
            return "config"
        return "none"
    
    
    def require_api_key(provided_key: str | None) -> str:
        key = resolve_api_key(provided_key)
        if key:
            return key
        result = {
            "error": "NO_API_KEY",
            "message": "No API key configured",
            "steps": [
                "1. Register/login at https://www.runninghub.cn",
                "2. Create API Key at https://www.runninghub.cn/enterprise-api/sharedApi",
                "3. Recharge wallet at https://www.runninghub.cn/vip-rights/4",
                "4. Send the key in chat or add to ~/.openclaw/openclaw.json: skills.entries.runninghub.apiKey",
            ],
        }
        print(json.dumps(result, ensure_ascii=False))
        sys.exit(1)
    
    
    # ---------------------------------------------------------------------------
    # HTTP helpers (curl-based, stdlib only)
    # ---------------------------------------------------------------------------
    
    def curl_post_json(url: str, payload: dict, headers: dict, timeout: int = 60) -> subprocess.CompletedProcess:
        with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
            json.dump(payload, f)
            tmp_path = f.name
        try:
            cmd = ["curl", "-s", "-S", "--fail-with-body", "-X", "POST", url,
                   "--max-time", str(timeout), "-d", f"@{tmp_path}"]
            for k, v in headers.items():
                cmd += ["-H", f"{k}: {v}"]
            return subprocess.run(cmd, capture_output=True, text=True)
        finally:
            os.unlink(tmp_path)
    
    
    def api_post(api_key: str, url: str, payload: dict, timeout: int = 60) -> dict:
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}",
        }
        result = curl_post_json(url, payload, headers, timeout)
    
        if result.returncode != 0:
            error_body = result.stdout or result.stderr
            try:
                err = json.loads(error_body)
                code = err.get("code", "")
                msg = err.get("msg", error_body)
            except (json.JSONDecodeError, TypeError):
                code = ""
                msg = error_body
    
            code_str = str(code).lower()
            msg_lower = msg.lower() if isinstance(msg, str) else ""
    
            if any(k in code_str or k in msg_lower for k in ["auth", "401", "403", "token", "key"]):
                error_result = {
                    "error": "AUTH_FAILED",
                    "message": f"API authentication failed: {msg}",
                    "manage_url": "https://www.runninghub.cn/enterprise-api/sharedApi",
                }
            elif any(k in code_str or k in msg_lower for k in ["balance", "insufficient", "余额", "credit"]):
                error_result = {
                    "error": "INSUFFICIENT_BALANCE",
                    "message": f"Insufficient balance: {msg}",
                    "recharge_url": "https://www.runninghub.cn/vip-rights/4",
                }
            else:
                error_result = {
                    "error": "API_ERROR",
                    "message": f"API request failed: {msg}",
                    "http_stderr": result.stderr[:500] if result.stderr else "",
                }
            print(json.dumps(error_result, ensure_ascii=False), file=sys.stderr)
            sys.exit(1)
    
        try:
            return json.loads(result.stdout)
        except json.JSONDecodeError:
            print(json.dumps({
                "error": "API_ERROR",
                "message": f"Invalid JSON response: {result.stdout[:500]}",
            }, ensure_ascii=False), file=sys.stderr)
            sys.exit(1)
    
    
    # ---------------------------------------------------------------------------
    # --check: account health check
    # ---------------------------------------------------------------------------
    
    def cmd_check(api_key_arg: str | None):
        key = resolve_api_key(api_key_arg)
        if not key:
            print(json.dumps({
                "status": "no_key",
                "message": "No API key configured",
                "steps": [
                    "1. Register/login at https://www.runninghub.cn",
                    "2. Create API Key at https://www.runninghub.cn/enterprise-api/sharedApi",
                    "3. Recharge wallet at https://www.runninghub.cn/vip-rights/4",
                    "4. Send the key in chat or add to ~/.openclaw/openclaw.json: skills.entries.runninghub.apiKey",
                ],
            }, ensure_ascii=False))
            return
    
        key_prefix = key[:4] + "****"
        key_source = get_key_source(api_key_arg)
    
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {key}",
        }
        result = curl_post_json(ACCOUNT_STATUS_URL, {"apikey": key}, headers, timeout=15)
    
        if result.returncode != 0:
            print(json.dumps({
                "status": "invalid_key",
                "key_prefix": key_prefix,
                "key_source": key_source,
                "message": "API key is invalid or expired, or network error",
                "detail": (result.stdout or result.stderr)[:300],
                "manage_url": "https://www.runninghub.cn/enterprise-api/sharedApi",
            }, ensure_ascii=False))
            return
    
        try:
            resp = json.loads(result.stdout)
        except json.JSONDecodeError:
            print(json.dumps({
                "status": "error",
                "key_prefix": key_prefix,
                "message": f"Unexpected response: {result.stdout[:300]}",
            }, ensure_ascii=False))
            return
    
        if resp.get("code") != 0:
            print(json.dumps({
                "status": "invalid_key",
                "key_prefix": key_prefix,
                "key_source": key_source,
                "message": resp.get("msg", "API key verification failed"),
                "manage_url": "https://www.runninghub.cn/enterprise-api/sharedApi",
            }, ensure_ascii=False))
            return
    
        data = resp.get("data", {})
        balance = data.get("remainMoney")
        balance_str = str(balance) if balance is not None else "0"
        currency = data.get("currency", "CNY")
    
        try:
            balance_num = float(balance_str)
        except (ValueError, TypeError):
            balance_num = 0.0
    
        if balance_num <= 0:
            print(json.dumps({
                "status": "no_balance",
                "key_prefix": key_prefix,
                "key_source": key_source,
                "balance": balance_str,
                "currency": currency,
                "coins": data.get("remainCoins", "0"),
                "running_tasks": data.get("currentTaskCounts", "0"),
                "api_type": data.get("apiType", ""),
                "message": "Wallet balance is zero. Recharge required.",
                "recharge_url": "https://www.runninghub.cn/vip-rights/4",
            }, ensure_ascii=False))
            return
    
        print(json.dumps({
            "status": "ready",
            "key_prefix": key_prefix,
            "key_source": key_source,
            "balance": balance_str,
            "currency": currency,
            "coins": data.get("remainCoins", "0"),
            "running_tasks": data.get("currentTaskCounts", "0"),
            "api_type": data.get("apiType", ""),
        }, ensure_ascii=False))
    
    
    # ---------------------------------------------------------------------------
    # --list / --info: capability discovery
    # ---------------------------------------------------------------------------
    
    def cmd_list(type_filter: str | None, task_filter: str | None):
        caps = load_capabilities()
        endpoints = caps["endpoints"]
    
        if type_filter:
            endpoints = [e for e in endpoints if e["output_type"] == type_filter]
        if task_filter:
            endpoints = [e for e in endpoints if e["task"] == task_filter]
    
        rows = []
        for e in endpoints:
            name = e["name_cn"] or e["name_en"] or e["endpoint"]
            tags = ",".join(e["tags"]) if e["tags"] else ""
            pop = e["popularity"] if e["popularity"] < 99 else "-"
            rows.append(f"  [{e['output_type']:6s}] {e['task']:25s} rank={str(pop):3s} {e['endpoint']:60s} {name}")
    
        print(f"Total: {len(rows)} endpoints")
        if type_filter:
            print(f"Filter: type={type_filter}")
        if task_filter:
            print(f"Filter: task={task_filter}")
        print()
        for r in rows:
            print(r)
    
    
    def cmd_info(endpoint: str):
        ep = find_endpoint(endpoint)
        if not ep:
            print(f"Error: endpoint '{endpoint}' not found", file=sys.stderr)
            print("Use --list to see available endpoints.", file=sys.stderr)
            sys.exit(1)
        print(json.dumps(ep, indent=2, ensure_ascii=False))
    
    
    # ---------------------------------------------------------------------------
    # Media handling
    # ---------------------------------------------------------------------------
    
    def upload_file(api_key: str, file_path: str) -> str:
        url = f"{BASE_URL}{UPLOAD_ENDPOINT}"
        cmd = ["curl", "-s", "-S", "--fail-with-body", "-X", "POST", url,
               "-H", f"Authorization: Bearer {api_key}",
               "-F", f"file=@{file_path}", "--max-time", "120"]
        result = subprocess.run(cmd, capture_output=True, text=True)
        if result.returncode != 0:
            print(f"Upload failed: {result.stderr}", file=sys.stderr)
            sys.exit(1)
        try:
            resp = json.loads(result.stdout)
        except json.JSONDecodeError:
            print(f"Upload returned invalid JSON: {result.stdout[:500]}", file=sys.stderr)
            sys.exit(1)
        if resp.get("code") == 0:
            return resp["data"]["download_url"]
        print(f"Upload error: {resp}", file=sys.stderr)
        sys.exit(1)
    
    
    def image_to_data_uri(file_path: str) -> str:
        mime_type = mimetypes.guess_type(file_path)[0] or "image/png"
        with open(file_path, "rb") as f:
            encoded = base64.b64encode(f.read()).decode()
        return f"data:{mime_type};base64,{encoded}"
    
    
    def resolve_media(api_key: str, media_path: str, force_upload: bool = False) -> str:
        if media_path.startswith(("http://", "https://")):
            return media_path
        path = Path(media_path)
        if not path.exists():
            print(f"Error: file not found: {media_path}", file=sys.stderr)
            sys.exit(1)
        size = path.stat().st_size
        if force_upload or size > 5 * 1024 * 1024:
            return upload_file(api_key, media_path)
        return image_to_data_uri(media_path)
    
    
    # ---------------------------------------------------------------------------
    # Task execution: submit → poll → download
    # ---------------------------------------------------------------------------
    
    def poll_once(api_key: str, url: str, task_id: str) -> dict | None:
        """Single poll attempt with retry on transient network errors."""
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}",
        }
        for attempt in range(3):
            result = curl_post_json(url, {"taskId": task_id}, headers, timeout=30)
            if result.returncode == 0:
                try:
                    return json.loads(result.stdout)
                except json.JSONDecodeError:
                    return None
            if attempt < 2:
                time.sleep(2)
        return None
    
    
    def poll_task(api_key: str, task_id: str) -> dict:
        url = f"{BASE_URL}{POLL_ENDPOINT}"
        print(f"Task ID: {task_id}")
        print("Waiting for result", end="", flush=True)
    
        elapsed = 0
        consecutive_failures = 0
        while elapsed < MAX_POLL_SECONDS:
            time.sleep(POLL_INTERVAL)
            elapsed += POLL_INTERVAL
            resp = poll_once(api_key, url, task_id)
            if resp is None:
                consecutive_failures += 1
                print("x", end="", flush=True)
                if consecutive_failures >= 5:
                    print(f"\nToo many consecutive poll failures", file=sys.stderr)
                    sys.exit(1)
                continue
            consecutive_failures = 0
            status = resp.get("status", "UNKNOWN")
    
            if status == "SUCCESS":
                print(f" done ({elapsed}s)")
                return resp
            if status == "FAILED":
                error_msg = resp.get("errorMessage", "Unknown error")
                error_code = resp.get("errorCode", "")
                msg_lower = f"{error_msg} {error_code}".lower()
                if any(k in msg_lower for k in ["balance", "insufficient", "余额", "credit"]):
                    print(json.dumps({
                        "error": "INSUFFICIENT_BALANCE",
                        "message": f"Task failed: {error_msg}",
                        "recharge_url": "https://www.runninghub.cn/vip-rights/4",
                    }, ensure_ascii=False), file=sys.stderr)
                else:
                    print(json.dumps({
                        "error": "TASK_FAILED",
                        "message": f"Task failed: [{error_code}] {error_msg}",
                    }, ensure_ascii=False), file=sys.stderr)
                sys.exit(1)
    
            print(".", end="", flush=True)
    
        print(f"\nTimeout after {MAX_POLL_SECONDS}s", file=sys.stderr)
        sys.exit(1)
    
    
    def download_file(url: str, output_path: str) -> str:
        Path(output_path).parent.mkdir(parents=True, exist_ok=True)
        cmd = ["curl", "-s", "-S", "-L", "-o", output_path, "--max-time", "300", url]
        result = subprocess.run(cmd, capture_output=True, text=True)
        if result.returncode != 0:
            print(f"Download failed: {result.stderr}", file=sys.stderr)
            sys.exit(1)
        return str(Path(output_path).resolve())
    
    
    import struct
    
    def fix_mov_to_mp4(file_path: str) -> bool:
        """Rewrite QuickTime MOV ftyp box to standard MP4 for platform compatibility.
        Only touches the ftyp header; no re-encoding, no external dependencies.
        Returns True if the file was patched."""
        try:
            with open(file_path, "rb") as f:
                header = f.read(64)
        except OSError:
            return False
    
        if len(header) < 16:
            return False
    
        box_size = struct.unpack(">I", header[0:4])[0]
        if header[4:8] != b"ftyp" or box_size < 16 or box_size > len(header):
            return False
    
        if header[8:12] != b"qt  ":
            return False
    
        minor_version = header[12:16]
        brands = [b"isom", b"iso2", b"avc1", b"mp41"]
        brands_space = box_size - 16
        max_brands = brands_space // 4
        used_brands = brands[:max_brands]
    
        new_ftyp = struct.pack(">I", box_size) + b"ftyp" + b"isom" + minor_version
        for b in used_brands:
            new_ftyp += b
        new_ftyp += b"\x00" * (box_size - len(new_ftyp))
    
        with open(file_path, "r+b") as f:
            f.write(new_ftyp)
    
        print(f"Fixed MOV→MP4 container: {Path(file_path).name}", file=sys.stderr)
        return True
    
    
    def build_payload(endpoint_def: dict, args) -> dict:
        """Build API payload from endpoint definition and CLI args."""
        api_key = require_api_key(args.api_key)
        payload = {}
    
        # Collect --param key=value pairs
        extra_params = {}
        if args.param:
            for p in args.param:
                if "=" not in p:
                    print(f"Error: invalid --param format '{p}', expected key=value", file=sys.stderr)
                    sys.exit(1)
                k, v = p.split("=", 1)
                extra_params[k] = v
    
        # --prompt is a convenient alias for the "prompt" or "text" param
        prompt_key = None
        for param in endpoint_def["params"]:
            if param["key"] in ("prompt", "text"):
                prompt_key = param["key"]
                break
    
        if args.prompt and prompt_key:
            payload[prompt_key] = args.prompt
        elif args.prompt:
            payload["prompt"] = args.prompt
    
        # Map CLI media inputs to the appropriate payload keys
        media_keys = []
        for param in endpoint_def["params"]:
            if param["type"] in ("IMAGE", "VIDEO", "AUDIO"):
                media_keys.append(param)
    
        # --image can map to imageUrl, imageUrls, firstImageUrl, etc.
        if args.image:
            image_params = [p for p in media_keys if p["type"] == "IMAGE"]
            if len(args.image) == 1 and len(image_params) >= 1:
                pk = image_params[0]["key"]
                needs_upload = pk in ("videoUrl",) or endpoint_def["output_type"] == "video"
                resolved = resolve_media(api_key, args.image[0], force_upload=needs_upload)
                if image_params[0].get("multiple"):
                    payload[pk] = [resolved]
                else:
                    payload[pk] = resolved
            elif len(args.image) > 1:
                multi_param = next((p for p in image_params if p.get("multiple")), None)
                if multi_param:
                    payload[multi_param["key"]] = [
                        resolve_media(api_key, img, force_upload=True) for img in args.image
                    ]
                else:
                    for i, (img, param) in enumerate(zip(args.image, image_params)):
                        payload[param["key"]] = resolve_media(api_key, img, force_upload=True)
    
        if args.video:
            video_params = [p for p in media_keys if p["type"] == "VIDEO"]
            if video_params:
                payload[video_params[0]["key"]] = resolve_media(api_key, args.video, force_upload=True)
    
        if args.audio:
            audio_params = [p for p in media_keys if p["type"] == "AUDIO"]
            if audio_params:
                payload[audio_params[0]["key"]] = resolve_media(api_key, args.audio, force_upload=True)
    
        # Apply extra --param key=value (overrides defaults)
        for k, v in extra_params.items():
            param_def = next((p for p in endpoint_def["params"] if p["key"] == k), None)
            if param_def and param_def["type"] == "BOOLEAN":
                payload[k] = v.lower() in ("true", "1", "yes")
            elif param_def and param_def["type"] in ("INT", "FLOAT"):
                try:
                    payload[k] = int(v) if param_def["type"] == "INT" else float(v)
                except ValueError:
                    payload[k] = v
            else:
                payload[k] = v
    
        # Fill defaults for required params not yet set
        for param in endpoint_def["params"]:
            if param["key"] not in payload and param.get("required") and "default" in param:
                payload[param["key"]] = param["default"]
    
        return payload
    
    
    def cmd_execute(args):
        """Execute a generation task."""
        api_key = require_api_key(args.api_key)
    
        # Resolve endpoint
        if args.endpoint:
            endpoint_def = find_endpoint(args.endpoint)
            if not endpoint_def:
                print(f"Error: endpoint '{args.endpoint}' not found", file=sys.stderr)
                print("Use --list to see available endpoints.", file=sys.stderr)
                sys.exit(1)
        elif args.task:
            endpoint_def = find_best_for_task(args.task)
            if not endpoint_def:
                print(f"Error: no endpoint found for task '{args.task}'", file=sys.stderr)
                print("Use --list to see available tasks.", file=sys.stderr)
                sys.exit(1)
            print(f"Auto-selected: {endpoint_def['endpoint']} ({endpoint_def.get('name_cn', '')})", file=sys.stderr)
        else:
            print("Error: --endpoint or --task is required", file=sys.stderr)
            sys.exit(1)
    
        payload = build_payload(endpoint_def, args)
        submit_url = f"{BASE_URL}/{endpoint_def['endpoint']}"
    
        print(f"Submitting {endpoint_def['task']} to {endpoint_def['endpoint']}...", file=sys.stderr)
        resp = api_post(api_key, submit_url, payload)
        task_id = resp.get("taskId")
        if not task_id:
            print(f"Error: no taskId in response: {json.dumps(resp, ensure_ascii=False)}", file=sys.stderr)
            sys.exit(1)
    
        final = resp if (resp.get("status") == "SUCCESS" and resp.get("results")) else poll_task(api_key, task_id)
        results = final.get("results")
        if not results:
            print("Error: no results in final response", file=sys.stderr)
            sys.exit(1)
    
        result_item = results[0]
        result_url = result_item.get("url") or result_item.get("outputUrl")
        output_type_ext = result_item.get("outputType", "")
    
        # Extract cost from usage data
        usage = final.get("usage") or {}
        consume_money = usage.get("consumeMoney") or usage.get("thirdPartyConsumeMoney")
        task_cost_time = usage.get("taskCostTime")
    
        # Text results (for string output_type endpoints)
        if not result_url:
            text_result = result_item.get("text") or result_item.get("content") or result_item.get("output")
            if text_result:
                print(text_result)
                if consume_money is not None:
                    print(f"COST:¥{consume_money}")
                if task_cost_time and str(task_cost_time) != "0":
                    print(f"DURATION:{task_cost_time}s")
                return
            print(json.dumps({"error": "TASK_FAILED", "message": "No URL or text in results"}))
            sys.exit(1)
    
        output_path = args.output
        if not output_path:
            ext = output_type_ext or _guess_ext(endpoint_def["output_type"])
            output_path = f"/tmp/openclaw/rh-output/result.{ext}"
    
        if output_type_ext:
            output_path = str(Path(output_path).with_suffix(f".{output_type_ext}"))
    
        print(f"Downloading result to local file...", file=sys.stderr)
        full_path = download_file(result_url, output_path)
        fix_mov_to_mp4(full_path)
        print(f"OUTPUT_FILE:{full_path}")
    
        if consume_money is not None:
            print(f"COST:¥{consume_money}")
        if task_cost_time and str(task_cost_time) != "0":
            print(f"DURATION:{task_cost_time}s")
    
    
    def _guess_ext(output_type: str) -> str:
        return {"image": "png", "video": "mp4", "audio": "mp3", "3d": "glb"}.get(output_type, "bin")
    
    
    # ---------------------------------------------------------------------------
    # CLI
    # ---------------------------------------------------------------------------
    
    def main():
        parser = argparse.ArgumentParser(
            description="RunningHub universal API client for OpenClaw",
            formatter_class=argparse.RawDescriptionHelpFormatter,
            epilog="""\
    Modes:
      --check                           Check API key and account balance
      --list [--type T] [--task T]      List available endpoints
      --info ENDPOINT                   Show endpoint parameter details
      --endpoint EP [options]           Execute with specific endpoint
      --task TASK [options]             Execute with auto-selected best endpoint
    
    Examples:
      python3 runninghub.py --check
      python3 runninghub.py --list --type image
      python3 runninghub.py --info rhart-image-n-pro/text-to-image
      python3 runninghub.py --endpoint rhart-image-n-pro/text-to-image --prompt "a cute dog" --output /tmp/dog.png
      python3 runninghub.py --task text-to-image --prompt "a cute dog" --output /tmp/dog.png
    """,
        )
    
        # Mode flags
        parser.add_argument("--check", action="store_true", help="Check API key and account status")
        parser.add_argument("--list", action="store_true", help="List available endpoints")
        parser.add_argument("--info", metavar="ENDPOINT", help="Show details for an endpoint")
    
        # Execution params
        parser.add_argument("--endpoint", "-e", help="API endpoint to call")
        parser.add_argument("--task", "-t", help="Task type (auto-selects best endpoint)")
        parser.add_argument("--prompt", "-p", help="Text prompt")
        parser.add_argument("--image", "-i", action="append", help="Input image path or URL (repeatable)")
        parser.add_argument("--video", help="Input video path or URL")
        parser.add_argument("--audio", help="Input audio path or URL")
        parser.add_argument("--param", action="append", help="Extra parameter as key=value (repeatable)")
        parser.add_argument("--output", "-o", help="Output file path")
        parser.add_argument("--api-key", "-k", help="API key (optional, resolved from config)")
    
        # Filters for --list
        parser.add_argument("--type", dest="type_filter", help="Filter by output type (image/video/audio/3d/string)")
    
        args = parser.parse_args()
    
        if args.check:
            cmd_check(args.api_key)
        elif args.list:
            cmd_list(args.type_filter, args.task)
        elif args.info:
            cmd_info(args.info)
        elif args.endpoint or args.task:
            cmd_execute(args)
        else:
            parser.print_help()
            sys.exit(1)
    
    
    if __name__ == "__main__":
        main()
    
  • runninghub/scripts/runninghub_app.py19 KBe19a302a1cd7upstream ↗
    #!/usr/bin/env python3
    """
    RunningHub AI Application client for OpenClaw.
    
    Run any RunningHub AI Application (custom ComfyUI workflow) by webappId.
    Uses only Python stdlib and curl.
    
    Modes:
      --check                          Account health check (key + balance)
      --list [--sort S] [--size N]     Browse AI applications
      --info WEBAPP_ID                 Show app's modifiable nodes
      --run WEBAPP_ID [options]        Execute an AI application task
    """
    
    from __future__ import annotations
    
    import argparse
    import json
    import os
    import re
    import subprocess
    import sys
    import tempfile
    from pathlib import Path
    
    API_HOST = "https://www.runninghub.cn"
    APP_LIST_PATH = "/openapi/v2/aiapp/list"
    NODE_INFO_PATH = "/api/webapp/apiCallDemo"
    UPLOAD_PATH = "/task/openapi/upload"
    SUBMIT_PATH = "/task/openapi/ai-app/run"
    
    SCRIPT_DIR = Path(__file__).resolve().parent
    
    sys.path.insert(0, str(SCRIPT_DIR))
    from runninghub import resolve_api_key, require_api_key, cmd_check, poll_task, fix_mov_to_mp4  # noqa: E402
    
    
    # ---------------------------------------------------------------------------
    # HTTP helpers (curl-based, stdlib only)
    # ---------------------------------------------------------------------------
    
    def curl_get(url: str, timeout: int = 30) -> subprocess.CompletedProcess:
        cmd = ["curl", "-s", "-S", "--fail-with-body", "--max-time", str(timeout), url]
        return subprocess.run(cmd, capture_output=True, text=True)
    
    
    def curl_post_json(url: str, payload: dict, timeout: int = 60) -> subprocess.CompletedProcess:
        with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
            json.dump(payload, f)
            tmp_path = f.name
        try:
            cmd = [
                "curl", "-s", "-S", "--fail-with-body", "-X", "POST", url,
                "--max-time", str(timeout),
                "-H", "Content-Type: application/json",
                "-H", f"Host: {API_HOST.split('//')[1]}",
                "-d", f"@{tmp_path}",
            ]
            return subprocess.run(cmd, capture_output=True, text=True)
        finally:
            os.unlink(tmp_path)
    
    
    def curl_upload(url: str, api_key: str, file_path: str, timeout: int = 120) -> subprocess.CompletedProcess:
        cmd = [
            "curl", "-s", "-S", "--fail-with-body", "-X", "POST", url,
            "--max-time", str(timeout),
            "-H", f"Host: {API_HOST.split('//')[1]}",
            "-F", f"apiKey={api_key}",
            "-F", "fileType=input",
            "-F", f"file=@{file_path}",
        ]
        return subprocess.run(cmd, capture_output=True, text=True)
    
    
    def _parse_response(result: subprocess.CompletedProcess, context: str) -> dict:
        body = result.stdout or result.stderr
        if result.returncode != 0:
            try:
                err = json.loads(body)
                msg = err.get("msg", body)
            except (json.JSONDecodeError, TypeError):
                msg = body
            print(json.dumps({
                "error": "API_ERROR",
                "message": f"{context} failed: {msg}",
            }, ensure_ascii=False), file=sys.stderr)
            sys.exit(1)
        try:
            return json.loads(result.stdout)
        except json.JSONDecodeError:
            print(json.dumps({
                "error": "API_ERROR",
                "message": f"{context}: invalid JSON response: {result.stdout[:500]}",
            }, ensure_ascii=False), file=sys.stderr)
            sys.exit(1)
    
    
    # ---------------------------------------------------------------------------
    # AI Application API functions
    # ---------------------------------------------------------------------------
    
    def _extract_webapp_id(invoke_example: str) -> str | None:
        """Extract webappId from the invokeExample cURL string."""
        m = re.search(r'/run/ai-app/(\d+)', invoke_example)
        return m.group(1) if m else None
    
    
    def list_apps(api_key: str, sort: str = "RECOMMEND", size: int = 10,
                  page: int = 1, days: int = 7) -> dict:
        url = f"{API_HOST}{APP_LIST_PATH}"
        payload: dict = {"current": page, "size": min(size, 50), "sort": sort}
        if sort == "HOTTEST" and days:
            payload["days"] = days
    
        with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
            json.dump(payload, f)
            tmp_path = f.name
        try:
            cmd = [
                "curl", "-s", "-S", "--fail-with-body", "-X", "POST", url,
                "--max-time", "60",
                "-H", "Content-Type: application/json",
                "-H", f"Authorization: {api_key}",
                "-d", f"@{tmp_path}",
            ]
            result = subprocess.run(cmd, capture_output=True, text=True)
        finally:
            os.unlink(tmp_path)
    
        resp = _parse_response(result, "List AI apps")
    
        if resp.get("code") != 0:
            print(json.dumps({
                "error": "LIST_FAILED",
                "message": resp.get("msg", "Failed to list AI apps"),
            }, ensure_ascii=False), file=sys.stderr)
            sys.exit(1)
    
        return resp.get("data", {})
    
    
    def get_node_info(api_key: str, webapp_id: str) -> list[dict]:
        url = f"{API_HOST}{NODE_INFO_PATH}?apiKey={api_key}&webappId={webapp_id}"
        result = curl_get(url)
        resp = _parse_response(result, "Get node info")
    
        if resp.get("code") != 0:
            print(json.dumps({
                "error": "APP_INFO_FAILED",
                "message": resp.get("msg", "Failed to get AI app info"),
                "detail": resp,
            }, ensure_ascii=False), file=sys.stderr)
            sys.exit(1)
    
        node_list = resp.get("data", {}).get("nodeInfoList", [])
        if not node_list:
            print(json.dumps({
                "error": "NO_NODES",
                "message": "No modifiable nodes found for this AI app. "
                           "Make sure the app has been run at least once on the web.",
            }, ensure_ascii=False), file=sys.stderr)
            sys.exit(1)
    
        return node_list
    
    
    def upload_file(api_key: str, file_path: str) -> str:
        path = Path(file_path)
        if not path.exists():
            print(f"Error: file not found: {file_path}", file=sys.stderr)
            sys.exit(1)
    
        url = f"{API_HOST}{UPLOAD_PATH}"
        print(f"Uploading {path.name}...", file=sys.stderr)
        result = curl_upload(url, api_key, file_path)
        resp = _parse_response(result, "Upload file")
    
        if resp.get("code") != 0 or resp.get("msg") != "success":
            print(json.dumps({
                "error": "UPLOAD_FAILED",
                "message": f"Upload failed: {resp.get('msg', resp)}",
            }, ensure_ascii=False), file=sys.stderr)
            sys.exit(1)
    
        file_name = resp.get("data", {}).get("fileName")
        if not file_name:
            print(json.dumps({
                "error": "UPLOAD_FAILED",
                "message": "Upload succeeded but no fileName returned",
            }, ensure_ascii=False), file=sys.stderr)
            sys.exit(1)
    
        print(f"Uploaded: {file_name}", file=sys.stderr)
        return file_name
    
    
    def submit_task(api_key: str, webapp_id: str, node_info_list: list[dict],
                    instance_type: str = "default") -> dict:
        url = f"{API_HOST}{SUBMIT_PATH}"
        payload = {
            "apiKey": api_key,
            "webappId": int(webapp_id),
            "nodeInfoList": node_info_list,
        }
        if instance_type and instance_type != "default":
            payload["instanceType"] = instance_type
    
        print(f"Submitting AI app task (webapp {webapp_id})...", file=sys.stderr)
        result = curl_post_json(url, payload)
        resp = _parse_response(result, "Submit task")
    
        if resp.get("code") != 0:
            print(json.dumps({
                "error": "SUBMIT_FAILED",
                "message": f"Submit failed: {resp.get('msg', resp)}",
                "detail": resp,
            }, ensure_ascii=False), file=sys.stderr)
            sys.exit(1)
    
        data = resp.get("data", {})
        task_id = data.get("taskId")
        if not task_id:
            print(json.dumps({
                "error": "SUBMIT_FAILED",
                "message": "No taskId in response",
                "detail": resp,
            }, ensure_ascii=False), file=sys.stderr)
            sys.exit(1)
    
        prompt_tips_str = data.get("promptTips")
        if prompt_tips_str:
            try:
                tips = json.loads(prompt_tips_str)
                node_errors = tips.get("node_errors", {})
                if node_errors:
                    print(json.dumps({
                        "error": "NODE_ERRORS",
                        "message": "Workflow has node errors",
                        "node_errors": node_errors,
                    }, ensure_ascii=False), file=sys.stderr)
                    sys.exit(1)
            except (json.JSONDecodeError, TypeError):
                pass
    
        return data
    
    
    def download_file(url: str, output_path: str) -> str:
        Path(output_path).parent.mkdir(parents=True, exist_ok=True)
        cmd = ["curl", "-s", "-S", "-L", "-o", output_path, "--max-time", "300", url]
        result = subprocess.run(cmd, capture_output=True, text=True)
        if result.returncode != 0:
            print(f"Download failed: {result.stderr}", file=sys.stderr)
            sys.exit(1)
        return str(Path(output_path).resolve())
    
    
    # ---------------------------------------------------------------------------
    # --node / --file argument parsing
    # ---------------------------------------------------------------------------
    
    def parse_node_arg(arg: str) -> tuple[str, str, str]:
        """Parse 'nodeId:fieldName=value' into (nodeId, fieldName, value)."""
        colon_idx = arg.find(":")
        if colon_idx == -1:
            print(f"Error: invalid --node format '{arg}', expected nodeId:fieldName=value", file=sys.stderr)
            sys.exit(1)
        node_id = arg[:colon_idx]
        rest = arg[colon_idx + 1:]
        eq_idx = rest.find("=")
        if eq_idx == -1:
            print(f"Error: invalid --node format '{arg}', expected nodeId:fieldName=value", file=sys.stderr)
            sys.exit(1)
        field_name = rest[:eq_idx]
        field_value = rest[eq_idx + 1:]
        return node_id, field_name, field_value
    
    
    def apply_modifications(api_key: str, node_list: list[dict],
                            node_args: list[str] | None,
                            file_args: list[str] | None) -> list[dict]:
        if node_args:
            for arg in node_args:
                nid, fname, fval = parse_node_arg(arg)
                target = next(
                    (n for n in node_list if n["nodeId"] == nid and n["fieldName"] == fname),
                    None,
                )
                if target:
                    target["fieldValue"] = fval
                else:
                    node_list.append({"nodeId": nid, "fieldName": fname, "fieldValue": fval})
    
        if file_args:
            for arg in file_args:
                nid, fname, fpath = parse_node_arg(arg)
                uploaded_name = upload_file(api_key, fpath)
                target = next(
                    (n for n in node_list if n["nodeId"] == nid and n["fieldName"] == fname),
                    None,
                )
                if target:
                    target["fieldValue"] = uploaded_name
                else:
                    node_list.append({"nodeId": nid, "fieldName": fname, "fieldValue": uploaded_name})
    
        return node_list
    
    
    # ---------------------------------------------------------------------------
    # Commands
    # ---------------------------------------------------------------------------
    
    def _download_cover(url: str, out_path: str) -> bool:
        """Download a cover image. Returns True on success."""
        if not url:
            return False
        Path(out_path).parent.mkdir(parents=True, exist_ok=True)
        cmd = ["curl", "-s", "-S", "-L", "-o", out_path, "--max-time", "15", url]
        result = subprocess.run(cmd, capture_output=True, text=True)
        return result.returncode == 0 and Path(out_path).exists() and Path(out_path).stat().st_size > 0
    
    
    def cmd_list(api_key: str, sort: str, size: int, page: int, days: int):
        data = list_apps(api_key, sort, size, page, days)
        records = data.get("records", [])
    
        cover_dir = Path("/tmp/openclaw/rh-output/app_covers")
        cover_dir.mkdir(parents=True, exist_ok=True)
    
        apps = []
        for i, r in enumerate(records):
            webapp_id = _extract_webapp_id(r.get("invokeExample", ""))
            cover_url = r.get("cover", "")
    
            app: dict = {
                "title": r.get("title", ""),
                "description": r.get("description", ""),
            }
            if webapp_id:
                app["webappId"] = webapp_id
    
            if cover_url:
                ext = cover_url.split("?")[0].rsplit(".", 1)[-1].lower() if "." in cover_url.split("/")[-1] else "jpg"
                if ext not in ("jpg", "jpeg", "png", "webp", "gif"):
                    ext = "jpg"
                cover_path = str(cover_dir / f"cover_{sort.lower()}_p{page}_{i+1}.{ext}")
                if _download_cover(cover_url, cover_path):
                    app["coverFile"] = str(Path(cover_path).resolve())
                else:
                    print(f"Warning: failed to download cover for '{app['title']}'", file=sys.stderr)
    
            apps.append(app)
    
        output = {
            "sort": sort,
            "page": int(data.get("current", page)),
            "size": int(data.get("size", size)),
            "total": int(data.get("total", 0)),
            "pages": int(data.get("pages", 0)),
            "hasNext": data.get("hasNext", False),
            "apps": apps,
        }
        print(json.dumps(output, indent=2, ensure_ascii=False))
    
    
    def cmd_info(api_key: str, webapp_id: str):
        node_list = get_node_info(api_key, webapp_id)
        print(json.dumps({
            "webappId": webapp_id,
            "nodeCount": len(node_list),
            "nodes": node_list,
        }, indent=2, ensure_ascii=False))
    
    
    def cmd_run(args):
        api_key = require_api_key(args.api_key)
        webapp_id = args.run
    
        node_list = get_node_info(api_key, webapp_id)
        node_list = apply_modifications(api_key, node_list, args.node, args.file)
    
        data = submit_task(api_key, webapp_id, node_list, args.instance_type or "default")
        task_id = str(data["taskId"])
    
        final = poll_task(api_key, task_id)
        results = final.get("results")
    
        usage = final.get("usage") or {}
        consume_money = usage.get("consumeMoney") or usage.get("thirdPartyConsumeMoney")
        task_cost_time = usage.get("taskCostTime")
    
        if not results:
            print(json.dumps({
                "error": "TASK_FAILED",
                "message": "No results in final response",
            }, ensure_ascii=False), file=sys.stderr)
            sys.exit(1)
    
        file_urls = []
        for item in results:
            url = item.get("url") or item.get("outputUrl")
            ext = item.get("outputType", "")
            if url:
                file_urls.append((url, ext))
    
        if not file_urls:
            text_results = []
            for item in results:
                t = item.get("text") or item.get("content") or item.get("output")
                if t:
                    text_results.append(t)
            if text_results:
                for t in text_results:
                    print(t)
                if consume_money is not None:
                    print(f"COST:¥{consume_money}")
                return
            print(json.dumps(results, indent=2, ensure_ascii=False))
            return
    
        output_base = args.output
        for i, (url, ext) in enumerate(file_urls):
            if not ext:
                ext = _guess_ext_from_url(url)
            if output_base:
                if len(file_urls) == 1:
                    out_path = output_base
                else:
                    stem = Path(output_base).stem
                    suffix = Path(output_base).suffix or f".{ext}"
                    out_path = str(Path(output_base).parent / f"{stem}_{i+1}{suffix}")
            else:
                out_path = f"/tmp/openclaw/rh-output/app_result_{i+1}.{ext}"
    
            if ext:
                out_path = str(Path(out_path).with_suffix(f".{ext}"))
            elif not Path(out_path).suffix:
                out_path = f"{out_path}.png"
    
            print(f"Downloading result {i+1}/{len(file_urls)}...", file=sys.stderr)
            full_path = download_file(url, out_path)
            fix_mov_to_mp4(full_path)
            print(f"OUTPUT_FILE:{full_path}")
    
        if consume_money is not None:
            print(f"COST:¥{consume_money}")
        if task_cost_time and str(task_cost_time) != "0":
            print(f"DURATION:{task_cost_time}s")
    
    
    def _guess_ext_from_url(url: str) -> str:
        path = url.split("?")[0]
        if "." in path.split("/")[-1]:
            return path.split("/")[-1].rsplit(".", 1)[-1].lower()
        return "png"
    
    
    # ---------------------------------------------------------------------------
    # CLI
    # ---------------------------------------------------------------------------
    
    def main():
        parser = argparse.ArgumentParser(
            description="RunningHub AI Application client for OpenClaw",
            formatter_class=argparse.RawDescriptionHelpFormatter,
            epilog="""\
    Modes:
      --check                           Check API key and account balance
      --list [--sort S] [--size N]      Browse AI applications
      --info WEBAPP_ID                  Show app's modifiable nodes
      --run WEBAPP_ID [options]         Execute an AI application task
    
    Examples:
      python3 runninghub_app.py --check
      python3 runninghub_app.py --list --sort HOTTEST --size 5
      python3 runninghub_app.py --list --sort NEWEST
      python3 runninghub_app.py --info 1877265245566922800
      python3 runninghub_app.py --run 1877265245566922800 \\
        --node "52:prompt=a girl dancing" \\
        --file "39:image=/tmp/photo.jpg" \\
        -o /tmp/result.png
    """,
        )
    
        parser.add_argument("--check", action="store_true", help="Check API key and account status")
        parser.add_argument("--list", action="store_true", help="Browse AI applications")
        parser.add_argument("--sort", choices=["RECOMMEND", "HOTTEST", "NEWEST"], default="RECOMMEND",
                            help="Sort order for --list (default: RECOMMEND)")
        parser.add_argument("--size", type=int, default=10,
                            help="Number of results per page for --list (default: 10, max: 50)")
        parser.add_argument("--page", type=int, default=1,
                            help="Page number for --list (default: 1)")
        parser.add_argument("--days", type=int, default=7,
                            help="Hotness window in days for --list --sort HOTTEST (default: 7)")
        parser.add_argument("--info", metavar="WEBAPP_ID", help="Show modifiable nodes for an AI app")
        parser.add_argument("--run", metavar="WEBAPP_ID", help="Run an AI application")
        parser.add_argument("--node", action="append",
                            help="Set node value as nodeId:fieldName=value (repeatable)")
        parser.add_argument("--file", action="append",
                            help="Upload file and set node as nodeId:fieldName=/path (repeatable)")
        parser.add_argument("--instance-type", choices=["default", "plus"], default="default",
                            help="GPU instance type: default=24G, plus=48G (default: default)")
        parser.add_argument("--output", "-o", help="Output file path")
        parser.add_argument("--api-key", "-k", help="API key (optional, resolved from config)")
    
        args = parser.parse_args()
    
        if args.check:
            cmd_check(args.api_key)
        elif args.list:
            api_key = require_api_key(args.api_key)
            cmd_list(api_key, args.sort, args.size, args.page, args.days)
        elif args.info:
            api_key = require_api_key(args.api_key)
            cmd_info(api_key, args.info)
        elif args.run:
            cmd_run(args)
        else:
            parser.print_help()
            sys.exit(1)
    
    
    if __name__ == "__main__":
        main()
    
  • runninghub/references/ai-application.md7.4 KB0bd915d27a2aupstream ↗
    # AI Application
    
    **Use `runninghub_app.py`** (NOT `runninghub.py`) for AI app tasks. AI apps are user-created ComfyUI workflows hosted on RunningHub.
    
    ## When to Trigger
    
    Trigger AI Application flow when the user:
    - Mentions "AI应用", "AI app", "工作流", "workflow", "webappId"
    - Pastes a RunningHub AI app link like `runninghub.cn/ai-detail/1877265245566922800`
    - Says "帮我跑这个应用", "运行这个工作流", "用这个 AI 应用处理"
    - Asks about available apps: "有什么AI应用", "最热门的应用", "最新的应用", "推荐什么应用"
    
    ## Browse AI Apps
    
    When the user wants to discover or explore AI apps, use `--list`:
    
    ```bash
    # Recommended apps (default)
    python3 {baseDir}/scripts/runninghub_app.py --list --sort RECOMMEND --size 10
    
    # Hottest apps in the last 7 days
    python3 {baseDir}/scripts/runninghub_app.py --list --sort HOTTEST --size 10 --days 7
    
    # Newest apps
    python3 {baseDir}/scripts/runninghub_app.py --list --sort NEWEST --size 10
    
    # Page 2
    python3 {baseDir}/scripts/runninghub_app.py --list --sort RECOMMEND --size 10 --page 2
    ```
    
    The output is JSON with an `apps` array. Each app has: `title`, `description`, `webappId`, and `coverFile` (local path to downloaded cover image).
    
    **Present apps to the user with cover images**. For EACH app, use the `message` tool to send its cover image, then describe it:
    
    ```
    For each app in the list:
      1. Call message tool: { "action": "send", "text": "1. 全能图片2.0 — 多功能图片生成", "media": "/tmp/openclaw/rh-output/app_covers/cover_xxx.png" }
      2. Move to next app
    After all apps, send a final message:
      { "action": "send", "text": "想试试哪个?告诉我编号就行!也可以说'下一页'看更多~" }
    ```
    
    Alternatively, if sending many images is too slow, you can send just the **first 3 covers** via `message` tool and list the rest as text.
    
    Rules:
    - ALWAYS send cover images via `message` tool — NEVER show cover URLs or file paths as text
    - Show title as bold, description if available
    - NEVER show raw webappId to the user
    - If `coverFile` is missing for an app (download failed), just show the title as text
    - If the user picks one, proceed to Step 1 (get webappId) using the selected app's webappId
    - For "翻页" / "下一页" / "更多", call `--list` with `--page 2`, etc.
    - Map user intents: "推荐" → RECOMMEND, "最热/热门" → HOTTEST, "最新/新的" → NEWEST
    
    ## Step 1 — Get webappId
    
    If the user provides a link, extract the number from the URL:
    - `https://www.runninghub.cn/ai-detail/1877265245566922800` → webappId = `1877265245566922800`
    
    If the user selected an app from the list, use its `webappId` directly.
    
    If no webappId and no list selection, ask warmly:
    > "好的!要用 AI 应用的话,发给我应用链接或者 webappId 就行~ 在应用页面的地址栏可以找到哦!或者我帮你看看有什么推荐的应用?"
    
    ## Step 2 — Fetch node info
    
    ```bash
    python3 {baseDir}/scripts/runninghub_app.py --info WEBAPP_ID
    ```
    
    This returns a JSON with all modifiable nodes, each containing:
    - `nodeId` — node identifier
    - `nodeName` — node type (e.g. "LoadImage", "RH_Translator")
    - `fieldName` — field key (e.g. "prompt", "image", "model")
    - `fieldValue` — current default value
    - `fieldType` — value type: `STRING`, `IMAGE`, `AUDIO`, `VIDEO`, `LIST`, `INT`, `FLOAT`, `BOOLEAN`
    - `description` — Chinese description of the field
    
    ## Step 3 — Present nodes to user
    
    Show the modifiable nodes in a friendly format. Example:
    
    > 这个 AI 应用有以下可修改的参数:
    >
    > 1. 📷 **上传图像** (节点 39) — 当前: 默认示例图
    > 2. ✏️ **图像编辑文本输入框** (节点 52) — 当前: "给这个女人的发型变成齐耳短发"
    > 3. 🔄 **模型切换** (节点 37) — 当前: flux-kontext-pro
    > 4. 📐 **输出比例** (节点 37) — 当前: match_input_image
    >
    > 你想修改哪些?直接告诉我就行~ 比如 "换张图片" 或 "把提示词改成xxx"
    
    Rules:
    - Use `description` as the label (not fieldName)
    - For IMAGE/AUDIO/VIDEO type, show 📷/🔊/🎬 icon and hint "上传文件"
    - For LIST type with `fieldData`, mention available options
    - For STRING type, show current value in quotes
    - NEVER show raw nodeId/fieldName to the user — translate to friendly Chinese
    
    ## Step 4 — Notify user, then execute
    
    **Before running the script**, ALWAYS send a progress notification via `message` tool:
    > "好的,开始运行 AI 应用啦!工作流生成通常需要几分钟,请稍等~ 🎬"
    
    This is critical — AI app tasks are slow, and users need to know the task has started. Send the notification FIRST, then execute the script.
    
    Map user's modifications to `--node` and `--file` arguments:
    
    ```bash
    # Modify text node + upload image
    python3 {baseDir}/scripts/runninghub_app.py --run WEBAPP_ID \
      --node "52:prompt=make her hair into a short bob cut" \
      --file "39:image=/tmp/openclaw/rh-output/photo.jpg" \
      -o /tmp/openclaw/rh-output/app_result_$(date +%s).png
    
    # Text-only modification
    python3 {baseDir}/scripts/runninghub_app.py --run WEBAPP_ID \
      --node "52:prompt=a boy with sunglasses" \
      -o /tmp/openclaw/rh-output/app_result_$(date +%s).png
    ```
    
    For GPU-intensive apps, the user can request a larger instance:
    - `--instance-type plus` — 48G VRAM (tell user: "用更强的 GPU 跑,可能会快一些但也贵一些")
    - Default is `default` (24G VRAM)
    
    ## Step 5 — Deliver results
    
    Same rules as standard API: use `message` tool, report cost, suggest next steps.
    
    If the app outputs multiple files, deliver all of them.
    
    ## AI App Script Reference
    
    ```bash
    # Get modifiable nodes for an AI app
    python3 {baseDir}/scripts/runninghub_app.py --info 1877265245566922800
    
    # Run AI app with text modification
    python3 {baseDir}/scripts/runninghub_app.py --run 1877265245566922800 \
      --node "52:prompt=a boy with sunglasses" \
      -o /tmp/openclaw/rh-output/app_$(date +%s).png
    
    # Run AI app with file upload + text modification
    python3 {baseDir}/scripts/runninghub_app.py --run 1877265245566922800 \
      --file "39:image=/tmp/openclaw/rh-output/photo.jpg" \
      --node "52:prompt=change hairstyle to short bob" \
      -o /tmp/openclaw/rh-output/app_$(date +%s).png
    
    # Run on a larger GPU instance
    python3 {baseDir}/scripts/runninghub_app.py --run 1877265245566922800 \
      --node "52:prompt=a girl dancing" \
      --instance-type plus \
      -o /tmp/openclaw/rh-output/app_$(date +%s).png
    ```
    
    Flags: `--node nodeId:fieldName=value`, `--file nodeId:fieldName=/path`, `--instance-type default|plus`, `-o path`
    Browse: `--list [--sort RECOMMEND|HOTTEST|NEWEST] [--size N] [--page N] [--days N]`
    Discovery: `--info WEBAPP_ID`
    
    ## AI App Errors
    
    | Error | Action |
    |-------|--------|
    | `APP_INFO_FAILED` | webappId wrong or app not publicly accessible → "这个应用 ID 可能不对,确认一下?" |
    | `NO_NODES` | App never run on web → "这个应用需要先在网页上成功跑一次才能通过 API 调用哦~" |
    | `NODE_ERRORS` | Workflow node errors → "工作流有节点出错了,可能参数不对,要不要看看错误信息?" |
    | `TASK_FAILED` | Runtime failure → show friendly error, offer to retry |
    | `UPLOAD_FAILED` | File upload failed → "文件上传失败了,再试一次?" |
    
    ## Notes
    
    - The AI app must have been run successfully at least once on the RunningHub web interface before it can be called via API.
    - Upload links are valid for one day only.
    - For prompts in AI apps, keep the user's original language unless the node description suggests otherwise.
    - AI app tasks may take 1-10+ minutes depending on the workflow complexity.
    
  • runninghub/references/api-key-setup.md1.1 KBba198a277cf4upstream ↗
    # API Key Setup
    
    ## Check Status
    
    Run `--check` first:
    ```bash
    python3 {baseDir}/scripts/runninghub.py --check
    ```
    
    React by `status`:
    - `"ready"` → "账号就绪!余额 ¥{balance},想做点什么?生图、视频、配音都可以找我~"
    - `"no_key"` → Guide: 1) 注册 runninghub.cn 2) 创建 Key 3) 充值 4) 发 Key 给我
    - `"no_balance"` → "余额空了~ 充个值就能继续:https://www.runninghub.cn/vip-rights/4"
    - `"invalid_key"` → "Key 不太对,去这里看看:https://www.runninghub.cn/enterprise-api/sharedApi"
    
    ## Save Key
    
    When user sends a key, verify with `--check --api-key THE_KEY`. If valid, save it:
    
    ```bash
    python3 -c "
    import json, pathlib
    p = pathlib.Path.home() / '.openclaw' / 'openclaw.json'
    p.parent.mkdir(exist_ok=True)
    cfg = json.loads(p.read_text()) if p.exists() else {}
    cfg.setdefault('skills', {}).setdefault('entries', {}).setdefault('runninghub', {})['apiKey'] = 'THE_KEY'
    p.write_text(json.dumps(cfg, indent=2))
    "
    ```
    
    Replace `THE_KEY` with the actual key. OpenClaw auto-injects it as `RUNNINGHUB_API_KEY` env var via `primaryEnv`.
    
  • runninghub/references/image-models.md3.3 KB9d1c46dfdf23upstream ↗
    # Image Model Selection
    
    **Whenever** the user wants ANY image generation (text-to-image OR image-edit/image-to-image), you MUST show this menu and WAIT:
    
    > 好的!先帮你选个图片模型~
    >
    > 1. 🎨 **全能图片PRO** — 香蕉Pro同款,默认推荐,综合效果最好
    > 2. ⚡ **全能图片V2** — 香蕉2同款,最快最便宜
    > 3. 🎭 **悠船 v7** — Midjourney 风格,欧美大片质感
    > 4. 🌸 **悠船 niji7** — 二次元/动漫风格,插画感满满
    > 5. 📷 **Seedream v5** — 字节跳动出品,写实照片感超强
    >
    > 说个数字就行~ 不选的话我默认用 🎨全能图片PRO 哦!
    
    **Do NOT invent your own model list. Do NOT skip this menu. Use EXACTLY this 5-model list.**
    
    After user replies, map choice → endpoint:
    
    **Text-to-image** (no source image):
    | # | Endpoint |
    |---|----------|
    | 1 (default) | `rhart-image-n-pro/text-to-image` |
    | 2 | `rhart-image-n-g31-flash/text-to-image` |
    | 3 | `youchuan/text-to-image-v7` |
    | 4 | `youchuan/text-to-image-niji7` |
    | 5 | `seedream-v5-lite/text-to-image` |
    
    **Image-to-image / Image edit** (user has source image):
    | # | Endpoint |
    |---|----------|
    | 1 (default) | `rhart-image-n-pro/edit` |
    | 2 | `rhart-image-n-g31-flash/image-to-image` |
    | 3 | `rhart-image-n-pro/edit` ⚠️ 悠船无图生图,回退到全能PRO |
    | 4 | `rhart-image-n-pro/edit` ⚠️ 悠船无图生图,回退到全能PRO |
    | 5 | `seedream-v5-lite/image-to-image` |
    
    When user picks 悠船 (3 or 4) for image-to-image, tell them warmly:
    > "悠船模型暂时不支持图生图,我帮你用全能图片PRO来处理哈~ 效果也很棒的!"
    
    ## Matching Rules
    
    - Number 1-5 → use that model
    - Partial name ("全能", "PRO", "V2") → match to #1 or #2
    - "悠船" / "Midjourney" / "MJ" → #3
    - "niji" / "二次元" / "动漫" → #4
    - "Seedream" / "种子" / "写实" / "照片" → #5
    - "随便" / "你选" / "默认" → #1
    - "最快的" / "便宜的" → #2
    - "效果最好的" → #1
    
    Skip menu ONLY if: user named a specific model, or said "跟上次一样" / "再来一个".
    
    ## After Model Is Chosen
    
    Confirm the choice warmly, then ask for missing info if needed:
    > "好嘞,用全能图片PRO!有什么画面要求吗?比如风格、尺寸、画质~"
    
    Smart defaults (use these if user doesn't specify):
    - Resolution: 2k
    - Aspect ratio: 1:1 (square); if user mentions landscape/横版 → 16:9; portrait/竖版 → 9:16
    
    ## Prompt Optimization
    
    When the user gives a short/vague prompt, ENHANCE it before sending to the API. Example:
    - User says: "画一只猫" → Enhance to: "A fluffy orange tabby cat sitting on a windowsill, warm afternoon sunlight streaming through, soft bokeh background, photorealistic, 4K"
    - User says: "赛博朋克城市" → Enhance to: "A neon-lit cyberpunk cityscape at night, towering skyscrapers with holographic billboards, rain-slicked streets reflecting pink and blue lights, cinematic wide-angle shot, 8K ultra-detailed"
    
    Always write prompts in **English** for best model results, even if the user speaks Chinese.
    
    ## AI Image Editing (special case)
    
    If the user wants **AI-powered image editing** (e.g. "把背景换成海边", "去掉这个人", "加个帽子"):
    - Use `alibaba/qwen-image-2.0-pro/image-edit` directly — no model menu needed for this case.
    - This is a different capability from the image generation models above.
    
  • runninghub/references/output-delivery.md2.2 KB26968ccfa026upstream ↗
    # Output & Delivery
    
    ## Progress Notification (for slow tasks)
    
    For video, AI app, 3D, and music generation: **ALWAYS send a `message` notification BEFORE starting the script.** These tasks take 1-10+ minutes. Users must know the task has started.
    
    ```json
    { "action": "send", "text": "开始生成啦,视频一般需要几分钟,请稍等~ 🎬", "target": "<user>" }
    ```
    
    Do this BEFORE calling `exec` to run the script. For fast tasks (text-to-image, image upscale, TTS), notification is optional.
    
    ## Media (image/video/audio/3D)
    
    Script prints `OUTPUT_FILE:/path` and optionally `COST:¥X.XX`.
    
    **You MUST use the `message` tool to deliver files. Printing file paths as text does NOT work — users on Feishu/Lark/Slack cannot access local paths.**
    
    Step 1 — ALWAYS call `message` tool:
    ```json
    { "action": "send", "text": "搞定啦!花了 ¥0.12~ 要不要做成视频?🐱", "media": "/tmp/openclaw/rh-output/cat.jpg" }
    ```
    Step 2 — Then respond with `NO_REPLY` (prevents duplicate message).
    
    **If `message` tool call fails** (error/exception):
    - Retry the `message` tool call once.
    - If still fails → include `OUTPUT_FILE:<path>` in text AND tell user: "文件生成好了但发送遇到问题,我再试一次~"
    
    **NEVER do these**:
    - Print `OUTPUT_FILE:` as first-choice delivery (users see raw text, not a file!)
    - Show `runninghub.cn` URLs (internal, users cannot open)
    - Use `![](...)` markdown images
    - Say "已发送" or "点击下面的附件" without actually calling `message` tool
    
    ## Text Results
    
    Print the text directly to user. Include cost if `COST:` line present.
    
    ## Errors & Retry
    
    | Error | Action |
    |-------|--------|
    | `NO_API_KEY` | Guide key setup → Read `{baseDir}/references/api-key-setup.md` |
    | `AUTH_FAILED` | Key expired → https://www.runninghub.cn/enterprise-api/sharedApi |
    | `INSUFFICIENT_BALANCE` | "余额不够啦~" → https://www.runninghub.cn/vip-rights/4 |
    | `TASK_FAILED` | For video: offer fallback model. For others: show friendly error, offer retry. |
    
    ## General Notes
    
    - Video is slow (1-5 min); script auto-polls up to 20 min.
    - Images < 5MB → base64; larger → upload first.
    - Key order: `--api-key` flag → `RUNNINGHUB_API_KEY` env → config file.
    
  • runninghub/references/video-models.md5.0 KBf615546a395aupstream ↗
    # Video Model Selection
    
    **Whenever** the user wants ANY video (text-to-video OR image-to-video), you MUST show this menu and WAIT:
    
    > 好的!先帮你选个最合适的视频模型~
    >
    > 1. 🚀 **全能视频V3.1 Fast** — 我最推荐的!又快效果又好,性价比之王
    > 2. 🔥 **全能视频X** — Grok 驱动,画面想象力超强,创意天花板
    > 3. 🎯 **可灵 v3.0 Pro** — 运动特别自然,拍人物选它准没错
    > 4. 🎬 **全能视频V3.1 Pro** — 电影感拉满,适合风景大片
    > 5. ✨ **Vidu Q3 Pro** — 风格化独特,适合创意类短片
    > 6. ⭐ **全能视频S** — Sora 同款引擎效果好,但最近模型负载比较高,可能要多等一会儿
    > 7. 🌊 **海螺 Hailuo** — 速度快画面细腻,适合创意类内容
    > 8. 🌱 **超能视频SD2.0** — 效果超赞!最长15秒+自动配音,适合动画/风景,不适合真人,价格偏高
    >
    > 说个数字就行~ 不选的话我默认用 🚀全能视频V3.1 Fast 哦!
    
    **Do NOT invent your own model list. Do NOT skip this menu. Use EXACTLY this 8-model list.**
    
    After user replies, map choice → endpoint:
    
    **Text-to-video** (no image):
    | # | Endpoint |
    |---|----------|
    | 1 (default) | `rhart-video-v3.1-fast/text-to-video` |
    | 2 | `rhart-video-g/text-to-video` |
    | 3 | `kling-v3.0-pro/text-to-video` |
    | 4 | `rhart-video-v3.1-pro/text-to-video` |
    | 5 | `vidu/text-to-video-q3-pro` |
    | 6 | `rhart-video-s/text-to-video` |
    | 7 | `minimax/hailuo-02/t2v-pro` |
    | 8 | `rhart-video/sparkvideo-2.0/text-to-video` |
    
    **Image-to-video** (user has image):
    | # | Endpoint |
    |---|----------|
    | 1 (default) | `rhart-video-v3.1-fast/image-to-video` |
    | 2 | `rhart-video-g/image-to-video` |
    | 3 | `kling-v3.0-pro/image-to-video` |
    | 4 | `rhart-video-v3.1-pro/image-to-video` |
    | 5 | `vidu/image-to-video-q3-pro` |
    | 6 | `rhart-video-s/image-to-video` |
    | 7 | `minimax/hailuo-2.3-fast/image-to-video` |
    | 8 | `rhart-video/sparkvideo-2.0/image-to-video` |
    
    ## Matching Rules
    
    - Number 1-8 → use that model
    - Partial name ("可灵", "海螺", "全能", "万相", "Grok", "Seedance", "超能", "种子") → match
    - "随便" / "你选" / "默认" → choice 1
    - "最快的" / "便宜的" → choice 1
    - "万相" → use `alibaba/wan-2.6/text-to-video` or `alibaba/wan-2.6/image-to-video-flash`
    - "效果最好的" / "创意最好的" → choice 2 (全能X) or 3 (可灵)
    - "最长的" / "15秒" / "长视频" / "自动配音" → recommend choice 8 (超能视频SD2.0)
    - "多模态" / "图片+视频" → use multimodal endpoint: `rhart-video/sparkvideo-2.0/multimodal-video`
    - Real people in image → recommend choice 3 (可灵). **NEVER recommend 8 (超能视频SD2.0) for real people.**
    
    Skip menu ONLY if: user named a specific model, or said "跟上次一样" / "再来一个".
    
    ## After Model Is Chosen
    
    **Before running the script**, ALWAYS send a progress notification via `message` tool:
    > "好嘞,开始用 XX模型 生成视频啦!一般需要几分钟,请稍等~ 🎬"
    
    This is critical — video generation takes 1-5 minutes and users need to know the task has started. Send the notification FIRST, then execute the script.
    
    Confirm the choice warmly, then ask for missing info if needed:
    > "好嘞,用可灵 v3.0 Pro!视频时长要多久?默认 5 秒,也可以选 10 秒~"
    
    Smart defaults (use these if user doesn't specify):
    - Duration: 5s for text-to-video, 5s for image-to-video
    - Aspect ratio: 16:9 (landscape); if user's image is portrait → use 9:16
    
    **超能视频SD2.0 special handling (choice 8):**
    - When user picks 8, warmly mention: "超能视频SD2.0 效果很棒!支持最长 15 秒哦~ 要多长?默认 5 秒"
    - If user's prompt/image involves real people, WARN: "超能视频SD2.0 对真人效果一般,要不要换 🎯可灵 v3.0 Pro?拍人物它最在行!"
    - Extra params: `--param generateAudio=true` (auto-generate audio, on by default), `--param resolution=720p`
    - Duration range: 4-15 seconds (broader than other models)
    - If user wants auto audio off: `--param generateAudio=false`
    
    ## Prompt Optimization
    
    When the user gives a short/vague prompt, ENHANCE it before sending to the API. Example:
    - User says: "甜妹跳舞" → Enhance to: "A sweet young woman dancing gracefully in a neon-lit city street at night, dynamic camera movement, cinematic lighting, MV style, 4K"
    - User says: "猫在花园" → Enhance to: "An orange tabby cat playing in a sunlit garden with colorful flowers, shallow depth of field, warm afternoon light"
    
    Always write prompts in **English** for best model results, even if the user speaks Chinese.
    
    ## Video Failure Retry
    
    If a video model fails (overloaded, timeout, error), do NOT just give up. Tell the user warmly and offer to retry with a different model:
    > "哎呀,全能视频S 那边服务器忙不过来了~ 要不要我换 🚀万相2.6 帮你重新生成?一般不会失败的!"
    
    If the user agrees (or says "好"/"换一个"/"试试"), immediately retry with the suggested model. Default fallback order: 全能视频V3.1 Fast → 可灵 → 海螺.
    
  • runninghub/data/capabilities.json328 KBd59373a18e18upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • runninghub/data/Skills_R_Open_Claw_2.7.zip567 KB519659a6d808upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • README.mdupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

Plain-text copy, no login: /skill-bundles/apizziii-openclaw-rh-skills-runninghub.md

// REPO STATS

1 stars
0 open issues
Last commit: 1mo ago