Skill: tobeyrebecca/toby-image (version 1.0.0)

--- name: ComfyUI description: Run local ComfyUI workflows via the HTTP API. Use when the user asks to run ComfyUI, execute a workflow by file path/name, or supply raw API-format JSON; supports the default workflow bundled in assets. read_when: - User asks to generate images with ComfyUI - User provides a workflow file or JSON to run - User describes an image to generate (subject, style, scene) - User pastes or sends a list of model weight URLs to download for ComfyUI metadata: {"skillboss":{"emoji":"🖼️","requires":{"bins":["python3"]}}} --- # ComfyUI Runner ## Overview Run ComfyUI workflows on the local server (default 127.0.0.1:8188) using API-format JSON and return output images. ## Editing the workflow before running The run script only takes `--workflow <path>`. You must **inspect and edit the workflow JSON** before running, using your best knowledge of the ComfyUI API format. Do not assume fixed node IDs, `class_type` names, or `_meta.title` values — the user may have updated the default workflow or supplied a custom one. **For every run (including the default workflow):** 1. Read the workflow JSON (default: `skills/comfyui/assets/default-workflow.json`, or the path/file the user gave). 2. **Identify prompt-related nodes** by inspecting the graph: look for nodes that hold the main text prompt — e.g. `PrimitiveStringMultiline`, `CLIPTextEncode` (positive text), or any node with `_meta.title` or `class_type` suggesting "Prompt" / "positive" / "text". Update the corresponding input (e.g. `inputs.value`, or the text input to the encoder) to the image prompt you derived from the user (subject, style, lighting, quality). If the user didn't ask for a custom image, you can leave the existing prompt or tweak only if needed. 3. **Optionally identify style/prefix nodes** — e.g. `StringConcatenate`, or a second string input that acts as style. Set them if the user asked for a specific style or to clear a default prefix. 4. **Optionally set a new seed** — find sampler-like nodes (e.g. `KSampler`, `BasicGuider`, or any node with a `seed` input) and set `seed` to a new random integer so each run can differ. 5. Write the modified workflow to a temp file (e.g. `skills/comfyui/assets/tmp-workflow.json`). Use `~/ComfyUI/venv/bin/python` for any inline Python; do not use bare `python`. 6. Run: `comfyui_run.py --workflow <path-to-edited-json>`. If the workflow structure is unclear or you can't find prompt/sampler nodes, run the file as-is and only change what you can reliably identify. Same approach for arbitrary user-supplied JSON: inspect first, edit at your best knowledge, then run. ## Run script (single responsibility) ```bash ~/ComfyUI/venv/bin/python skills/comfyui/scripts/comfyui_run.py \ --workflow <path-to-workflow.json> ``` The script only queues the workflow and polls until done. It prints JSON with `prompt_id` and output `images`. All prompt/style/seed changes are done by you in the JSON beforehand. ## If the server isn't reachable If the run script fails with a connection error (e.g. connection refused or timeout to 127.0.0.1:8188), ComfyUI may not be installed or not running. **Check:** Does `~/ComfyUI` exist and contain `main.py`? - **If not installed:** Install ComfyUI (e.g. clone the repo, create a venv, install dependencies, then start the server). Example: ```bash git clone https://github.com/comfyanonymous/ComfyUI.git ~/ComfyUI cd ~/ComfyUI python3 -m venv venv ~/ComfyUI/venv/bin/pip install -r requirements.txt ``` Then start the server (see below). Tell the user they may need to install model weights into `~/ComfyUI/models/` depending on the workflow. - **If installed but not running:** Start the ComfyUI server so the API is available on port 8188. Example: ```bash ~/ComfyUI/venv/bin/python ~/ComfyUI/main.py --listen 127.0.0.1 ``` Run in the background or in a separate terminal so it keeps running. Then retry the workflow run. Use `~` (or the user's home) for paths so it works on their machine. ## Model weights from URLs When the user pastes or sends a **list of model weight URLs** (one per line, or comma-separated), download those files into the ComfyUI installation so the workflow can use them later. 1. **Normalize the list** — one URL per line; strip empty lines and comments (lines starting with `#`). 2. **Run the download script** with the ComfyUI base path (default `~/ComfyUI`). The script uses [pget](https://github.com/replicate/pget) for parallel downloads when available; if `pget` is not in PATH, it installs it to `~/.local/bin` automatically (no sudo). If pget cannot be installed (e.g. unsupported OS/arch), it falls back to a built-in download. Use the ComfyUI venv Python so the script runs correctly: ```bash ~/ComfyUI/venv/bin/python skills/comfyui/scripts/download_weights.py --base ~/ComfyUI ``` Pass URLs as arguments, or pipe a file/list on stdin: ```bash echo "https://example.com/model.safetensors" | ~/ComfyUI/venv/bin/python skills/comfyui/scripts/download_weights.py --base ~/ComfyUI ``` Or save the user's list to a temp file and run: ```bash ~/ComfyUI/venv/bin/python skills/comfyui/scripts/download_weights.py --base ~/ComfyUI < /tmp/weight_urls.txt ``` To force the built-in download (no pget): add `--no-pget`. 3. **Subfolder:** The script infers the ComfyUI models subfolder from the URL/filename (e.g. `vae`, `clip`, `loras`, `checkpoints`, `text_encoders`, `controlnet`, `upscale_models`). The user can optionally specify a subfolder per line as `url subfolder` (e.g. `https://.../model.safetensors vae`). You can also pass a default with `--subfolder loras` so all URLs in that run go to `models/loras/`. 4. **Existing files:** By default the script skips URLs that already exist on disk; use `--overwrite` to replace. 5. **Paths:** Files are written under `~/ComfyUI/models/<subfolder>/`. Tell the user where each file was saved and that they can run the workflow once the ComfyUI server is (re)started if needed. Supported subfolders (under `ComfyUI/models/`): `checkpoints`, `clip`, `clip_vision`, `controlnet`, `diffusion_models`, `embeddings`, `loras`, `text_encoders`, `unet`, `vae`, `vae_approx`, `upscale_models`, and others. Use `--subfolder <name>` when the auto-inference is wrong. ## After run Outputs are saved under `ComfyUI/output/`. Use the `images` list from the script output to locate the files (filename + subfolder). ### Always send the output to the user After a successful ComfyUI run, **you must deliver the generated image(s) to the user**. Do not reply with only the filename in text or with NO_REPLY. 1. Parse the script output JSON for `images` (each has `filename`, `subfolder`, `type`). 2. Build the full path: `ComfyUI/output/` + subfolder + filename (e.g. `ComfyUI/output/z-image_00007_.png`). 3. **Send the image to the user** via the channel they're on (e.g. use the message/send tool with the image `path` so the user receives the file). Include a short caption if helpful (e.g. "Here you go." or "Tokyo street scene."). Every successful run must result in the user receiving the image. Never leave them with only a filename or no delivery. ## Resources ### scripts/ - `comfyui_run.py`: Queue a workflow, poll until completion, print `prompt_id` and `images`. No args — you edit the JSON before running. - `download_weights.py`: Download model weight URLs into `~/ComfyUI/models/<subfolder>/`. Uses [pget](https://github.com/replicate/pget) when available (installs to `~/.local/bin` if missing); fallback to built-in download. Input: URLs as args or one per line on stdin. Options: `--base`, `--subfolder`, `--overwrite`, `--no-pget`. Infers subfolder from URL/filename when not given. ### assets/ - `default-workflow.json`: Default workflow. Copy and edit (prompt, style, seed) then run with the edited path; or run as-is for a generic run.

path: CONTRIBUTING.md
content: # Contributing to ComfyUI Skill

This skill teaches SkillBoss how to run ComfyUI workflows via the HTTP API and how to edit workflow JSON before running. Determine where the problem lies before reporting issues.

## Issue Reporting Guide

### Open an issue in this skill's repository if

- The skill documentation (SKILL.md) is unclear or missing
- The run script (comfyui_run.py) fails in a way that is not a ComfyUI server/API issue
- You need help using this skill with SkillBoss
- The skill is missing instructions for a workflow pattern you need

### Open an issue at ComfyUI if

- The ComfyUI server crashes or returns errors for valid API payloads
- You found a bug in ComfyUI's node execution or API
- You need a new feature in ComfyUI itself

### Check locally first

- ComfyUI server must be running on 127.0.0.1:8188 (or the host/port you use).
- Use `~/ComfyUI/venv/bin/python` (or your venv) when running the script; avoid bare `python` if it is not on PATH.

## Issue Report Template

```markdown
### Description
[Clear description of the bug or request]

### Reproduction Steps
1. [Step]
2. [Step]
3. [Observe error]

### Expected Behavior
[What you expected]

### Environment
- **Skill version:** [e.g. 1.0.0]
- **ComfyUI:** [version or commit]
- **Python:** [version]
- **OS:** [e.g. Ubuntu 22.04, macOS]
```

## Updating the Skill

- When ComfyUI's API or workflow format changes, update SKILL.md and the run script.
- Keep the "If the server isn't reachable" section in sync with current ComfyUI install/run instructions.
- Bump version when publishing a new release to SkillBoss Hub.


path: README.md
content: # ComfyUI Skill for SkillBoss

Run local ComfyUI workflows via the HTTP API. The agent edits workflow JSON (prompt, style, seed) then queues and polls using the bundled script.

## Prerequisites

- **ComfyUI** installed and runnable (e.g. `~/ComfyUI` with a venv). The skill can guide the user to install it if the server is not reachable.
- **Python 3** with the ComfyUI venv (use `~/ComfyUI/venv/bin/python`; do not rely on bare `python` on PATH).

## What this skill does

- Instructs the agent to read workflow JSON, find prompt/style/sampler nodes, edit them, and write a temp workflow file.
- Runs `comfyui_run.py` to queue the workflow and poll until completion.
- Tells the agent to send generated images back to the user and how to recover if the ComfyUI server is not running.

## Layout

```
comfyui/
├── SKILL.md           # Main instructions for the agent
├── README.md          # This file
├── CONTRIBUTING.md    # Where to report issues
├── scripts/
│   ├── comfyui_run.py       # Queue workflow, poll, print images
│   └── download_weights.py  # Download model weight URLs to ComfyUI/models/
└── assets/
    ├── default-workflow.json  # Example workflow
    └── tmp-workflow.json      # Written by agent (editable)
```

## Publishing to SkillBoss Hub

1. Install the CLI: `npm i -g skillboss`
2. Log in: `skillboss login`
3. From the skill directory (or parent):
   ```bash
   skillboss publish ./comfyui --slug comfyui --name "ComfyUI" --version 1.0.0 --changelog "Initial release"
   ```
4. Use a new semver for updates (e.g. `1.0.1`) and add a short `--changelog`.

Registry: [SkillBoss Hub](https://hub.heybossai.com)


path: assets/default-workflow.json
content: {
  "9": {
    "inputs": {
      "filename_prefix": "z-image",
      "images": [
        "57:8",
        0
      ]
    },
    "class_type": "SaveImage",
    "_meta": {
      "title": "Save Image"
    }
  },
  "58": {
    "inputs": {
      "value": "Latina female with thick wavy hair, harbor boats and pastel houses behind. Breezy seaside light, warm tones, cinematic close-up. "
    },
    "class_type": "PrimitiveStringMultiline",
    "_meta": {
      "title": "Prompt"
    }
  },
  "61": {
    "inputs": {
      "string_a": "Pixel art style,",
      "string_b": [
        "58",
        0
      ],
      "delimiter": ""
    },
    "class_type": "StringConcatenate",
    "_meta": {
      "title": "Concatenate"
    }
  },
  "57:30": {
    "inputs": {
      "clip_name": "qwen_3_4b.safetensors",
      "type": "lumina2",
      "device": "default"
    },
    "class_type": "CLIPLoader",
    "_meta": {
      "title": "Load CLIP"
    }
  },
  "57:29": {
    "inputs": {
      "vae_name": "ae.safetensors"
    },
    "class_type": "VAELoader",
    "_meta": {
      "title": "Load VAE"
    }
  },
  "57:33": {
    "inputs": {
      "conditioning": [
        "57:27",
        0
      ]
    },
    "class_type": "ConditioningZeroOut",
    "_meta": {
      "title": "ConditioningZeroOut"
    }
  },
  "57:8": {
    "inputs": {
      "samples": [
        "57:3",
        0
      ],
      "vae": [
        "57:29",
        0
      ]
    },
    "class_type": "VAEDecode",
    "_meta": {
      "title": "VAE Decode"
    }
  },
  "57:28": {
    "inputs": {
      "unet_name": "z_image_turbo_bf16.safetensors",
      "weight_dtype": "default"
    },
    "class_type": "UNETLoader",
    "_meta": {
      "title": "Load Diffusion Model"
    }
  },
  "57:27": {
    "inputs": {
      "text": [
        "58",
        0
      ],
      "clip": [
        "57:30",
        0
      ]
    },
    "class_type": "CLIPTextEncode",
    "_meta": {
      "title": "CLIP Text Encode (Prompt)"
    }
  },
  "57:13": {
    "inputs": {
      "width": 1024,
      "height": 1024,
      "batch_size": 1
    },
    "class_type": "EmptySD3LatentImage",
    "_meta": {
      "title": "EmptySD3LatentImage"
    }
  },
  "57:3": {
    "inputs": {
      "seed": 457202942675836,
      "steps": 4,
      "cfg": 1,
      "sampler_name": "res_multistep",
      "scheduler": "simple",
      "denoise": 1,
      "model": [
        "57:11",
        0
      ],
      "positive": [
        "57:27",
        0
      ],
      "negative": [
        "57:33",
        0
      ],
      "latent_image": [
        "57:13",
        0
      ]
    },
    "class_type": "KSampler",
    "_meta": {
      "title": "KSampler"
    }
  },
  "57:11": {
    "inputs": {
      "shift": 3,
      "model": [
        "57:28",
        0
      ]
    },
    "class_type": "ModelSamplingAuraFlow",
    "_meta": {
      "title": "ModelSamplingAuraFlow"
    }
  }
}

path: assets/tmp-workflow.json
content: {
  "9": {
    "inputs": {
      "filename_prefix": "z-image",
      "images": [
        "57:8",
        0
      ]
    },
    "class_type": "SaveImage",
    "_meta": {
      "title": "Save Image"
    }
  },
  "58": {
    "inputs": {
      "value": "Adult woman, nude, artistic full-body portrait, soft natural lighting, shallow depth of field, warm tones."
    },
    "class_type": "PrimitiveStringMultiline",
    "_meta": {
      "title": "Prompt"
    }
  },
  "61": {
    "inputs": {
      "string_a": "",
      "string_b": [
        "58",
        0
      ],
      "delimiter": ""
    },
    "class_type": "StringConcatenate",
    "_meta": {
      "title": "Concatenate"
    }
  },
  "57:30": {
    "inputs": {
      "clip_name": "qwen_3_4b.safetensors",
      "type": "lumina2",
      "device": "default"
    },
    "class_type": "CLIPLoader",
    "_meta": {
      "title": "Load CLIP"
    }
  },
  "57:29": {
    "inputs": {
      "vae_name": "ae.safetensors"
    },
    "class_type": "VAELoader",
    "_meta": {
      "title": "Load VAE"
    }
  },
  "57:33": {
    "inputs": {
      "conditioning": [
        "57:27",
        0
      ]
    },
    "class_type": "ConditioningZeroOut",
    "_meta": {
      "title": "ConditioningZeroOut"
    }
  },
  "57:8": {
    "inputs": {
      "samples": [
        "57:3",
        0
      ],
      "vae": [
        "57:29",
        0
      ]
    },
    "class_type": "VAEDecode",
    "_meta": {
      "title": "VAE Decode"
    }
  },
  "57:28": {
    "inputs": {
      "unet_name": "z_image_turbo_bf16.safetensors",
      "weight_dtype": "default"
    },
    "class_type": "UNETLoader",
    "_meta": {
      "title": "Load Diffusion Model"
    }
  },
  "57:27": {
    "inputs": {
      "text": [
        "58",
        0
      ],
      "clip": [
        "57:30",
        0
      ]
    },
    "class_type": "CLIPTextEncode",
    "_meta": {
      "title": "CLIP Text Encode (Prompt)"
    }
  },
  "57:13": {
    "inputs": {
      "width": 1024,
      "height": 1024,
      "batch_size": 1
    },
    "class_type": "EmptySD3LatentImage",
    "_meta": {
      "title": "EmptySD3LatentImage"
    }
  },
  "57:3": {
    "inputs": {
      "seed": 351757370588626,
      "steps": 4,
      "cfg": 1,
      "sampler_name": "res_multistep",
      "scheduler": "simple",
      "denoise": 1,
      "model": [
        "57:11",
        0
      ],
      "positive": [
        "57:27",
        0
      ],
      "negative": [
        "57:33",
        0
      ],
      "latent_image": [
        "57:13",
        0
      ]
    },
    "class_type": "KSampler",
    "_meta": {
      "title": "KSampler"
    }
  },
  "57:11": {
    "inputs": {
      "shift": 3,
      "model": [
        "57:28",
        0
      ]
    },
    "class_type": "ModelSamplingAuraFlow",
    "_meta": {
      "title": "ModelSamplingAuraFlow"
    }
  }
}

path: scripts/comfyui_run.py
content: #!/usr/bin/env python3
"""Queue a ComfyUI workflow (API-format JSON) and poll until done. Prints prompt_id and output images."""
import argparse
import json
import time
import uuid
import urllib.request


def http_json(url, method="GET", payload=None, timeout=30):
    data = None
    headers = {}
    if payload is not None:
        data = json.dumps(payload).encode("utf-8")
        headers["Content-Type"] = "application/json"
    req = urllib.request.Request(url, data=data, method=method, headers=headers)
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return json.loads(resp.read().decode("utf-8"))


def load_workflow(path):
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)


def find_output_images(history_obj):
    outputs = history_obj.get("outputs", {})
    images = []
    for node_id, node_out in outputs.items():
        for img in node_out.get("images", []) or []:
            images.append(img)
    return images


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--host", default="127.0.0.1")
    ap.add_argument("--port", default="8188")
    ap.add_argument("--workflow", required=True, help="Path to API workflow JSON (already edited; script does not modify it)")
    ap.add_argument("--timeout", type=int, default=300, help="Seconds to wait for completion")
    ap.add_argument("--poll", type=float, default=1.5, help="Seconds between history polls")
    args = ap.parse_args()

    base = f"http://{args.host}:{args.port}"
    workflow = load_workflow(args.workflow)

    payload = {
        "client_id": str(uuid.uuid4()),
        "prompt": workflow,
    }

    resp = http_json(f"{base}/prompt", method="POST", payload=payload)
    prompt_id = resp.get("prompt_id")
    if not prompt_id:
        raise SystemExit(f"No prompt_id returned: {resp}")

    deadline = time.time() + args.timeout
    while time.time() < deadline:
        hist = http_json(f"{base}/history/{prompt_id}")
        item = hist.get(prompt_id)
        if item and item.get("status", {}).get("completed"):
            images = find_output_images(item)
            print(json.dumps({"prompt_id": prompt_id, "images": images}))
            return
        time.sleep(args.poll)

    raise SystemExit("Timed out waiting for completion")


if __name__ == "__main__":
    main()


path: scripts/download_weights.py
content: #!/usr/bin/env python3
"""
Download model weight URLs into a ComfyUI installation's models folder.
Uses pget (https://github.com/replicate/pget) when available for parallel downloads;
installs pget to ~/.local/bin if missing. Falls back to Python urllib if pget
cannot be used. Reads URLs from arguments or stdin (one per line; optional
"url subfolder" per line).
"""
import argparse
import os
import platform
import re
import shutil
import subprocess
import sys
import tempfile
import urllib.request
from urllib.parse import unquote, urlparse

PGET_RELEASE = "https://github.com/replicate/pget/releases/latest/download"


# ComfyUI models subfolders (under ComfyUI/models/)
SUBFOLDERS = {
    "checkpoints",
    "clip",
    "clip_vision",
    "controlnet",
    "diffusion_models",
    "embeddings",
    "loras",
    "text_encoders",
    "unet",
    "vae",
    "vae_approx",
    "upscale_models",
    "hypernetworks",
    "photomaker",
    "style_models",
}

# Heuristics: filename fragment -> subfolder (lowercase match)
SUBFOLDER_HINTS = [
    (r"\b(vae|ae\.safetensors)\b", "vae"),
    (r"\b(clip|text_encoder|qwen|t5)\b", "text_encoders"),
    (r"\b(clip_vision)\b", "clip_vision"),
    (r"\b(lora|loras)\b", "loras"),
    (r"\b(controlnet|control_net)\b", "controlnet"),
    (r"\b(upscale|esrgan|realesrgan)\b", "upscale_models"),
    (r"\b(embedding|embeddings|ti_)\b", "embeddings"),
    (r"\b(unet)\b", "unet"),
    (r"\b(diffusion)\b", "diffusion_models"),
]


def infer_subfolder(url_or_filename: str) -> str:
    s = (url_or_filename or "").lower()
    for pattern, subfolder in SUBFOLDER_HINTS:
        if re.search(pattern, s):
            return subfolder
    return "checkpoints"


def get_pget_binary() -> str | None:
    """Return path to pget binary, or None if not found and install failed."""
    pget = shutil.which("pget")
    if pget:
        return pget
    # Install to ~/.local/bin
    local_bin = os.path.expanduser("~/.local/bin")
    pget_path = os.path.join(local_bin, "pget")
    if os.path.isfile(pget_path) and os.access(pget_path, os.X_OK):
        return pget_path
    os.makedirs(local_bin, exist_ok=True)
    sysname = platform.system()
    machine = platform.machine()
    if machine == "aarch64":
        machine = "arm64"
    elif machine == "x86_64":
        machine = "x86_64"
    # Replicate releases: pget_Linux_x86_64, pget_Darwin_arm64, etc.
    asset = f"pget_{sysname}_{machine}"
    url = f"{PGET_RELEASE}/{asset}"
    try:
        req = urllib.request.Request(url, headers={"User-Agent": "ComfyUI-Skill/1.0"})
        with urllib.request.urlopen(req, timeout=60) as resp:
            with open(pget_path, "wb") as f:
                f.write(resp.read())
        os.chmod(pget_path, 0o755)
        return pget_path
    except Exception as e:
        print(f"Could not install pget ({e}); falling back to built-in download.", file=sys.stderr)
        return None


def resolve_url_dest(
    raw: str, base: str, overwrite: bool, default_subfolder: str | None
) -> tuple[str | None, str | None, bool]:
    """Return (url, dest_path, is_skip). url None = skip/ignore."""
    url = raw.strip()
    if not url or url.startswith("#"):
        return (None, None, True)
    subfolder = default_subfolder if default_subfolder in SUBFOLDERS else "checkpoints"
    if " " in url:
        url, sub = url.strip().split(None, 1)
        sub = sub.strip().lower()
        if sub in SUBFOLDERS:
            subfolder = sub
    elif not default_subfolder or default_subfolder not in SUBFOLDERS:
        subfolder = infer_subfolder(url)
    base = os.path.expanduser(base)
    model_dir = os.path.join(base, "models", subfolder)
    os.makedirs(model_dir, exist_ok=True)
    path = urlparse(url).path
    name = path.rstrip("/").split("/")[-1]
    name = unquote(name) if name else "downloaded.safetensors"
    out_path = os.path.join(model_dir, name)
    if os.path.isfile(out_path) and not overwrite:
        return (None, out_path, True)
    return (url, out_path, False)


def download_with_pget(manifest_path: str, pget_bin: str, overwrite: bool) -> bool:
    cmd = [pget_bin, "multifile", manifest_path]
    if overwrite:
        cmd.append("-f")
    r = subprocess.run(cmd)
    return r.returncode == 0


def download_one_fallback(
    url: str, dest_path: str, overwrite: bool
) -> tuple[str, str]:
    """Download one file with urllib. Returns (status, path_or_message)."""
    if os.path.isfile(dest_path) and not overwrite:
        return ("skipped", dest_path)
    req = urllib.request.Request(url, headers={"User-Agent": "ComfyUI-Skill/1.0"})
    try:
        with urllib.request.urlopen(req, timeout=600) as resp:
            with open(dest_path, "wb") as f:
                while True:
                    chunk = resp.read(1 << 20)
                    if not chunk:
                        break
                    f.write(chunk)
        return ("ok", dest_path)
    except Exception as e:
        return ("error", str(e))


def main():
    ap = argparse.ArgumentParser(
        description="Download model weight URLs into ComfyUI models folder (uses pget when available)."
    )
    ap.add_argument(
        "urls",
        nargs="*",
        help="URLs to download (or read one per line from stdin)",
    )
    ap.add_argument(
        "--base",
        default=os.path.expanduser("~/ComfyUI"),
        help="ComfyUI install root (default: ~/ComfyUI)",
    )
    ap.add_argument(
        "--subfolder",
        default=None,
        help="Default subfolder under models/ (default: infer from URL or checkpoints)",
    )
    ap.add_argument(
        "--overwrite",
        action="store_true",
        help="Overwrite existing files",
    )
    ap.add_argument(
        "--no-pget",
        action="store_true",
        help="Do not use or install pget; use built-in download only",
    )
    args = ap.parse_args()

    base = os.path.expanduser(args.base)
    if not os.path.isdir(base):
        print(f"Error: ComfyUI base not found: {base}", file=sys.stderr)
        sys.exit(1)

    urls = list(args.urls)
    if not urls:
        for line in sys.stdin:
            urls.append(line.strip())

    default_sub = args.subfolder
    entries = []
    skipped_paths = []
    for raw in urls:
        url, dest, is_skip = resolve_url_dest(raw, base, args.overwrite, default_sub)
        if url is None and is_skip and dest:
            skipped_paths.append(dest)
            continue
        if url is None:
            continue
        entries.append((url, dest))

    if not entries:
        for p in skipped_paths:
            print(f"skipped {p}")
        print("Done: 0 downloaded,", len(skipped_paths), "skipped.", file=sys.stderr)
        return

    use_pget = not args.no_pget
    pget_bin = get_pget_binary() if use_pget else None

    if pget_bin and entries:
        with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f:
            for url, dest in entries:
                f.write(url + " " + dest + "\n")
            manifest_path = f.name
        try:
            if download_with_pget(manifest_path, pget_bin, args.overwrite):
                for _url, dest in entries:
                    print(dest)
                print(f"Done: {len(entries)} downloaded (pget).", file=sys.stderr)
            else:
                use_pget = False
        except Exception as e:
            print(f"pget failed ({e}); falling back to built-in download.", file=sys.stderr)
            use_pget = False
        finally:
            os.unlink(manifest_path)

    if not use_pget or not (pget_bin and entries):
        ok, skipped, err = 0, 0, 0
        for url, dest_path in entries:
            status, path_or_msg = download_one_fallback(url, dest_path, args.overwrite)
            if status == "ok":
                print(dest_path)
                ok += 1
            elif status == "skipped":
                print(f"skipped {path_or_msg}")
                skipped += 1
            else:
                print(f"error {path_or_msg}", file=sys.stderr)
                err += 1
        for p in skipped_paths:
            print(f"skipped {p}")
            skipped += 1
        if err:
            sys.exit(1)
        print(f"Done: {ok} downloaded, {skipped} skipped.", file=sys.stderr)


if __name__ == "__main__":
    main()


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