diff --git a/.github/workflows/docs-search.yml b/.github/workflows/docs-search.yml new file mode 100644 index 000000000..1929aaab6 --- /dev/null +++ b/.github/workflows/docs-search.yml @@ -0,0 +1,64 @@ +name: Test optional LanceDB documentation search + +on: + pull_request: + paths: + - "comfy_cli/docs/**" + - "comfy_cli/command/docs.py" + - "comfy_cli/schemas/docs.json" + - "comfy_cli/docs/search/**" + - "packages/comfy-cli-docs-search/**" + - "scripts/build_docs_lancedb.py" + - "scripts/set_release_version.py" + - "tests/comfy_cli/test_docs*.py" + - "docs/search-sources.json" + - "pyproject.toml" + - "uv.lock" + - ".github/workflows/docs-search.yml" + push: + branches: [main] + paths: + - "comfy_cli/docs/**" + - "comfy_cli/command/docs.py" + - "comfy_cli/schemas/docs.json" + - "packages/comfy-cli-docs-search/**" + - "scripts/build_docs_lancedb.py" + - "scripts/set_release_version.py" + - "tests/comfy_cli/test_docs*.py" + - "docs/search-sources.json" + - "pyproject.toml" + - "uv.lock" + - ".github/workflows/docs-search.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + docs-search: + env: + PYTHONUTF8: "1" + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v7 + + - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + python-version: '3.10' + + - name: Install optional search dependencies + run: uv sync --extra dev --extra docs-search --locked + + - name: Build the pinned offline pack + run: uv run --locked --extra dev --extra docs-search python scripts/build_docs_lancedb.py + + - name: Check the generated pack + run: uv run --locked --extra dev --extra docs-search python scripts/build_docs_lancedb.py --check + + - name: Test lexical, semantic, and hybrid retrieval + run: uv run --locked --extra dev --extra docs-search pytest tests/comfy_cli/test_docs.py tests/comfy_cli/test_docs_lancedb.py tests/comfy_cli/command/test_docs_cli.py tests/comfy_cli/output/test_discovery.py tests/comfy_cli/output/test_envelope_schemas.py -q diff --git a/.github/workflows/publish_package.yml b/.github/workflows/publish_package.yml index 55b535f45..40547b062 100644 --- a/.github/workflows/publish_package.yml +++ b/.github/workflows/publish_package.yml @@ -21,8 +21,10 @@ jobs: with: python-version: '3.12' - - name: Install build and tomlkit dependencies - run: python -m pip install --upgrade pip build tomlkit + - name: Install build and LanceDB pack dependencies + run: >- + python -m pip install --upgrade pip build tomlkit jsonschema + "lancedb==0.25.0" "pyarrow>=16,<25" "onnxruntime>=1.23.2,<1.24" "tokenizers>=0.15,<1" - name: Extract version from tag id: get_version @@ -31,18 +33,21 @@ jobs: VERSION="${VERSION#v}" echo "VERSION=${VERSION}" >> $GITHUB_ENV - - name: Update version in pyproject.toml + - name: Set matching CLI and docs-pack versions + run: python scripts/set_release_version.py "${VERSION}" + + - name: Check bundled documentation + run: python scripts/build_docs_bundle.py --check + + - name: Build and validate offline LanceDB docs pack run: | - python -c " - import tomlkit - with open('pyproject.toml', 'r') as f: - content = tomlkit.load(f) - content['project']['version'] = '${{ env.VERSION }}' - with open('pyproject.toml', 'w') as f: - tomlkit.dump(content, f) - " - - - name: Build distribution + python scripts/build_docs_lancedb.py + python scripts/build_docs_lancedb.py --check + + - name: Build the version-matched docs-search package + run: python -m build --sdist --wheel --outdir dist/ packages/comfy-cli-docs-search + + - name: Build comfy-cli distribution run: python -m build --sdist --wheel --outdir dist/ # - name: Publish distribution to TestPyPI for Validation @@ -94,3 +99,37 @@ jobs: - name: Test Comfy CLI Help run: comfy --help + + test-docs-search-installation: + name: Test optional LanceDB docs search from PyPI + needs: build-n-publish-pypi + runs-on: ubuntu-latest + steps: + - name: Set up Python + uses: actions/setup-python@v7 + with: + python-version: '3.11' + + - name: Extract version from tag + id: get_version + run: | + VERSION="${GITHUB_REF#refs/tags/}" + VERSION="${VERSION#v}" + echo "VERSION=${VERSION}" >> $GITHUB_ENV + + - name: Install optional docs-search extra + run: | + for attempt in 1 2 3 4 5 6 7 8; do + if pip install --no-cache-dir "comfy-cli[docs-search]==${VERSION}"; then + exit 0 + fi + echo "Attempt ${attempt}: package not yet available on PyPI, waiting 15s..." + sleep 15 + done + echo "::error::Failed to install comfy-cli[docs-search]==${VERSION} after 8 attempts" + exit 1 + + - name: Search the shipped corpus offline + run: | + comfy --json docs status + comfy --json docs search "stuck job wait timeout" --mode hybrid diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml index 6ad414445..7b9fe4e81 100644 --- a/.github/workflows/pytest.yml +++ b/.github/workflows/pytest.yml @@ -31,6 +31,9 @@ jobs: - name: Install dependencies run: uv sync --extra dev --locked + - name: Check bundled documentation + run: uv run python scripts/build_docs_bundle.py --check + - name: Run tests env: PYTHONPATH: ${{ github.workspace }} diff --git a/.gitignore b/.gitignore index 1e542ddf7..63f13f9d2 100644 --- a/.gitignore +++ b/.gitignore @@ -51,6 +51,8 @@ sdist/ var/ wheels/ pip-wheel-metadata/ +packages/comfy-cli-docs-search/src/comfy_cli_docs_search/assets/docs-search-pack.tar.gz +packages/comfy-cli-docs-search/src/comfy_cli_docs_search/assets/manifest.json share/python-wheels/ *.egg-info/ .installed.cfg @@ -76,4 +78,3 @@ requirements.compiled override.txt .coverage coverage.xml - diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a9d22bf34..231857115 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -241,6 +241,38 @@ scope in the command module, or import them inside the command function. `tests/comfy_cli/test_import_budget.py` fails if `comfy --version` starts importing them. +### Updating searchable agent documentation + +`comfy docs` indexes a curated allowlist of README sections, `docs/json-output.md`, +and the shipped agent skill files. When changing an included source, rebuild the +checked-in corpus and verify it is current: + +```bash +python scripts/build_docs_bundle.py +python scripts/build_docs_bundle.py --check +``` + +Add or remove sources in `docs/search-sources.json`; the generator fails when a +selected README heading is missing. Keep generated IDs, excerpts, and content +derived from the Markdown rather than maintaining a second copy. + +The optional LanceDB pack stores chunks and precomputed vectors alongside the +pinned BGE query encoder. Test the hybrid path from an isolated environment +with the extra enabled: + +```bash +uv sync --locked --extra dev --extra docs-search +python scripts/build_docs_lancedb.py # fetches the pinned model for local pack creation +python scripts/build_docs_lancedb.py --check +uv run --locked --extra dev --extra docs-search pytest tests/comfy_cli/test_docs_lancedb.py +``` + +The build downloads the pinned ONNX model once and creates ignored pack assets; +search then runs from those local files. Release automation builds the same +archive from the pinned source revision, validates it against the current corpus, +and publishes the version-matched companion package with comfy-cli. PyPI must +trust the release workflow for both project names before the next release. + ## Important notes - Use `typer` for all command args management diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 000000000..944e23b05 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,9 @@ +include docs/search-sources.json +include docs/json-output.md +include scripts/build_docs_bundle.py +include scripts/build_docs_lancedb.py +include scripts/set_release_version.py +include packages/comfy-cli-docs-search/pyproject.toml +include packages/comfy-cli-docs-search/README.md +include packages/comfy-cli-docs-search/MODEL-LICENSE.txt +recursive-include packages/comfy-cli-docs-search/src *.py *.typed diff --git a/README.md b/README.md index 29435571d..d00f1984d 100644 --- a/README.md +++ b/README.md @@ -665,6 +665,28 @@ Enrichment only ever reads the cache, so no command waits on a fetch. The cache refreshes during `comfy skills install` and in the background during `comfy launch`, or on demand with `comfy knowledge status --refresh`. +## Searching the CLI docs + +Search the CLI guides and installed agent guides locally. BM25 works with the +base CLI. The optional extra adds a version-matched LanceDB pack and local +query encoder for offline semantic and hybrid search: + +```bash +pip install 'comfy-cli[docs-search]' # optional; includes the version-matched offline pack +comfy --json docs status +comfy --json docs search "workflow hangs on a cloud timeout" --mode hybrid +comfy --json docs show "SECTION_ID" +``` + +`docs status` reports which modes this install can use. Search results include +a section ID, source location, and a short excerpt. Pass the ID to `docs show` +to read the full section; use `--max-chars` and `--offset` to page through a +long section. The docs command needs no ComfyUI workspace, and queries never +download a model. Results describe this comfy-cli release. Without the optional +pack, `--mode auto` uses BM25 and reports why semantic search is unavailable. +Agents can search each part of a larger question, read the relevant sections, +and reformulate a missed search once with a comfy command or flag. + ## Analytics Analytics are **opt-in and off by default**. The first time you run the CLI in an diff --git a/comfy_cli/cmdline.py b/comfy_cli/cmdline.py index dc8bf06f6..895daa6f9 100644 --- a/comfy_cli/cmdline.py +++ b/comfy_cli/cmdline.py @@ -357,7 +357,7 @@ def _maybe_nudge_setup(ctx: typer.Context, renderer) -> None: # can be closed independently of stdout (`comfy install 2>&-`, where CPython # sets `sys.stderr = None`). A bare `.isatty()` there would kill the command # from the onboarding nudge of all places. See `caller.stream_is_tty`. - if sub in (None, "setup") or not renderer.is_pretty() or not stream_is_tty(getattr(sys, "stderr", None)): + if sub in (None, "setup", "docs") or not renderer.is_pretty() or not stream_is_tty(getattr(sys, "stderr", None)): return try: from comfy_cli.credentials import get_session @@ -523,12 +523,16 @@ def entry( rprint(cli_version) ctx.exit(0) - workspace_manager.setup_workspace_manager(workspace, here, recent, skip_prompt) + # Documentation lookup is self-contained: it must work from any directory + # without resolving or prompting for a ComfyUI workspace. + docs_command = ctx.invoked_subcommand == "docs" + if not docs_command: + workspace_manager.setup_workspace_manager(workspace, here, recent, skip_prompt) # `comfy setup` owns the telemetry consent decision as a branded wizard step # (with full disclosure). Suppress the bare global prompt for that one command # so the user is asked exactly once, in the right place — not pre-empted here. - if ctx.invoked_subcommand != "setup": + if ctx.invoked_subcommand not in {"setup", "docs"}: tracking.prompt_tracking_consent(skip_prompt, default_value=enable_telemetry) _maybe_nudge_setup(ctx, renderer) @@ -2253,6 +2257,7 @@ def standalone( "comfy_cli.command.knowledge", help="Inspect the curated model-knowledge bundle: status, resolve an alias, ranked picks per capability.", ), + "docs": LazySubcommand("comfy_cli.command.docs", help="Search and read the documentation bundled with comfy-cli."), "workflow": LazySubcommand( "comfy_cli.command.workflow", help="Slot-based editing of frontend-format ComfyUI workflows." ), diff --git a/comfy_cli/command/docs.py b/comfy_cli/command/docs.py new file mode 100644 index 000000000..509a73a8a --- /dev/null +++ b/comfy_cli/command/docs.py @@ -0,0 +1,131 @@ +"""Search and read documentation shipped with comfy-cli.""" + +from __future__ import annotations + +from typing import Annotated + +import typer +from rich.text import Text + +from comfy_cli import docs as docs_index +from comfy_cli.docs import DocsSearchPackError, DocsUnavailableError +from comfy_cli.output import get_renderer + +app = typer.Typer(no_args_is_help=True, help="Search documentation shipped with comfy-cli.") + + +def _load_failure(renderer) -> None: + renderer.error( + code="docs_unavailable", + message="the documentation shipped with comfy-cli could not be loaded", + hint="reinstall comfy-cli to restore its documentation bundle", + ) + raise typer.Exit(code=1) + + +def _pack_failure(renderer, error: DocsSearchPackError) -> None: + if error.code == "docs_search_unavailable": + renderer.error(code="docs_search_unavailable", message=str(error), hint=error.hint) + else: + renderer.error(code="docs_pack_incompatible", message=str(error), hint=error.hint) + raise typer.Exit(code=1) + + +@app.command("search", help="Search bundled CLI and agent documentation.") +def search_cmd( + query: Annotated[str, typer.Argument(help="Words, command names, or flags to search for.")], + limit: Annotated[ + int, + typer.Option("--limit", min=1, max=docs_index.MAX_RESULTS, help="Maximum number of sections to return."), + ] = docs_index.DEFAULT_RESULTS, + mode: Annotated[ + str, + typer.Option("--mode", help="Retrieval mode: auto, bm25, semantic, or hybrid."), + ] = "auto", +) -> None: + """Find relevant sections with local BM25 or optional LanceDB semantic search.""" + renderer = get_renderer() + try: + payload = docs_index.search(query, limit=limit, mode=mode.casefold()) + except DocsUnavailableError: + _load_failure(renderer) + except DocsSearchPackError as error: + _pack_failure(renderer, error) + except ValueError as error: + raise typer.BadParameter(str(error), param_hint="query") from error + + if renderer.is_pretty(): + if payload["zero_hit"]: + renderer.print(Text("No documentation matched.", style="yellow")) + renderer.print(Text(payload["hint"], style="dim")) + else: + for result in payload["results"]: + heading = " › ".join(result["headings"]) + renderer.print(Text(f"{result['id']} {heading}", style="bold cyan")) + renderer.print(Text(f" {result['source']}:{result['source_line']}")) + if result["excerpt"]: + renderer.print(Text(f" {result['excerpt']}")) + renderer.emit(payload, command="docs search") + + +@app.command("status", help="Show the documentation corpus and available retrieval modes.") +def status_cmd() -> None: + """Report local docs pack compatibility without loading the model.""" + renderer = get_renderer() + try: + payload = docs_index.status() + except DocsUnavailableError: + _load_failure(renderer) + + if renderer.is_pretty(): + renderer.print(Text(f"Corpus: {payload['corpus_hash']}", style="bold")) + renderer.print(Text(f"Search modes: {', '.join(payload['available_modes'])}")) + if payload["pack_installed"]: + renderer.print(Text(f"Search pack: {payload['pack_version']} (compatible={payload['pack_compatible']})")) + if payload["model"]: + renderer.print(Text(f"Model: {payload['model']}")) + else: + renderer.print(Text("Search pack: not installed")) + if payload["unavailable_reason"]: + renderer.print(Text(payload["unavailable_reason"], style="yellow")) + renderer.print(Text(payload["hint"], style="dim")) + renderer.emit(payload, command="docs status") + + +@app.command("show", help="Read a documentation section returned by `docs search`.") +def show_cmd( + section_id: Annotated[str, typer.Argument(help="Section ID returned by `comfy docs search`.")], + max_chars: Annotated[ + int, + typer.Option( + "--max-chars", + min=1, + max=docs_index.MAX_SECTION_CHARS, + help="Maximum content characters to return.", + ), + ] = docs_index.DEFAULT_SECTION_CHARS, + offset: Annotated[int, typer.Option("--offset", min=0, help="Zero-based character offset for long sections.")] = 0, +) -> None: + """Print the complete section or one bounded page of a long section.""" + renderer = get_renderer() + try: + payload = docs_index.show(section_id, max_chars=max_chars, offset=offset) + except DocsUnavailableError: + _load_failure(renderer) + except ValueError as error: + raise typer.BadParameter(str(error), param_hint="--offset") from error + if payload is None: + renderer.error( + code="docs_not_found", + message=f"documentation section {section_id!r} was not found", + hint="search for the topic again with `comfy docs search`", + ) + raise typer.Exit(code=1) + + if renderer.is_pretty(): + renderer.print(Text(" › ".join(payload["headings"]), style="bold cyan")) + renderer.print(Text(f"{payload['source']}:{payload['source_line']}")) + renderer.print(Text(payload["content"])) + if payload["truncated"]: + renderer.print(Text(f"Continue with --offset {payload['next_offset']}", style="dim")) + renderer.emit(payload, command="docs show") diff --git a/comfy_cli/discovery.py b/comfy_cli/discovery.py index 9992e4372..7b8d94c00 100644 --- a/comfy_cli/discovery.py +++ b/comfy_cli/discovery.py @@ -26,6 +26,9 @@ "comfy which": "which", "comfy run": "run", "comfy discover": "discover", + "comfy docs search": "docs", + "comfy docs status": "docs", + "comfy docs show": "docs", "comfy auth list": "auth", "comfy auth set": "auth", "comfy auth remove": "auth", diff --git a/comfy_cli/docs/__init__.py b/comfy_cli/docs/__init__.py new file mode 100644 index 000000000..4e63479ff --- /dev/null +++ b/comfy_cli/docs/__init__.py @@ -0,0 +1,308 @@ +"""Read and search the documentation shipped with comfy-cli.""" + +from __future__ import annotations + +import hashlib +import json +import re +import sqlite3 +from collections.abc import Sequence +from importlib import resources +from typing import Any + +CORPUS_SCHEMA_VERSION = 1 +MAX_QUERY_CHARS = 500 +MAX_RESULTS = 20 +DEFAULT_RESULTS = 5 +MAX_EXCERPT_CHARS = 800 +DEFAULT_SECTION_CHARS = 12_000 +MAX_SECTION_CHARS = 50_000 +_TOKEN_RE = re.compile(r"[^\W_]+", re.UNICODE) +_STOP_WORDS = frozenset("a an and are as at be by for from how i in is it not of on or the to with".split()) + + +class DocsUnavailableError(Exception): + """The installed documentation corpus is absent or malformed.""" + + +class DocsSearchPackError(Exception): + """The optional LanceDB search pack is missing or incompatible.""" + + def __init__(self, code: str, message: str, hint: str) -> None: + super().__init__(message) + self.code = code + self.hint = hint + + +def _canonical_sections(sections: list[dict[str, Any]]) -> bytes: + return json.dumps(sections, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + + +def load_corpus() -> tuple[list[dict[str, Any]], str]: + """Read and validate the packaged corpus without touching the network.""" + try: + raw = (resources.files("comfy_cli.docs") / "data" / "corpus.json").read_text(encoding="utf-8") + corpus = json.loads(raw) + sections = corpus["sections"] + content_hash = corpus["content_hash"] + if corpus.get("schema_version") != CORPUS_SCHEMA_VERSION or not isinstance(sections, list): + raise ValueError("unsupported docs corpus schema") + if not isinstance(content_hash, str) or not re.fullmatch(r"[0-9a-f]{64}", content_hash): + raise ValueError("invalid docs corpus hash") + ids: set[str] = set() + for section in sections: + if not isinstance(section, dict) or not all( + isinstance(section.get(key), expected) + for key, expected in ( + ("id", str), + ("title", str), + ("headings", list), + ("source", str), + ("source_line", int), + ("content", str), + ) + ): + raise ValueError("invalid docs section") + if section["id"] in ids or not all(isinstance(heading, str) for heading in section["headings"]): + raise ValueError("duplicate or malformed docs section") + ids.add(section["id"]) + if not sections: + raise ValueError("docs corpus is empty") + if hashlib.sha256(_canonical_sections(sections)).hexdigest() != content_hash: + raise ValueError("docs corpus hash does not match its content") + except (OSError, ValueError, TypeError, KeyError, json.JSONDecodeError) as error: + raise DocsUnavailableError("the installed documentation corpus is missing or invalid") from error + return sections, content_hash + + +def query_terms(query: str) -> list[str]: + """Extract plain text search terms, dropping common grammatical filler.""" + return [term for term in _TOKEN_RE.findall(query.casefold()) if term not in _STOP_WORDS] + + +def _quote_fts_terms(terms: Sequence[str]) -> str: + # Terms contain Unicode letters/numbers only, but quote them explicitly so + # FTS always sees ordinary words rather than a caller-supplied expression. + return " OR ".join('"' + term.replace('"', '""') + '"' for term in terms) + + +def _stem(token: str) -> str: + """Apply small Porter-style suffix rules for the no-FTS fallback.""" + if len(token) > 5 and token.endswith("ies"): + return token[:-3] + "y" + if len(token) > 5 and token.endswith("ing"): + token = token[:-3] + if len(token) > 2 and token[-1] == token[-2]: + token = token[:-1] + return token + if len(token) > 4 and token.endswith("ed"): + token = token[:-2] + if len(token) > 2 and token[-1] == token[-2]: + token = token[:-1] + return token + if len(token) > 4 and token.endswith("s") and not token.endswith("ss"): + return token[:-1] + if len(token) > 5 and token.endswith("e"): + return token[:-1] + return token + + +def _fallback_search( + sections: list[dict[str, Any]], terms: Sequence[str], limit: int +) -> list[tuple[dict[str, Any], float]]: + terms = [_stem(term) for term in terms] + ranked: list[tuple[dict[str, Any], float]] = [] + for section in sections: + title_text = " ".join([section["title"], *section["headings"]]).casefold() + title_tokens = {_stem(token) for token in _TOKEN_RE.findall(title_text)} + body_tokens = {_stem(token) for token in _TOKEN_RE.findall(section["content"].casefold())} + score = sum(5 for term in terms if term in title_tokens) + sum(1 for term in terms if term in body_tokens) + if score: + ranked.append((section, -float(score))) + ranked.sort(key=lambda item: (item[1], item[0]["id"])) + return ranked[:limit] + + +def _fts_search(sections: list[dict[str, Any]], terms: Sequence[str], limit: int) -> list[tuple[dict[str, Any], float]]: + db = sqlite3.connect(":memory:") + try: + db.execute( + "CREATE VIRTUAL TABLE doc_search USING fts5(id UNINDEXED, title, headings, content, " + "tokenize='porter unicode61 remove_diacritics 2')" + ) + except sqlite3.OperationalError as error: + if "no such module: fts5" in str(error).casefold(): + raise NotImplementedError("SQLite was built without FTS5") from error + raise + try: + db.executemany( + "INSERT INTO doc_search (id, title, headings, content) VALUES (?, ?, ?, ?)", + [ + (section["id"], section["title"], " ".join(section["headings"]), section["content"]) + for section in sections + ], + ) + rows = db.execute( + "SELECT id, bm25(doc_search, 0.0, 8.0, 5.0, 1.0) AS score " + "FROM doc_search WHERE doc_search MATCH ? ORDER BY score, id LIMIT ?", + (_quote_fts_terms(terms), limit), + ).fetchall() + finally: + db.close() + by_id = {section["id"]: section for section in sections} + return [(by_id[section_id], float(score)) for section_id, score in rows] + + +def _excerpt(section: dict[str, Any], terms: Sequence[str]) -> str: + content = section["content"].strip() + if len(content) <= MAX_EXCERPT_CHARS: + return content + earliest: int | None = None + for term in terms: + match = re.search(re.escape(term), content, re.IGNORECASE) + if match and (earliest is None or match.start() < earliest): + earliest = match.start() + start = max(0, (earliest or 0) - MAX_EXCERPT_CHARS // 4) + prefix = start > 0 + end = min(len(content), start + MAX_EXCERPT_CHARS - int(prefix)) + suffix = end < len(content) + if suffix: + end -= 1 + excerpt = content[start:end].strip() + if prefix: + excerpt = "…" + excerpt + if suffix: + excerpt += "…" + return excerpt + + +def search(query: str, *, limit: int = DEFAULT_RESULTS, mode: str = "auto") -> dict[str, Any]: + """Return ranked section previews for a natural-language query.""" + if not query.strip(): + raise ValueError("query must not be empty") + if len(query) > MAX_QUERY_CHARS: + raise ValueError(f"query must be at most {MAX_QUERY_CHARS} characters") + if not 1 <= limit <= MAX_RESULTS: + raise ValueError(f"limit must be between 1 and {MAX_RESULTS}") + if mode not in {"auto", "bm25", "semantic", "hybrid"}: + raise ValueError("mode must be auto, bm25, semantic, or hybrid") + + sections, content_hash = load_corpus() + terms = query_terms(query) + if not terms: + ranked: list[tuple[dict[str, Any], float]] = [] + payload: dict[str, Any] = { + "query": query, + "results": [], + "zero_hit": True, + "has_more": False, + "search_backend": "none", + "retrieval_mode": "none", + "query_mode": mode, + "corpus_hash": content_hash, + "fallback_reason": None, + } + payload["hint"] = "No searchable terms; try a command name or a more specific topic." + return payload + + from comfy_cli.docs import lancedb_search + + pack_state = lancedb_search.inspect_pack(corpus_hash=content_hash) + requested_mode = mode + effective_mode = "hybrid" if mode == "auto" and pack_state["compatible"] else mode + fallback_reason = None if pack_state["compatible"] else pack_state["reason"] + if effective_mode in {"semantic", "hybrid"} and not pack_state["compatible"]: + code = "docs_pack_incompatible" if pack_state["installed"] else "docs_search_unavailable" + raise lancedb_search.DocsSearchPackError( + code, + pack_state["reason"] or "The docs-search pack is unavailable.", + pack_state["hint"] or "Install the matching comfy-cli[docs-search] extra.", + ) + + if pack_state["compatible"]: + try: + payload = lancedb_search.search( + query, + mode="bm25" if effective_mode == "auto" else effective_mode, + limit=limit, + sections=sections, + corpus_hash=content_hash, + fallback_reason=None, + ) + payload["query_mode"] = requested_mode + return payload + except lancedb_search.DocsSearchPackError as error: + if requested_mode in {"semantic", "hybrid"}: + raise + fallback_reason = str(error) + + if mode not in {"auto", "bm25"}: + raise ValueError("requested semantic retrieval is unavailable") + + if terms: + try: + ranked = _fts_search(sections, terms, limit + 1) + backend = "fts5" + except NotImplementedError: + ranked = _fallback_search(sections, terms, limit + 1) + backend = "token-scan" + + results = [ + { + **{key: section[key] for key in ("id", "title", "headings", "source", "source_line")}, + "excerpt": _excerpt(section, terms), + } + for section, _score in ranked[:limit] + ] + zero_hit = not results + payload: dict[str, Any] = { + "query": query, + "results": results, + "zero_hit": zero_hit, + "has_more": len(ranked) > limit, + "search_backend": backend, + "retrieval_mode": "bm25" if backend == "fts5" else "token-scan", + "query_mode": requested_mode, + "corpus_hash": content_hash, + "fallback_reason": fallback_reason, + } + if zero_hit: + payload["hint"] = "No documentation matched; try a command name or a more specific topic." + return payload + + +def status() -> dict[str, Any]: + """Describe core docs and the optional LanceDB semantic-search pack.""" + _sections, content_hash = load_corpus() + from comfy_cli.docs.lancedb_search import status as pack_status + + return { + "corpus_hash": content_hash, + "core_modes": ["bm25", "token-scan-fallback"], + **pack_status(corpus_hash=content_hash), + } + + +def show(section_id: str, *, max_chars: int = DEFAULT_SECTION_CHARS, offset: int = 0) -> dict[str, Any] | None: + """Return a section page, or None when the ID is not in this corpus.""" + if not 1 <= max_chars <= MAX_SECTION_CHARS: + raise ValueError(f"max_chars must be between 1 and {MAX_SECTION_CHARS}") + if offset < 0: + raise ValueError("offset must be non-negative") + sections, content_hash = load_corpus() + section = next((item for item in sections if item["id"] == section_id), None) + if section is None: + return None + content = section["content"] + if offset > len(content): + raise ValueError(f"offset must be between 0 and {len(content)} for this section") + end = min(offset + max_chars, len(content)) + return { + **{key: section[key] for key in ("id", "title", "headings", "source", "source_line")}, + "content": content[offset:end], + "total_chars": len(content), + "offset": offset, + "truncated": end < len(content), + "next_offset": end if end < len(content) else None, + "corpus_hash": content_hash, + } diff --git a/comfy_cli/docs/data/corpus.json b/comfy_cli/docs/data/corpus.json new file mode 100644 index 000000000..d1a974abc --- /dev/null +++ b/comfy_cli/docs/data/corpus.json @@ -0,0 +1,2467 @@ +{ + "schema_version": 1, + "content_hash": "1d62f56018524ac95c81a250666f0f4405c545328e6670b7b338ecb3a17af519", + "sections": [ + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-quick-start", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Quick Start" + ], + "source": "README.md", + "source_line": 33, + "content": "```bash\npip install comfy-cli\ncomfy setup\n```\n\n`comfy setup` walks you through everything — local or cloud routing, authentication, and agent skill installation — in one interactive wizard. Pass `-y` for non-interactive (CI/scripted) installs." + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-run-a-workflow-in-the-cloud", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Run a workflow in the cloud" + ], + "source": "README.md", + "source_line": 42, + "content": "No local GPU? Route any API-format workflow to [Comfy Cloud](https://www.comfy.org/) with `--where cloud`:\n\n```bash\ncomfy cloud login # sign in via your browser (OAuth)\ncomfy run --workflow ./workflow.json --where cloud # submits, prints a prompt_id, returns immediately\ncomfy jobs wait --where cloud # block until the job finishes (or: jobs status for a one-shot check)\ncomfy download --where cloud -o ./outputs # save the results locally\n```\n\n`comfy run` submits asynchronously and prints the `prompt_id` you feed to `jobs`/`download`; add `--wait` to block inline instead. Check your sign-in anytime with `comfy cloud whoami`. Export the workflow JSON from ComfyUI via **File → Export (API)** (UI-format JSON is auto-converted). Set cloud as your default target so you can drop the flag: `comfy set-default --where cloud`.\n\n**Credits:** cloud generation (`comfy run --where cloud`, `comfy generate`) consumes Comfy Cloud credits and needs an active subscription. Discovery and inspection commands — `comfy cloud whoami`, `comfy cloud status`, `comfy jobs status/ls`, `comfy templates ls`, `comfy generate list` — don't. Check your balance and tier with `comfy cloud status`." + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-installation", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Installation" + ], + "source": "README.md", + "source_line": 57, + "content": "1. (Recommended) Activate a virtual environment ([venv](https://docs.python.org/3/library/venv.html) or [conda](https://conda.io/projects/conda/en/latest/user-guide/getting-started.html)).\n\n2. Install with `pip` (requires Python 3.10+):\n\n ```bash\n pip install comfy-cli\n ```" + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-installation-shell-autocomplete", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Installation", + "Shell Autocomplete" + ], + "source": "README.md", + "source_line": 67, + "content": "Install shell completion so `comfy ` expands commands and options:\n\n```bash\ncomfy --install-completion\n```" + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-installing-comfyui", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Installing ComfyUI" + ], + "source": "README.md", + "source_line": 77, + "content": "To install ComfyUI using comfy, simply run:\n\n`comfy install`\n\nThis command will download and set up the latest version of ComfyUI and ComfyUI-Manager on your\nsystem. If you run in a ComfyUI repo that has already been setup. The command\nwill simply update the comfy.yaml file to reflect the local setup\n\n- `comfy install --skip-manager`: Install ComfyUI without ComfyUI-Manager.\n To use a custom Manager fork or specific version, skip the default installation\n and install your own into the workspace venv:\n ```bash\n comfy install --skip-manager\n # Then install your custom Manager:\n pip install -e /path/to/your-manager-fork # editable install\n # or\n pip install comfyui-manager==4.1b8 # specific version\n ```\n- `comfy --workspace= install`: Install ComfyUI into `/ComfyUI`.\n- `comfy install --fast-deps`: Use `uv` instead of `pip` for faster dependency resolution\n during initial ComfyUI installation. comfy-cli's built-in resolver compiles all requirements (core + custom nodes)\n into a single lockfile and installs from it. Also handles GPU-specific PyTorch wheel selection automatically.\n- For `comfy install`, if no path specification like `--workspace, --recent, or --here` is provided, it will be implicitly installed in `/comfy`." + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-installing-comfyui-python-environment-handling", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Installing ComfyUI", + "Python environment handling" + ], + "source": "README.md", + "source_line": 103, + "content": "When you run `comfy install`, comfy-cli picks a Python environment for ComfyUI\ndependencies using the following precedence:\n\n1. An **active virtualenv or conda** environment (`VIRTUAL_ENV` / `CONDA_PREFIX`) is used as-is.\n2. An **existing `.venv` or `venv`** directory inside the workspace is reused.\n3. Otherwise the choice depends on how comfy-cli was installed:\n - **`pip install comfy-cli`** (global / system Python): dependencies go\n directly into the same Python environment. This is the typical Docker setup.\n - **`pipx install comfy-cli`** or **`uv tool install comfy-cli`** (isolated\n tool environment): a `.venv` is created inside the ComfyUI workspace.\n Use `comfy launch` to start ComfyUI with the correct Python." + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-updating-comfyui", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Updating ComfyUI" + ], + "source": "README.md", + "source_line": 117, + "content": "`comfy update` brings an existing workspace up to date:\n\n- `comfy update` (or `comfy update comfy`): pull the branch the workspace is currently on and reinstall `requirements.txt`.\n- `comfy update all`: also update every installed custom node.\n- `comfy update cli`: upgrade comfy-cli itself.\n\nBy default `comfy update all` exits 0 even when the custom-node update step fails — the error is printed, but the exit code says success, so scripts and wrappers can't tell. Pass `--exit-on-fail` (the same flag name and default as `comfy node install --exit-on-fail`) to have that failure exit non-zero instead. The flag only changes the `all` target; `comfy update comfy` and `comfy update cli` already exit non-zero when they fail, and accept the flag as a no-op so it can be forwarded unconditionally.\n\nOne limit worth knowing: `--exit-on-fail` can only surface what ComfyUI-Manager's `cm-cli update` reports. `cm-cli` currently handles a *single* pack failing to update by printing `ERROR: ...` and carrying on, still exiting 0, so that particular case stays invisible until ComfyUI-Manager propagates it. Unlike `comfy node install`, the flag is not forwarded to `cm-cli` — only its `install` subcommand accepts `--exit-on-fail`; its `update` subcommand has no such option and would reject it.\n\nWhen the flag does fire, the exit code is `cm-cli`'s own, normalized so it is always usable: a process killed by a signal becomes `128+N` rather than a truncated value, an exit code that would truncate to 0 becomes 1, and 2 becomes 1 so it can't be mistaken for a CLI usage error. In `--json` mode the failure is also reported as an `update_custom_nodes_failed` error envelope carrying `cm-cli`'s raw status in `details.cm_cli_returncode`." + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-updating-comfyui-switching-to-a-specific-version", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Updating ComfyUI", + "Switching to a specific version" + ], + "source": "README.md", + "source_line": 131, + "content": "`comfy update comfy --version ` moves an existing workspace to a specific ComfyUI version — a downgrade (rollback) or an upgrade — without prompting for anything, so it is safe to run headlessly or from a script. `` is `nightly` (the repo's default branch), `latest` (the newest stable release), or a version number such as `0.3.0` (a leading `v` is optional).\n\n```bash\ncomfy update comfy --version 0.3.0 # roll back to the v0.3.0 release\ncomfy update comfy --version latest # newest stable release\ncomfy update comfy --version nightly # roll forward to the default branch\n```\n\nBehavior worth knowing:\n\n- **The target is validated before anything is touched.** An unknown version exits non-zero, lists the nearest available versions, and leaves the working tree exactly as it was.\n- **Uncommitted changes are stashed by default** (`git stash push -u`) and are *never* popped or dropped automatically — the stash ref is printed so you can restore them with `git stash pop`. Pass `--no-stash` if you would rather the command refuse to run on a dirty tree.\n- **A version number checks out a tag, which leaves a detached HEAD.** That is expected. Roll forward again with `comfy update comfy --version nightly` (or `--version latest`); a plain `comfy update` cannot advance a detached HEAD.\n- **Dependencies are reinstalled** from the target version's `requirements.txt`. PyTorch is deliberately left alone: the ComfyUI version doesn't determine your torch build, your machine does. If the dependency install fails, the command exits non-zero and says so — the tree is already on the new version, and re-running the same command is safe.\n- `--version` and `--no-stash` apply only to target `comfy`; combining `--version` with `all` or `cli` is an error." + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-specifying-execution-path", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Specifying execution path" + ], + "source": "README.md", + "source_line": 149, + "content": "- You can specify the path of ComfyUI where the command will be applied through path indicators as follows:\n - `comfy --workspace=`: Run from the ComfyUI installed in the specified workspace.\n - `comfy --recent`: Run from the recently executed or installed ComfyUI.\n - `comfy --here`: Run from the ComfyUI located in the current directory.\n- --workspace, --recent, and --here options cannot be used simultaneously.\n- If there is no path indicator, the following priority applies:\n\n - Run from the default ComfyUI at the path specified by `comfy set-default `.\n - Run from the recently executed or installed ComfyUI.\n - Run from the ComfyUI located in the current directory.\n\n- Example 1: To run the recently executed ComfyUI:\n - `comfy --recent launch`\n- Example 2: To install a package on the ComfyUI in the current directory:\n - `comfy --here node install comfyui-impact-pack`\n- Example 3: To update the automatically selected path of ComfyUI and custom nodes based on priority:\n\n - `comfy node update all`\n\n- You can use the `comfy which` command to check the path of the target workspace.\n - e.g `comfy --recent which`, `comfy --here which`, `comfy which`, ..." + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-default-setup", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Default Setup" + ], + "source": "README.md", + "source_line": 173, + "content": "The default sets the option that will be executed by default when no specific workspace's ComfyUI has been set for the command.\n\n`comfy set-default ?[--launch-extras=\"\"]`\n\n- `--launch-extras` option specifies extra args that are applied only during launch by default. However, if extras are specified at the time of launch, this setting is ignored." + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-launch-comfyui", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Launch ComfyUI" + ], + "source": "README.md", + "source_line": 181, + "content": "Comfy provides commands that allow you to easily run the installed ComfyUI.\n\n`comfy launch`\n\n- To run with default ComfyUI options:\n\n `comfy launch -- `\n\n `comfy launch -- --cpu --listen 0.0.0.0`\n\n - When you manually configure the extra options, the extras set by set-default will be overridden.\n\n- To run background\n\n `comfy launch --background`\n\n `comfy --workspace=~/comfy launch --background -- --listen 10.0.0.10 --port 8000`\n\n - Instances launched with `--background` are displayed in the \"Background ComfyUI\" section of `comfy env`, providing management functionalities for a single background instance only.\n - Background-running ComfyUI can be stopped with `comfy stop`.\n\n- To point **every** command (not just one) at a ComfyUI on a non-default\n address — e.g. a server you started _outside_ comfy-cli on `:8189` — export\n the `COMFY_LOCAL_URL` environment variable:\n\n `export COMFY_LOCAL_URL=http://127.0.0.1:8189`\n\n - Accepts `http://host:port`, `host:port`, or `http://host` (the port\n defaults to `8188`; the scheme is optional and, if present, must be\n `http`). IPv6 literals are bracketed: `COMFY_LOCAL_URL=http://[::1]:8189`.\n - Honored by `comfy env`, `comfy run`, `comfy jobs`, `comfy upload`/`download`,\n `comfy nodes`, and every other local-targeting command, so `comfy env`'s\n \"Comfy Server Running\" line now probes and reports the resolved address.\n - Precedence (per command): a per-command `--host`/`--port` flag wins, then\n `COMFY_LOCAL_URL`, then a comfy-cli-launched background server, then the\n `127.0.0.1:8188` default. A malformed value is ignored with a one-line\n stderr warning rather than breaking the command.\n\n- to run ComfyUI with a specific pull request:\n\n `comfy install --pr \"#1234\"`\n\n `comfy install --pr \"jtydhr88:load-3d-nodes\"`\n\n `comfy install --pr \"https://github.com/comfyanonymous/ComfyUI/pull/1234\"`\n\n - If you want to run ComfyUI with a specific pull request, you can use the `--pr` option. This will automatically install the specified pull request and run ComfyUI with it.\n - Important: The --pr option cannot be combined with --version or --commit and will be rejected if used together.\n\n- To test a frontend pull request:\n\n ```\n comfy launch --frontend-pr \"#456\"\n comfy launch --frontend-pr \"username:branch-name\"\n comfy launch --frontend-pr \"https://github.com/Comfy-Org/ComfyUI_frontend/pull/456\"\n ```\n\n - The `--frontend-pr` option allows you to test frontend PRs by automatically cloning, building, and using the frontend for that session.\n - Requirements: Node.js and npm must be installed to build the frontend.\n - Builds are cached for quick switching between PRs - subsequent uses of the same PR are instant.\n - Each PR is used only for that launch session. Normal launches use the default frontend.\n\n **Managing PR cache**:\n ```\n comfy pr-cache list # List cached PR builds\n comfy pr-cache clean # Clean all cached builds\n comfy pr-cache clean 456 # Clean specific PR cache\n ```\n\n - Cache automatically expires after 7 days\n - Maximum of 10 PR builds are kept (oldest are removed automatically)\n - Cache limits help manage disk space while keeping recent builds available\n\n- To check VRAM/RAM usage: `comfy system-stats` (add `--where cloud` to target Comfy Cloud instead of local)\n- To unload models / free the executor cache: `comfy free` (pass `--free-memory` to also reset the executor cache)" + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-managing-custom-nodes", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Managing Custom Nodes" + ], + "source": "README.md", + "source_line": 259, + "content": "comfy provides a convenient way to manage custom nodes for extending ComfyUI's functionality. Here are some examples:\n\n- Show custom nodes' information:\n\n```\ncomfy node [show|simple-show] [installed|enabled|not-installed|disabled|all|snapshot|snapshot-list]\n ?[--channel ]\n ?[--mode [remote|local|cache]]\n```\n\n- `comfy node show all --channel recent`\n\n `comfy node simple-show installed`\n\n `comfy node update all`\n\n `comfy node install comfyui-impact-pack`\n\n > **Note:** the argument is the node's **Comfy Registry ID**, which is\n > lowercase (e.g. `comfyui-impact-pack`), not the GitHub repository name\n > (`ComfyUI-Impact-Pack`). Passing the repo-name casing fails to resolve with\n > an error like `Node 'ComfyUI-Impact-Pack@unknown' not found`. Find a node's\n > ID on its [Comfy Registry](https://registry.comfy.org) page or via\n > `comfy node show all`.\n\n- Managing snapshot:\n\n `comfy node save-snapshot`\n\n `comfy node restore-snapshot `\n\n- Install dependencies:\n\n `comfy node install-deps --deps=`\n\n `comfy node install-deps --workflow=`\n\n- Generate deps:\n\n `comfy node deps-in-workflow --workflow= --output=`" + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-managing-custom-nodes-install-vs-registry-install", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Managing Custom Nodes", + "`install` vs `registry-install`" + ], + "source": "README.md", + "source_line": 302, + "content": "comfy-cli offers two ways to install a custom node, backed by different\nmechanisms:\n\n- **`comfy node install ...`** delegates to\n [ComfyUI-Manager](https://github.com/Comfy-Org/ComfyUI-Manager)'s `cm-cli`.\n It accepts one or more node IDs, resolves them through the Manager's channel\n database (`--channel`, `--mode`), and installs dependencies via the Manager\n (so it also supports `--fast-deps`, `--no-deps`, and `--uv-compile`). This is\n the recommended command for day-to-day node management, and it requires\n ComfyUI-Manager to be present in the workspace.\n\n `comfy node install comfyui-impact-pack`\n\n- **`comfy node registry-install [--version ]`** talks directly to the\n [Comfy Registry](https://registry.comfy.org) API. It downloads the published\n archive for a single node (optionally pinned with `--version`), extracts it\n into `custom_nodes/`, and runs the node's own install script. It does **not**\n go through ComfyUI-Manager, so it does not require the Manager to be\n installed — this is the command the Registry's own install instructions use.\n\n `comfy node registry-install comfyui-impact-pack`\n\n `comfy node registry-install comfyui-impact-pack --version 1.0.0` # install a specific version\n\n Because `registry-install` bypasses the Manager's dependency machinery and\n simply runs the node's bundled install script, it only accepts\n `--force-download` — it does **not** accept `--fast-deps`, `--no-deps`, or\n `--uv-compile`. If you want fast/unified dependency resolution, use\n `comfy node install` instead." + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-managing-custom-nodes-unified-dependency-resolution---uv-compile", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Managing Custom Nodes", + "Unified Dependency Resolution (--uv-compile)" + ], + "source": "README.md", + "source_line": 334, + "content": "Requires ComfyUI-Manager v4.1+. Instead of installing dependencies per-node with\n`pip install`, `--uv-compile` delegates to ComfyUI-Manager's unified resolver which batch-resolves\nall custom node dependencies via `uv pip compile` with **cross-node conflict detection** —\nit can identify which node packs have incompatible dependencies and why.\n\n- Install with unified resolution:\n\n `comfy node install comfyui-impact-pack --uv-compile`\n\n- Available on: `install`, `reinstall`, `update`, `fix`, `restore-snapshot`,\n `restore-dependencies`, `install-deps`\n\n- Run standalone (resolve all existing custom node dependencies):\n\n `comfy node uv-sync`\n\n- `--uv-compile` is mutually exclusive with `--fast-deps` and `--no-deps` —\n except on `restore-snapshot`, where `--fast-deps` selects the `--uv-compile`\n path instead (see [--fast-deps](#--fast-deps) below).\n\n- To make `--uv-compile` the default for all commands, see\n [uv-compile default](#uv-compile-default) below.\n\n- Use `--no-uv-compile` to override the default for a single command:\n\n `comfy node install comfyui-impact-pack --no-uv-compile`" + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-managing-custom-nodes-fast-deps", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Managing Custom Nodes", + "--fast-deps" + ], + "source": "README.md", + "source_line": 363, + "content": "`--fast-deps` swaps comfy-cli's dependency installation from `pip` to comfy-cli's\nbuilt-in `uv`-based resolver (`DependencyCompiler`), which is significantly\nfaster and only requires `uv` (no ComfyUI-Manager). On a dependency version\nconflict it prompts you interactively to pick a version.\n\n- Accepted by: `comfy install`, `comfy node install`, `comfy node reinstall`,\n and `comfy node restore-snapshot`.\n\n `comfy install --fast-deps`\n\n `comfy node install comfyui-impact-pack --fast-deps`\n\n- **Not** accepted by `comfy node registry-install`: that command installs a\n node directly from the Comfy Registry by running the node's own bundled\n install script, so it never touches comfy-cli's dependency resolver (see\n [`install` vs `registry-install`](#install-vs-registry-install) above).\n- Mutually exclusive with `--no-deps` and `--uv-compile`, where those flags\n exist — the exact pairing is per-command:\n\n | Command | Rejected combination |\n |---------|----------------------|\n | `comfy node install` | `--fast-deps --no-deps`, `--fast-deps --uv-compile` |\n | `comfy node reinstall` | `--fast-deps --uv-compile` (no `--no-deps` on this command) |\n | `comfy node restore-snapshot` | `--fast-deps --no-uv-compile` (see below) |\n | `comfy install` | none (neither flag exists on this command) |\n\n- **Exception — `comfy node restore-snapshot`:** here `--fast-deps` *selects*\n the `--uv-compile` fast path rather than conflicting with it. ComfyUI-Manager's\n `cm-cli` has no `--no-deps` on `restore-snapshot`, and its `--uv-compile`\n already implies no-deps internally, so the two are synonyms on this command.\n Combining `--fast-deps` with `--no-uv-compile` is the contradiction, and it\n errors: `Cannot use --fast-deps with --no-uv-compile`." + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-managing-custom-nodes-fast-deps-vs---uv-compile", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Managing Custom Nodes", + "--fast-deps vs --uv-compile" + ], + "source": "README.md", + "source_line": 398, + "content": "Both flags use `uv` for faster dependency resolution, but they work differently:\n\n| | `--fast-deps` | `--uv-compile` |\n|-----------------------|-------------------------------------------------|-----------------------------------------------|\n| **Resolver** | comfy-cli built-in (`DependencyCompiler`) | ComfyUI-Manager (`UnifiedDepResolver`) |\n| **Scope** | `comfy install`, `comfy node install/reinstall/restore-snapshot` | Custom node commands only |\n| **Conflict handling** | Interactive prompt to pick a version | Automatic detection with node attribution |\n| **Config default** | No | Yes (`comfy manager uv-compile-default true`) |\n| **Requires** | Only `uv` | ComfyUI-Manager v4.1+ |\n\n**When to use which:**\n- For initial ComfyUI installation with uv: `comfy install --fast-deps`\n- For custom node management with Manager v4.1+: `--uv-compile` (recommended)\n- For custom node management with older Manager: `--fast-deps`" + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-managing-custom-nodes-bisect-custom-nodes", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Managing Custom Nodes", + "Bisect custom nodes" + ], + "source": "README.md", + "source_line": 415, + "content": "If you encounter bugs only with custom nodes enabled, and want to find out which custom node(s) causes the bug,\nthe bisect tool can help you pinpoint the custom node that causes the issue.\n\n- `comfy node bisect start`: Start a new bisect session with optional ComfyUI launch args. It automatically marks the starting state as bad, and takes all enabled nodes when the command executes as the test set.\n- `comfy node bisect good`: Mark the current active set as good, indicating the problem is not within the test set.\n- `comfy node bisect bad`: Mark the current active set as bad, indicating the problem is within the test set.\n- `comfy node bisect reset`: Reset the current bisect session." + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-managing-models", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Managing Models" + ], + "source": "README.md", + "source_line": 425, + "content": "- Model downloading\n\n `comfy model download --url ?[--relative-path ] ?[--set-civitai-api-token ] ?[--set-hf-api-token ]`\n\n - URL: CivitAI page, Hugging Face file URL, etc...\n - You can also specify your API tokens via the `CIVITAI_API_TOKEN` and `HF_API_TOKEN` environment variables. The order of priority is `--set-X-token` (always highest priority), then the environment variables if they exist, and lastly your config's stored tokens from previous `--set-X-token` usage (which remembers your most recently set token values).\n - Tokens provided via the environment variables are never stored persistently in your config file. They are intended as a way to easily and safely provide transient secrets.\n\n- Model remove\n\n `comfy model remove ?[--relative-path ] --model-names `\n\n- Model list\n\n `comfy model list ?[--relative-path ]`" + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-running-on-comfy-cloud---where-cloud", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Running on Comfy Cloud (`--where cloud`)" + ], + "source": "README.md", + "source_line": 443, + "content": "Comfy Cloud runs your workflow on Comfy's GPUs — no local ComfyUI install and no GPU required. The same verbs you use locally take `--where cloud`; the only extra step is signing in once.\n\nPrerequisites — a Comfy account with a credit balance ([add credits](https://docs.comfy.org/interface/credits); cloud runs are metered per GPU-second):\n\n```bash\ncomfy cloud login # opens your browser (OAuth + PKCE), stores a session\ncomfy cloud whoami # confirm who you're signed in as\ncomfy cloud status # workspace, credit balance, tier, concurrency limit\n```\n\nThen submit, watch, and collect:\n\n```bash\ncomfy run --workflow my_workflow_api.json --where cloud # submits, prints a prompt_id, returns\ncomfy jobs ls --where cloud # queue + history for your account\ncomfy jobs status --where cloud # one job's state\ncomfy jobs watch --where cloud # live progress until it finishes\ncomfy download --where cloud # fetch the outputs\n```\n\nNotes:\n\n- `--where cloud` is per-invocation. Make it the default with `comfy set-default --where cloud`; every command then honors it without the flag, and `--where local` overrides it for one call. Clear it again with `comfy set-default --clear-where`.\n- Add `--wait` to `comfy run` to block until the job completes instead of returning immediately.\n- `comfy run --prompt \"\"` (no `--workflow`) runs a bundled default text2img graph. **That graph loads the SD1.5 checkpoint `v1-5-pruned-emaonly.ckpt`, which comfy-cli does not download for you** — install it into `models/checkpoints`, or point the graph at a checkpoint you do have with `comfy run --prompt \"…\" --set checkpoint=`. The same applies on cloud, where the checkpoint must exist in your cloud assets.\n- `comfy download` also reads a `prompt_id` from piped stdin, so `comfy run ... --where cloud | comfy download --where cloud` works.\n- Models and custom nodes must exist on the cloud side. `comfy models search --where cloud` lists the cloud asset catalog, and `comfy nodes ls --where cloud` lists the node classes cloud can run.\n- Sign out with `comfy cloud logout`. If a run fails with `cloud_unauthorized`, your session expired — re-run `comfy cloud login`." + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-calling-partner-nodes-comfy-generate", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Calling partner nodes (`comfy generate`)" + ], + "source": "README.md", + "source_line": 474, + "content": "`comfy generate` calls Comfy's partner nodes directly from the terminal — no\nlocal ComfyUI or workflow JSON required. It hits the same hosted partner nodes\nyou'd otherwise wire into a ComfyUI workflow, but as one-shot CLI calls. Image\nmodels (Flux, Ideogram, DALL·E, Recraft, Stability, Runway, Reve, xAI Grok,\nGoogle Gemini Flash Image aka **nano-banana**, …) and video models (Kling,\nLuma, Runway Gen-3, Pika, Vidu, Moonvalley, Hailuo, Grok video, ByteDance\n**Seedance**) are all covered; video jobs run async and the CLI polls until\nthe result is ready.\n\nPrerequisites — a Comfy API key and a credit balance:\n\n- [Create an API key](https://docs.comfy.org/development/comfyui-server/api-key-integration)\n- [Browse partner nodes and per-call credit costs](https://docs.comfy.org/tutorials/partner-nodes/overview) · [pricing table](https://docs.comfy.org/tutorials/partner-nodes/pricing)\n- [Add credits](https://docs.comfy.org/interface/credits)\n\nSet the key once, then go:\n\n```bash\nexport COMFY_API_KEY=comfyui-... # or pass --api-key on each call\n\ncomfy generate list # browse available models\ncomfy generate schema flux-pro # see params for one model\ncomfy generate flux-pro --prompt \"a cat on the moon\" \\\n --width 1024 --height 1024 --download cat.png\n```\n\nReference images can be passed as local paths — the CLI uploads them through\nthe cloud's storage endpoint (or base64-encodes inline, as each partner\nrequires):\n\n```bash\ncomfy generate flux-kontext --prompt \"add a top hat\" \\\n --input_image ./photo.jpg --download out.png\n\ncomfy generate upload ./photo.jpg # explicit upload\n```\n\nAsync models (every video model plus the Flux family) block until ready by\ndefault. Pass `--async` to return immediately with a job id, then resume later\nwith `comfy generate resume `. Examples:\n\n```bash\ncomfy generate kling --prompt \"a paper boat drifting on a river at dusk\" \\\n --duration 5 --download boat.mp4\n\ncomfy generate luma --prompt \"...\" --aspect_ratio 16:9 --async\n# → prints job id; resume with:\ncomfy generate resume luma --download out.mp4\n```\n\n**Gemini Flash Image (nano-banana)** — text-to-image and image edits in one\nalias. Pass `--image` (repeatable) for reference images. The response is\ninline base64, so `--download` is required to save:\n\n```bash\ncomfy generate nano-banana --prompt \"a watercolor of a sleeping fox\" \\\n --download fox.png\n\n# Image edit — reference accepted as a local path, http(s) URL, or data URI:\ncomfy generate nano-banana --prompt \"add a top hat\" \\\n --image ./cat.png --download out.png\n\n# Switch model variants:\ncomfy generate nano-banana --prompt \"...\" --model gemini-3-pro-image-preview \\\n --download out.png\n```\n\n**Seedance** — text-to-video and image-to-video, up to 1080p / 12s clips.\nResolution, ratio, duration, fps, etc. get passed through as flags; the CLI\ninlines them into Seedance's prompt syntax for you:\n\n```bash\ncomfy generate seedance --prompt \"a hummingbird hovering over a flower\" \\\n --resolution 1080p --duration 5 --download bird.mp4\n\n# Image-to-video: pick a lite/i2v variant and pass a first frame.\ncomfy generate seedance --model seedance-1-0-lite-i2v-250428 \\\n --prompt \"the wave crests and crashes\" \\\n --image ./still.jpg --download wave.mp4\n```" + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-managing-comfyui-manager", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Managing ComfyUI-Manager" + ], + "source": "README.md", + "source_line": 557, + "content": "- Disable ComfyUI-Manager completely (no manager flags passed to ComfyUI):\n\n `comfy manager disable`\n\n- Enable ComfyUI-Manager with new GUI:\n\n `comfy manager enable-gui`\n\n- Enable ComfyUI-Manager without GUI (manager runs but UI is hidden):\n\n `comfy manager disable-gui`\n\n- Enable ComfyUI-Manager with legacy GUI:\n\n `comfy manager enable-legacy-gui`\n\n- Clear reserved startup action:\n\n `comfy manager clear`\n\n- Migrate legacy git-cloned ComfyUI-Manager to pip package:\n\n `comfy manager migrate-legacy`" + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-usage-managing-comfyui-manager-uv-compile-default", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Usage", + "Managing ComfyUI-Manager", + "uv-compile default" + ], + "source": "README.md", + "source_line": 583, + "content": "Set `--uv-compile` as the default behavior for all custom node operations:\n\n `comfy manager uv-compile-default true`\n\nWhen enabled, all node commands (`install`, `reinstall`, `update`, `fix`,\n`restore-snapshot`, `restore-dependencies`, `install-deps`) will automatically\nuse `--uv-compile`. Use `--no-uv-compile` on any individual command to override.\n\nTo disable:\n\n `comfy manager uv-compile-default false`" + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-curated-model-knowledge", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Curated model knowledge" + ], + "source": "README.md", + "source_line": 630, + "content": "Discovery commands can attach a `knowledge` block to their `--json` output: which\nmodel a name refers to, whether it is deprecated, ranked picks per capability,\nand known pitfalls. A signed-in install (`comfy cloud login`) fetches the bundle\nfrom the cloud knowledge channel on its own. Signed out, the fetch fails quietly\nand no block is emitted unless a bundle is already cached.\n\nPoint the CLI at a different bundle with either of:\n\n```\nexport COMFY_KNOWLEDGE_URL=https://.../knowledge.json # fetched and cached\nexport COMFY_KNOWLEDGE_FILE=/path/to/knowledge.json # read directly, never cached\n```\n\nCheck what is loaded:\n\n```\ncomfy knowledge status\ncomfy knowledge resolve \"Kling 3.0\"\ncomfy knowledge pick lipsync\n```\n\nTurn it off again:\n\n```\nexport COMFY_KNOWLEDGE_DISABLE=1\n```\n\nSigning out is *not* an off switch. Once a bundle is cached it keeps being\nserved, stale or not. `COMFY_KNOWLEDGE_DISABLE` suppresses envelope\nenrichment outright; the `comfy knowledge` verbs keep working under it, since\nthose are you asking for the bundle directly.\n\nEnrichment only ever reads the cache, so no command waits on a fetch. The cache\nrefreshes during `comfy skills install` and in the background during\n`comfy launch`, or on demand with `comfy knowledge status --refresh`." + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-searching-the-cli-docs", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Searching the CLI docs" + ], + "source": "README.md", + "source_line": 668, + "content": "Search the CLI guides and installed agent guides locally. BM25 works with the\nbase CLI. The optional extra adds a version-matched LanceDB pack and local\nquery encoder for offline semantic and hybrid search:\n\n```bash\npip install 'comfy-cli[docs-search]' # optional; includes the version-matched offline pack\ncomfy --json docs status\ncomfy --json docs search \"workflow hangs on a cloud timeout\" --mode hybrid\ncomfy --json docs show \"SECTION_ID\"\n```\n\n`docs status` reports which modes this install can use. Search results include\na section ID, source location, and a short excerpt. Pass the ID to `docs show`\nto read the full section; use `--max-chars` and `--offset` to page through a\nlong section. The docs command needs no ComfyUI workspace, and queries never\ndownload a model. Results describe this comfy-cli release. Without the optional\npack, `--mode auto` uses BM25 and reports why semantic search is unavailable.\nAgents can search each part of a larger question, read the relevant sections,\nand reformulate a missed search once with a comfy command or flag." + }, + { + "id": "readme:comfy-cli-a-command-line-tool-for-comfyui-analytics", + "title": "comfy-cli", + "headings": [ + "comfy-cli: A Command Line Tool for ComfyUI", + "Analytics" + ], + "source": "README.md", + "source_line": 690, + "content": "Analytics are **opt-in and off by default**. The first time you run the CLI in an\ninteractive terminal it asks whether to enable tracking, and that prompt defaults\nto no. Nothing is sent unless you answer yes. A non-interactive run (a pipe, CI,\nan agent) never enables it on its own. Setting `DO_NOT_TRACK` or\n`COMFY_NO_TELEMETRY` in the environment overrides the setting and suppresses\neverything.\n\nChange your mind at any time:\n\n```\ncomfy tracking enable\ncomfy tracking disable\n```\n\nWhen tracking is on, we use Mixpanel to understand usage patterns and know where\nto prioritize our efforts.\n\n**One event carries text you typed.** If a curated knowledge bundle is loaded\n(a signed-in install fetches one on its own), then `comfy nodes search`,\n`comfy templates ls`, `comfy generate schema`,\n`comfy generate list` and `comfy models search` send the search terms you typed\nand which curated entries they matched. This tells us what people look for and fail\nto find. It needs both the bundle and your tracking consent, so with either one\nabsent nothing is sent.\n\nCheck out the usage here: [Mixpanel Board](https://mixpanel.com/p/13hGfPfEPdRkjPtNaS7BYQ)" + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)" + ], + "source": "docs/json-output.md", + "source_line": 1, + "content": "> **Dialect change (breaking).** The legacy `{\"event\": …, \"schema_version\": 1,\n> \"error\": {\"kind\": …}}` dialect was removed; `comfy run --json` now emits the\n> CLI-wide renderer stream. Every event line carries `schema: \"event/1\"` and a\n> `type` discriminator, and the stream is terminated by a single envelope line\n> (`schema: \"envelope/1\"`, `type: \"envelope\"`) carrying `ok`/`data`/`error`.\n> Consumers discriminate the final line by `type: \"envelope\"`. Error\n> categorisation moved from `error.kind` to the registered `error.code` values\n> (`comfy --json discover` lists them all). The full legacy→current mapping is\n> at the [bottom of this document](#legacy-dialect-mapping).\n\nThis document specifies the output contract of `comfy run --json`. The intent\nis to give agents and automation a stable, parseable view of a workflow\nexecution — independent of the human-readable Rich-formatted output that\n`comfy run` emits by default.\n\n`comfy run --json` is exactly `comfy --json-stream run`: the command-local\nflag switches the process-wide renderer into NDJSON streaming mode. The same\nevent names are used by `comfy jobs watch` in stream mode, so the run stream\nand the watch stream speak one dialect." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-jobs-watch-attaches-as-the-submitting-session", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "`jobs watch` attaches as the submitting session" + ], + "source": "docs/json-output.md", + "source_line": 23, + "content": "A local ComfyUI server does **not** broadcast execution events: it addresses\n`executing` / `executed` / `progress_state` / `execution_cached` /\n`execution_success` to the websocket session that submitted the prompt. So\n`comfy jobs watch ` resolves that prompt's `client_id` — from the job\nstate file `comfy run` wrote, else `/queue`, else `/history` — and reconnects\nunder it; the terminal envelope reports which id it used (`data.client_id`) and\nwhether it was the real submitter (`data.attached`). Use `--client-id` to force a\nspecific one. Both keys are present on *every* `jobs watch` terminal envelope: a\nwatch of an already-finished prompt short-circuits without opening a socket, and\nreports `client_id: null` / `attached: false`. Reconnecting under an existing id\nis ComfyUI's own session-resume path, so a submitter that is *still* holding that\nsocket (an open browser tab, a blocking `comfy run`) stops receiving events until\nit reconnects.\n\n`data.completed_nodes` on the terminal envelope does not depend on the stream: it\nis the union of what the watch observed and what `/history` records for the\nprompt, so it is populated even for a watch that attached after the job ended." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-overview", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Overview" + ], + "source": "docs/json-output.md", + "source_line": 43, + "content": "When `--json` is passed, `comfy run` switches into a strict\nmachine-readable mode:\n\n- **stdout** carries exclusively **NDJSON** (newline-delimited JSON): one\n JSON object per line, each terminated by `\\n`. No ANSI, no progress bar,\n no headings. Each line is written and flushed to stdout as soon as the\n underlying event is produced; agents may rely on read-as-emitted timing —\n there is no batching (the `progress` event is throttled to ~10 Hz per node).\n- The stream is UTF-8. Non-ASCII characters in string fields are emitted\n as-is (`json.dumps(..., ensure_ascii=False)`).\n- **stderr** carries human-readable side messages plus anything the CLI\n cannot route through the JSON contract: framework-level Python errors,\n uncaught exceptions, library warnings. Agents should not parse stderr;\n they may discard it or capture it for diagnostics.\n- **Exit code** is `0` when the final envelope has `ok: true`, `130` when\n the run was cancelled (`error.code: \"cancelled\"` — Ctrl-C or a\n server-side interrupt), and `1` for every other failure. Fine-grained\n error categorisation is carried in `error.code`, not in the exit code.\n\nIn `--json` mode, `--verbose` has no effect: agents receive the full event\nstream regardless.\n\n**Workflow input format.** `--workflow` accepts both the ComfyUI **API\nformat** (the canonical `{node_id: {class_type, inputs, ...}}` graph\nproduced by \"Save (API Format)\") and the **exported UI format** (the\n`{nodes: [...], links: [...]}` shape produced by \"Save\"). UI workflows\nare converted to API format client-side via `/object_info` before\nqueuing; conversion is signalled by a [`converted`](#converted) event\nemitted before [`queued`](#queued). API-format input does not produce a\n`converted` event.\n\nAll duration fields in this contract are floats representing seconds.\nNumeric count fields (e.g., `progress.completed` / `total`) are JSON\n`number` and may be int or float depending on the underlying node." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-stream-shape", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Stream shape" + ], + "source": "docs/json-output.md", + "source_line": 80, + "content": "Every line on stdout is a JSON object with two universal fields:\n\n| Field | Type | Description |\n| -------- | ---- | ----------------------------------------------------------------- |\n| `schema` | str | Contract version: `\"event/1\"` on events, `\"envelope/1\"` on the final line |\n| `type` | str | Discriminator. Agents must dispatch on this field. |\n\nThe stream always ends with exactly one line of `type: \"envelope\"`:\n\n```json\n{\"schema\": \"envelope/1\", \"type\": \"envelope\", \"ok\": true, \"command\": \"run\", \"version\": \"1.6.1\", \"where\": \"local\", \"data\": {...}, \"error\": null}\n```\n\n| Field | Type | Description |\n| --------- | ------------ | --------------------------------------------------------------- |\n| `ok` | bool | `true` on success, `false` on failure |\n| `command` | str | The subcommand (`\"run\"`) |\n| `version` | str | comfy-cli version |\n| `where` | str \\| null | Target this invocation was routed to: `\"local\"` or `\"cloud\"`. Set as soon as routing resolves, so client-side failures that never reach that backend still carry it (e.g. `workflow_not_found`). `null` for commands that don't route, and for errors raised *before* routing resolves (e.g. `where_invalid`). |\n| `data` | dict \\| null | Result payload on success (see [Success envelope](#success-envelope)) |\n| `error` | dict \\| null | Error object on failure (see [Error object](#error-object)) |" + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-stream-shape-stream-archetypes", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Stream shape", + "Stream archetypes" + ], + "source": "docs/json-output.md", + "source_line": 104, + "content": "| Outcome | Stream |\n| ------------------------- | ---------------------------------------------------------------------------- |\n| Success (`--wait`) | `[converted]? + prompt_preview + queued + [node events]* + envelope(ok)` |\n| `--no-wait` queued (default) | `[converted]? + prompt_preview + queued + envelope(ok, data.status=\"queued\")` |\n| `--print-prompt` | `[converted]? + prompt_preview + envelope(ok, data.status=\"preview\")` |\n| Failure mid-execution | `[converted]? + prompt_preview + queued + [node events]* + envelope(error)` |\n| Failure at validation, consent, or submission | `[converted]? + prompt_preview + envelope(error)` |\n| Failure before the graph is parsed | `[converted]? + envelope(error)` |\n\nWhere `[node events]*` is zero or more interleaved `execution_cached`,\n`executing`, `progress`, `executed`, and `output` events. `[X]?` means X\nmay or may not appear. An error envelope can replace any non-terminal\nline, ending the stream early.\n\nThe last two rows split on **whether the CLI has a parsed graph in hand\nyet**, because `prompt_preview` is emitted as soon as it does — before any\ncheck that could still refuse the run:\n\n- **Before the graph is parsed** — the workflow file is missing, unreadable,\n or not JSON; a UI→API conversion failed (`conversion_error`,\n `conversion_crash`, `cql_no_graph`); the graph is empty\n (`workflow_empty`) or not in API format (`workflow_not_api_format`); no\n local server is running (`server_not_running`). These emit a bare error\n envelope. `converted` can precede it in exactly one case: conversion\n succeeded but its output still failed API-format classification.\n- **After it is parsed** — the CQL pre-flight (`workflow_unknown_nodes` and\n friends), the `spend_consent_required` consent gate, cloud authentication\n (`cloud_unauthorized`), and the submit call itself all run *after*\n `prompt_preview`. A run refused by any of them therefore emits\n `prompt_preview` first and *then* the error envelope — the previewed graph\n is what the CLI *would* have submitted, not a promise that it did.\n\nThis ordering is identical on both targets. Note that `prompt_preview`\ncarries the full workflow graph, so `--json-stream` output should be treated\nas sensitive if custom nodes embed local paths or credential-like widget\nvalues in it. Events are emitted in `--json-stream` mode only — neither\npretty nor plain `--json` mode ever writes a `prompt_preview` line.\n\nThese archetypes hold for **both** `--where local` and `--where cloud`, with\none exception: `comfy run --where cloud` produces no `[node events]*` — use\n`comfy jobs watch --where cloud` for in-flight cloud progress (see\n[Per-target differences](#per-target-differences)). Everything else — the\n`converted` / `prompt_preview` / `queued` prefix, the single terminal\nenvelope, and the exit-code mapping — is identical on both targets." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-per-target-differences", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Per-target differences" + ], + "source": "docs/json-output.md", + "source_line": 151, + "content": "`comfy run` has two execution targets — `--where local` (the default: an HTTP\nsubmit plus a WebSocket session against a ComfyUI server you run) and\n`--where cloud` (an HTTPS submit plus polling against Comfy Cloud). They emit\nthe **same event dialect** and the same envelope framing, but the targets are\nnot the same machine and a few things genuinely cannot match. The complete\nlist of differences:\n\n| Aspect | `--where local` | `--where cloud` |\n| ------ | --------------- | --------------- |\n| Per-node events (`executing`, `execution_cached`, `progress`, `executed`, `output`, `execution_error`) | Emitted, streamed live from the server WebSocket | Not emitted by `comfy run`. The cloud API is polled for a terminal record, so a `--wait` run goes straight from `queued` to the final envelope. For in-flight cloud progress, watch the job instead: `comfy --json-stream jobs watch --where cloud` emits a coarse `state` event per status transition plus an `output` event per artifact |\n| `queued.validation_warnings` | May be non-empty: the server can accept a prompt (HTTP 200) while reporting per-node issues | Always `[]` — the cloud rejects any submit carrying `node_errors` outright, as a `prompt_rejected` error envelope |\n| `queued.base_url` | Absent | Present — the cloud endpoint the prompt was submitted to |\n| Envelope `where` | `\"local\"` | `\"cloud\"` |\n| Envelope target fields | `data.host` (str), `data.port` (int) | `data.base_url` (str) |\n| Envelope `data.cached_node_ids` / `data.executed_node_ids` | Present on `--wait` | Absent — they are derived from the per-node event stream, which the cloud has none of |\n| Envelope `data.warnings` | Absent | Present on `--wait` success: an array of non-fatal warning objects (currently only `partial_execution`, see below). `[]` when there are none |\n| `prompt_rejected` `details` | `status` (400) and `node_errors` | `node_errors` only — the cloud reports rejected nodes on an otherwise-2xx submit, so there is no 4xx status to report. The `node_errors` value has the same [array-of-records shape](#node_errors-shape) on both targets |\n| Error codes | The local set below | The workflow/pre-flight codes and the node-failure codes (`execution_error`, `transient_auth`, `prompt_rejected`, `cancelled`, `spend_consent_required`) plus the cloud-only codes below. The local-server- and WebSocket-specific codes cannot occur: `server_not_running`, `object_info_unavailable`, `connection_error`, `ws_timeout`, `ws_disconnected`, `invalid_response`, `client_error`, `server_error`, `partner_node_requires_credential` (the cloud injects the caller's credential itself) |\n\nEverything not in that table is the same on both targets, including\n`converted`, `prompt_preview`, the `queued` field set, `data.status`,\n`data.prompt_id` / `client_id` / `outputs` / `outputs_by_node` /\n`outputs_by_item` / `state_file` / `watcher_spawned` / `elapsed_seconds`, and\nthe `--print-prompt` and `--no-wait` stream shapes." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-per-target-differences-cloud-only-error-codes", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Per-target differences", + "Cloud-only error codes" + ], + "source": "docs/json-output.md", + "source_line": 178, + "content": "| `code` | Triggered when | `details` | Exit |\n| -------------------- | ------------------------------------------------------------------ | -------------------------------- | ---- |\n| `cloud_unauthorized` | No usable cloud session, or the session was rejected — run `comfy cloud login` | — | 1 |\n| `cloud_http_error` | The cloud API returned a non-2xx response on submit or while polling | `status` (int), `body` (str) on submit; `status`, `prompt_id` while polling | 1 |\n| `cloud_rate_limited` | The cloud API throttled the request (HTTP 429) on submit or while polling. Throttling is not a verdict on the workflow, but it does not by itself prove the submit had no effect, and the CLI never repeats a submit on its own. On submit, wait, then check `comfy jobs ls --where cloud` for the job before re-running; while polling, the job was already submitted, so follow it with `comfy jobs watch --where cloud` instead of re-running (the job record is left non-terminal). Cloud only: a local server's 429 is `client_error` | same as `cloud_http_error`, plus `retry_after` (seconds) when the server sent `Retry-After` | 1 |\n| `cloud_payment_required` | The cloud refused the request because the account's plan does not allow it (HTTP 402, or a legacy HTTP 429 whose body type is a plan refusal: free generations used up, subscription required, a partner node or model that needs a paid plan). Not throttling and not a workflow problem; nothing was queued, so do not retry or edit the workflow. A full queue stays `cloud_rate_limited` | `status` (402 or 429), `body` (str), `reason` (the server's refusal type, when it sent one) | 1 |\n| `cloud_timeout` | The cloud job produced no progress for `--timeout` seconds | `prompt_id` (str) | 1 |\n| `cql_no_graph` | A UI-format workflow needs the cloud `object_info` snapshot to be lowered to API format, and it could not be loaded — run `comfy nodes refresh --where cloud` | — | 1 |\n\nAll of these are registered in `comfy_cli/error_codes.py` and listed by\n`comfy --json discover`, exactly like the local codes." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-per-target-differences-partial_execution-warning", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Per-target differences", + "`partial_execution` warning" + ], + "source": "docs/json-output.md", + "source_line": 192, + "content": "The cloud prunes workflow branches that fail server-side validation and still\nreports the job as completed. On a `--wait` success the CLI diffs the output\nnodes it submitted against the ones that returned outputs and, when some are\nmissing, appends a warning object to `data.warnings` rather than passing the\nrun off as a clean success:\n\n```json\n{\"code\": \"partial_execution\", \"message\": \"submitted 2 output node(s) but the cloud returned outputs for only 1; 1 branch(es) were pruned server-side (likely failed validation) and produced nothing\", \"submitted_output_nodes\": 2, \"returned_output_nodes\": 1}\n```\n\nThe envelope is still `ok: true` (exit `0`) — the job did run. Agents that\nneed all-or-nothing semantics should check `data.warnings` is empty." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-event-reference", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Event reference" + ], + "source": "docs/json-output.md", + "source_line": 207, + "content": "| `type` | When |\n| ------------------ | ---------------------------------------------------- |\n| `converted` | UI-format workflow was client-side converted |\n| `prompt_preview` | The API-format workflow graph about to be submitted |\n| `queued` | Server accepted the prompt (HTTP 200 on `/prompt`) |\n| `execution_cached` | Node hit the execution cache and was skipped |\n| `executing` | Node started execution |\n| `progress` | In-flight progress update for the running node |\n| `executed` | Node finished and reported its outputs |\n| `output` | One file-like output became available (`url`) |\n| `execution_error` | Server reported a node exception (error envelope follows) |\n| `login_url` | `comfy cloud login`: OAuth authorize URL, before the browser-callback wait |\n\nAgents must ignore events whose `type` they do not recognise — new event\nkinds may be added in a backward-compatible manner. Agents must ignore\nunknown fields on known events for the same reason.\n\nA handful of fields carry values from a server-defined open set rather\nthan a fixed enumeration: `class_type`, `category`, `type` (output folder),\nand `exception_type`. Agents must accept and pass through unknown values\nwithout keying behaviour on specific strings.\n\nEvery per-node event also carries a `title` field — the human-readable\nlabel to show in a per-node UI: **`_meta.title` if present, else\n`class_type`, else the node id**." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-event-reference-converted", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Event reference", + "`converted`" + ], + "source": "docs/json-output.md", + "source_line": 235, + "content": "Emitted once if the input workflow was in UI format and was converted to\nAPI format client-side.\n\n```json\n{\"schema\": \"event/1\", \"type\": \"converted\", \"node_count\": 2}\n```" + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-event-reference-prompt_preview", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Event reference", + "`prompt_preview`" + ], + "source": "docs/json-output.md", + "source_line": 244, + "content": "Emitted once the workflow has been successfully loaded, parsed, and (if\nUI-format) converted — i.e., in every stream except the **Failure\npre-flight** archetype. Carries the API-format workflow graph the CLI is\nabout to POST to `/prompt` — the same dict that would land in the\nrequest's `prompt` field. It does **not** include `client_id` or\n`extra_data` (so any `--api-key` value never appears here).\n\nUnder `--print-prompt` this is the only event: the CLI emits it plus the\nfinal envelope and exits 0 without queuing.\n\n```json\n{\"schema\": \"event/1\", \"type\": \"prompt_preview\", \"prompt\": {\"1\": {\"class_type\": \"EmptyLatentImage\", \"inputs\": {\"width\": 512, \"height\": 512, \"batch_size\": 1}}}}\n```" + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-event-reference-queued", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Event reference", + "`queued`" + ], + "source": "docs/json-output.md", + "source_line": 260, + "content": "Emitted after the submit request returns success — `POST /prompt` returning\n200 locally, the equivalent cloud submit under `--where cloud` — **and** after\nthe job's state file has been persisted.\n\n```json\n{\n \"schema\": \"event/1\",\n \"type\": \"queued\",\n \"prompt_id\": \"9b1c…\",\n \"client_id\": \"fe2a…\",\n \"validation_warnings\": [],\n \"nodes\": [\n {\"node_id\": \"1\", \"class_type\": \"GeminiNanoBanana2\", \"title\": \"Nano Banana 2\"},\n {\"node_id\": \"2\", \"class_type\": \"SaveImage\", \"title\": \"Save Image\"}\n ]\n}\n```\n\n| Field | Type | Description |\n| --------------------- | ------------- | ------------------------------------------------------ |\n| `prompt_id` | str | Server-assigned prompt UUID |\n| `client_id` | str | Client-generated UUID (sent with `/prompt`) |\n| `validation_warnings` | array of dict | Per-node validation issues ComfyUI reported alongside a successful queue (some output chains validated, others didn't). Same record shape as `prompt_rejected`'s `details.node_errors` (see [shape](#node_errors-shape)). Empty (`[]`) in the common case. |\n| `nodes` | array of dict | Manifest of every node in the submitted (post-conversion) workflow: `node_id` (str), `class_type` (str), `title` (str). Lets piped consumers render a per-node UI without the workflow file. |\n| `base_url` | str | **Cloud only.** The cloud endpoint the prompt was submitted to. Absent on `--where local`. |\n\n`queued` is emitted **after** the submit call returns successfully **and after\nthe job's state file has been persisted** — on the async (`--no-wait`) paths,\nafter the background watcher spawn attempt too. On both targets it therefore\nmeans more than \"the server has the prompt\": the durable record exists, so a\nconsumer may run `comfy jobs status ` — or expect the job in\n`comfy jobs ls` — the moment it reads this line. A run whose submit fails emits\nits error envelope with no `queued` line at all." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-event-reference-executing", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Event reference", + "`executing`" + ], + "source": "docs/json-output.md", + "source_line": 296, + "content": "Emitted when a node starts execution. Two consecutive `executing` events\nwith different `node` values are normal (intermediate compute nodes whose\noutputs aren't published to the client never fire `executed`); agents that\ntrack a \"current node\" should treat a new `executing` as implicitly\nclosing the previous one.\n\n```json\n{\"schema\": \"event/1\", \"type\": \"executing\", \"node\": \"2\", \"title\": \"Save Image\", \"class_type\": \"SaveImage\", \"prompt_id\": \"9b1c…\"}\n```" + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-event-reference-execution_cached", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Event reference", + "`execution_cached`" + ], + "source": "docs/json-output.md", + "source_line": 308, + "content": "One event per node whose outputs were retrieved from the execution cache\n(from ComfyUI's `execution_cached` websocket message). Same fields as\n`executing`. A cached output-bearing node (e.g., a cached `SaveImage`)\nmay emit both `execution_cached` AND `executed`." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-event-reference-progress", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Event reference", + "`progress`" + ], + "source": "docs/json-output.md", + "source_line": 315, + "content": "Per-step progress for samplers, video encoders, and any node that calls\n`ProgressBar.update_absolute(...)`. Throttled to ~10 events/second per\nnode. Same field names as the `comfy jobs watch` stream.\n\n```json\n{\"schema\": \"event/1\", \"type\": \"progress\", \"node\": \"1\", \"completed\": 14, \"total\": 30, \"prompt_id\": \"9b1c…\"}\n```\n\nSome custom nodes may emit `completed > total` near the end of execution;\nagents rendering a progress bar should clamp." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-event-reference-executed", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Event reference", + "`executed`" + ], + "source": "docs/json-output.md", + "source_line": 328, + "content": "Emitted when the server reports node completion via its `executed`\nwebsocket message. **Not guaranteed for every executed node** —\nintermediate compute nodes that don't surface output to the client may\nfinish without it.\n\n```json\n{\n \"schema\": \"event/1\",\n \"type\": \"executed\",\n \"node\": \"2\",\n \"title\": \"Save Image\",\n \"class_type\": \"SaveImage\",\n \"outputs\": [\n {\n \"category\": \"images\",\n \"node_id\": \"2\",\n \"class_type\": \"SaveImage\",\n \"title\": \"Save Image\",\n \"filename\": \"banana_test_00001_.png\",\n \"subfolder\": \"\",\n \"type\": \"output\",\n \"url\": \"http://127.0.0.1:8188/view?filename=banana_test_00001_.png&subfolder=&type=output\"\n }\n ],\n \"prompt_id\": \"9b1c…\"\n}\n```\n\n`outputs` is populated by iterating each key in ComfyUI's\n`executed.output` dict and emitting any item that matches the\nfile-record shape (a dict containing a `filename` key). Items that are\nnot file-record-shaped (strings, booleans, mixed lists from nodes that\npublish non-file data like text predictions or animation flags) are\nsilently skipped. See [Output object](#output-object)." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-event-reference-output", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Event reference", + "`output`" + ], + "source": "docs/json-output.md", + "source_line": 365, + "content": "One event per newly seen file-like output, emitted right after the\n`executed` event that produced it. `url` is the contractual way to fetch\nthe bytes (it points at ComfyUI's `/view` endpoint); on a local loopback\nrun with a resolvable workspace it may instead be an absolute local file\npath — treat any non-`http(s)` value as a filesystem path.\n\n```json\n{\"schema\": \"event/1\", \"type\": \"output\", \"url\": \"http://127.0.0.1:8188/view?filename=banana_test_00001_.png&subfolder=&type=output\", \"prompt_id\": \"9b1c…\"}\n```" + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-event-reference-execution_error", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Event reference", + "`execution_error`" + ], + "source": "docs/json-output.md", + "source_line": 377, + "content": "Diagnostic event carrying the raw server payload when a node raises\nduring execution. The terminal error envelope (`error.code:\n\"execution_error\"`) follows immediately; agents can dispatch on the\nenvelope alone.\n\n```json\n{\"schema\": \"event/1\", \"type\": \"execution_error\", \"prompt_id\": \"9b1c…\", \"details\": {\"node_id\": \"1\", \"exception_message\": \"API key invalid\", \"...\": \"...\"}}\n```" + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-event-reference-login_url", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Event reference", + "`login_url`" + ], + "source": "docs/json-output.md", + "source_line": 388, + "content": "Emitted by `comfy cloud login` under `--json`/`--json-stream` — this event is\npart of the sign-in stream, not the `run` stream. It carries the OAuth\nauthorize URL as soon as it is built, and is flushed **before** the command\nblocks (up to `timeout_s` seconds) waiting for the loopback browser callback,\nso a parent process driving login headlessly can open (or forward) `url` in\ntime. If the callback never arrives, the terminal envelope is an\n`oauth_timeout` error; on success it is the login envelope (`data.action:\n\"login\"`, `data.session` with tokens redacted).\n\n```json\n{\"schema\": \"event/1\", \"type\": \"login_url\", \"url\": \"https://api.comfy.org/oauth/authorize?...\", \"timeout_s\": 300}\n```" + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-event-reference-upload_plan-upload_progress-upload_complete", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Event reference", + "`upload_plan`, `upload_progress`, `upload_complete`" + ], + "source": "docs/json-output.md", + "source_line": 403, + "content": "Emitted by `comfy build push` while it uploads model files and packaged custom\nnodes. They are part of the push, not the `run` stream, and validate against\n`build_push_event.json`.\n\nWhere they go depends on the mode. Under `--json-stream` they are on stdout,\nahead of the envelope, like every other event. Under plain `--json` (which is\nwhat a caller with a piped stdout resolves to, so every agent) they are on\n**stderr**, because stdout in that mode is exactly one envelope. Read stderr line\nby line and keep the lines that parse as JSON with `schema: \"event/1\"`.\n\nA push opens with one `upload_plan`, sent before the first byte and sent even\nwhen there is nothing to upload. Each file that transfers gets an\n`upload_progress` as it starts and about every two seconds after, then one\n`upload_complete`. A file the builder already held gets only an\n`upload_complete` with `deduplicated: true`. A file whose upload fails gets no\n`upload_complete`; the error envelope is the next line.\n\n```json\n{\"schema\": \"event/1\", \"type\": \"upload_plan\", \"files\": 3, \"bytes_total\": 56908316672, \"already_held\": 2}\n{\"schema\": \"event/1\", \"type\": \"upload_progress\", \"file\": \"model.safetensors\", \"kind\": \"model\", \"index\": 1, \"of\": 3, \"bytes_done\": 1288490188, \"bytes_total\": 23761671782, \"bytes_per_second\": 47500000, \"eta_seconds\": 473, \"overall_bytes_done\": 1288490188, \"overall_bytes_total\": 56908316672, \"overall_eta_seconds\": 1171}\n{\"schema\": \"event/1\", \"type\": \"upload_complete\", \"file\": \"model.safetensors\", \"kind\": \"model\", \"index\": 1, \"of\": 3, \"bytes_total\": 23761671782, \"seconds\": 498.2, \"bytes_per_second\": 47695045, \"deduplicated\": false, \"overall_bytes_done\": 23761671782, \"overall_bytes_total\": 56908316672}\n```\n\n`bytes_per_second` on a progress event is measured over the last ten seconds\nand is sampled on a timer, not on bytes moving, so a stalled connection keeps\nreporting and its rate falls to `0` with `eta_seconds: null`. That is how to\ntell a slow upload from a dead one. `bytes_done` counts bytes handed to the\nconnection, which runs slightly ahead of bytes the server has acknowledged.\n\nAt a terminal the same numbers render as one redrawn progress line; with output\npiped under `--no-json` they are plain lines every five seconds, with no\ncarriage returns." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-event-reference-deploy_progress", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Event reference", + "`deploy_progress`" + ], + "source": "docs/json-output.md", + "source_line": 437, + "content": "Emitted by `comfy deploy up --watch` and `comfy deploy status --watch` while the\ndeployment's status is `provisioning` or `starting`. It is part of those\ncommands, not the `run` stream, and validates against\n`deploy_progress_event.json`.\n\nWhere it goes depends on the mode, the same way upload progress does. Under\n`--json-stream` it is on stdout, ahead of the envelope. Under plain `--json`\n(what a caller with a piped stdout resolves to, so every agent) it is on\n**stderr**, because stdout in that mode is exactly one envelope.\n\n```json\n{\"schema\": \"event/1\", \"type\": \"deploy_progress\", \"deployment_id\": \"dep-7edc1262\", \"status\": \"provisioning\", \"stale\": false, \"progress\": {\"step\": \"staging_models\", \"modelsDone\": 0, \"modelsTotal\": 2, \"bytesDone\": 3536540667, \"bytesTotal\": 7272719498, \"currentModel\": \"models/checkpoints/sd_xl_base_1.0.safetensors\", \"bytesPerSecond\": 44205525, \"etaSeconds\": 85, \"attempt\": 1, \"startedAt\": \"2026-09-20T01:59:55Z\", \"updatedAt\": \"2026-09-20T02:01:15Z\"}}\n{\"schema\": \"event/1\", \"type\": \"deploy_progress\", \"deployment_id\": \"dep-7edc1262\", \"status\": \"starting\", \"stale\": false, \"progress\": {\"step\": \"waiting_for_worker\", \"attempt\": 1, \"startedAt\": \"2026-09-20T02:02:46Z\", \"updatedAt\": \"2026-09-20T02:02:46Z\"}}\n```\n\nThe event's own fields are snake_case like every other event. `progress` is the\ndeploy service's object, passed through unchanged, so its fields are the API's\ncamelCase, the same as `computeConfig` and `endpointUrl` in the envelopes. The\nservice computes `bytesPerSecond` and `etaSeconds`; the CLI computes nothing, so\nthe portal and the CLI show the same numbers.\n\nOne event per new sample: the CLI polls every two seconds and the service writes\nabout every three, and a sample is keyed on its `updatedAt` (on its whole content\nwhere a sample carries no `updatedAt`). If a sample then goes\na minute without being rewritten, one more event carries it with `stale: true`.\nThe service's writes are best-effort, so a stale sample is not evidence that the\ndeploy stopped; `status` remains the verdict. A service that sends no `progress`\nobject produces no events, and the command behaves as it did before.\n\n`comfy deploy status --json` (with or without `--watch`) and `comfy deploy up\n--json` carry the same object as `data.progress` while the deployment is coming\nup, and omit the key otherwise.\n\nAt a terminal the numbers render as one redrawn progress line; with output piped\nunder `--no-json` they are plain lines, one per new sample, with no carriage\nreturns. Ctrl-C during `--watch` exits 130 after printing that the deployment\nkeeps coming up and the command that re-attaches, and in the JSON modes still\nwrites the envelope for the last state it read.\n\nA watch rides out a deploy API that stops answering, as it does for a few\nseconds while a new version rolls out: a 5xx or a failed connection on its read\nis retried, backing off (2, 4, 8, then 15 seconds), for about a minute from the\nfirst failure, and the watch says once that it is retrying. A 4xx still ends the\nwatch at once. If the API is still not answering when the window closes, the\nwatch ends with the error code `deploy_watch_lost` and exit code **75**, never 1:\nonly the watch ended, and the deployment may still be coming up. Its `hint`\ncarries the command that re-attaches and `details.deployment_id` the deployment." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-success-envelope", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Success envelope" + ], + "source": "docs/json-output.md", + "source_line": 487, + "content": "On `--wait` success, `data` carries:\n\n| Field | Type | Description |\n| ------------------- | --------------- | ------------------------------------------------------ |\n| `workflow` | str | Absolute path of the submitted workflow file |\n| `status` | str | `\"completed\"` (`\"queued\"` without `--wait`; `\"preview\"` under `--print-prompt`) |\n| `prompt_id` | str | Server-assigned prompt UUID |\n| `client_id` | str | Client-generated UUID |\n| `outputs` | array of str | URL (or local path) per file-like output, deduplicated |\n| `outputs_by_node` | dict | The same outputs grouped by the node id that produced them |\n| `outputs_by_item` | dict | The same outputs grouped by `compose` foreach item; `{}` when the workflow carried no item map |\n| `cached_node_ids` | array of str | **Local only.** Node IDs the server reported as cached |\n| `executed_node_ids` | array of str | **Local only.** Node IDs the executor *ran* — the union of every node that appeared in an `executing` or `executed` event, including intermediate compute nodes |\n| `warnings` | array of dict | **Cloud only.** Non-fatal warnings about the completed run — see [`partial_execution`](#partial_execution-warning). `[]` when there are none |\n| `elapsed_seconds` | float \\| null | Wall-clock duration (null when not waiting) |\n| `host` / `port` | str / int | **Local only.** Target server |\n| `base_url` | str | **Cloud only.** Target cloud endpoint |\n| `state_file` | str \\| null | Path of the job state file (poll with `comfy jobs status`) |\n\n`cached_node_ids` and `executed_node_ids` may overlap: a cached\noutput-bearing node emits both `execution_cached` and `executed`. Agents\nwanting \"ran fresh, not from cache\" should compute\n`set(executed_node_ids) - set(cached_node_ids)`. Both are derived from the\nper-node event stream and so are local-only — see\n[Per-target differences](#per-target-differences).\n\nWithout `--wait` (the default), the stream ends at the `queued` envelope\n(`data.status: \"queued\"`, `data.watcher_spawned: bool`) and a detached\nwatcher keeps the state file updated; follow up with\n`comfy jobs watch ` or `comfy jobs status `. This is\nthe same on both targets, `watcher_spawned` included (add `--where cloud` to\nthe follow-up commands for a cloud job). The async envelope carries no\n`outputs_by_node` / `outputs_by_item` / `warnings` — nothing has run yet." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-success-envelope-known-limit---wait-has-no-background-watcher", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Success envelope", + "Known limit: `--wait` has no background watcher" + ], + "source": "docs/json-output.md", + "source_line": 523, + "content": "`--wait` writes the job's state file at submit and finalizes it in the\nforeground — it does **not** spawn the detached watcher the async path does\n(`data.watcher_spawned` is an async-path field only). Every ordinary outcome is\nstill recorded: a node failure, a cancel, and a lost connection to a dying\nserver all run through the foreground handlers, which write `error.code`\n(the classified execution verdict or `execution_error`; `cancelled`;\n`server_died`) before exiting.\n\nA `--wait` process that is **killed from outside** — a caller-imposed timeout\n(`SIGKILL`/`SIGTERM` on the process group), a terminal going away, the OS\nreaping the CLI alongside the server — runs no handler, so the state file is\nleft at its submit-time `running`. To cover that, `--wait` (local and cloud)\nstamps its own `watcher_pid` (+ start time) on the submit-time record: the next\n`jobs ls` finds a non-terminal record whose recorded pid is dead, and its\nstale-watcher reap finalizes the job as `error` with `error_code:\n\"watcher_crashed\"` — the same treatment a crashed background watcher gets — and\n`jobs ls --orphaned` lists it. The stamp is dropped again on the exits where\nthe job may genuinely still be alive on the server, so the reap can't claim a\ncrash the CLI hasn't established: when local `--wait` gives up on its *own*\n`--timeout` (`ws_timeout`), and when cloud `--wait` dies on a network error\nthat escapes its handlers (a DNS failure or connection reset while polling, as\nopposed to the handled `cloud_timeout` / `cloud_unauthorized` /\n`cloud_http_error` exits, which record a terminal verdict of their own), or\nwhen cloud `--wait` gives up on a throttled status poll (`cloud_rate_limited`,\nrecorded as the record's `error` until the next successful status poll). In\nboth cases the record is left non-terminal with no pid, the reap never touches\nit, and `comfy jobs status ` can still consult the server for the\nreal outcome.\n\nThe reap itself never overwrites a verdict that landed first: it re-reads each\nrecord under that record's lock before rewriting it, so a `--wait` run\nfinishing normally in the same instant keeps its `completed` status and its\noutputs.\n\nWhat the reap cannot tell you is *why* the process died, or what happened to the\njob afterwards — `watcher_crashed` records the watcher's death, not the job's\noutcome. **For runs that may outlive the caller's patience, submit without\n`--wait`** — the async path spawns a watcher that survives the parent (its own\nsession/process group), and it is the watcher that writes `server_died` when the\nserver disappears mid-job. `comfy jobs ls` then reports both the status and the\n`error_code`.\n\nA watcher is deliberately *not* spawned on `--wait`: it would put a second,\nindependent writer on the state file the foreground already finalizes, add a\nsecond server connection per foreground run, and leave a background process\nbehind after a synchronous command returns — a real regression on the common\npath in exchange for a case the async path already covers." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-comfy-validate---json-envelope", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "`comfy validate --json` envelope" + ], + "source": "docs/json-output.md", + "source_line": 573, + "content": "`comfy validate --workflow --json` checks a workflow without submitting\nit and emits a single envelope (no event stream). On a valid workflow `ok` is\n`true` and `data` carries:\n\n| Field | Type | Description |\n| ---------------------- | ------------- | ----------------------------------------------------------------------------------------------- |\n| `workflow` | str | Absolute path of the validated workflow file |\n| `valid` | bool | Whether the graph passed validation (also the envelope `ok`) |\n| `error_count` | number | Number of entries in `errors` |\n| `warning_count` | number | Number of entries in `warnings` |\n| `errors` | array of dict | Per-node validation errors (empty when `valid`) |\n| `warnings` | array of dict | Non-fatal validation warnings |\n| `partner_nodes` | array of str | Sorted class_types in the workflow that are partner-API (paid) nodes. **Always present**; `[]` when none |\n| `spends_credits` | bool | `true` iff `partner_nodes` is non-empty — a convenience flag for \"will this workflow spend Comfy credits?\" |\n| `converted_from_ui` | bool | Present and `true` only when the input was a UI export that was lowered to API format before validating |\n| `converted_node_count` | number | Present only alongside `converted_from_ui`: node count of the converted graph |\n\n`partner_nodes` / `spends_credits` are **informational only** — they never\nchange validate's exit code (validate stays advisory; the credit-spend gate\nlives in `comfy run`). Detection is the same authoritative `api_node: true`\nflag (with a `partner/...` category fallback) that `comfy run` uses, run over\nthe loaded `object_info`; in offline `--input` mode where the `object_info`\nlacks `api_node` flags the list is simply empty (fail-open). When\n`spends_credits` is `true`, pretty (non-`--json`) mode also prints a yellow\n`⚠ uses partner-API (paid) nodes …` line after the verdict.\n\nInvalid workflows emit `ok: false` with the same `data` fields (`valid: false`,\na populated `errors` array, `partner_nodes`/`spends_credits` still present) and\nexit code `1`. Structural failures (missing file, non-object JSON, an\nunconvertible UI export) emit an [error object](#error-object) instead." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-error-object", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Error object" + ], + "source": "docs/json-output.md", + "source_line": 606, + "content": "Every failure envelope carries:\n\n| Field | Type | Description |\n| --------- | ------------ | -------------------------------------------------------------------------- |\n| `code` | str | Registered discriminator — see [Error codes](#error-codes); the full registry is in `comfy --json discover` under `data.error_codes` |\n| `message` | str | Human-readable summary. For display only — dispatch on `code` |\n| `hint` | str \\| null | Suggested next action |\n| `details` | dict \\| null | Per-code structured extras (documented below) |" + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-error-codes", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Error codes" + ], + "source": "docs/json-output.md", + "source_line": 617, + "content": "Codes raised by `comfy run` against a local server, with their `details`\npayloads. All of them are registered in `comfy_cli/error_codes.py` (the\nregistry test enforces this) and surfaced by `comfy discover`. For\n`--where cloud`, see [Cloud-only error codes](#cloud-only-error-codes) — it\nlists what the cloud adds and which of the codes below cannot occur there.\n\n| `code` | Triggered when | `details` | Exit |\n| ------------------------- | ------------------------------------------------------------------------------- | -------------------------------------------------- | ---- |\n| `workflow_not_found` | `--workflow` path does not exist | — | 1 |\n| `workflow_invalid_json` | Workflow file is not valid JSON | — | 1 |\n| `workflow_read_error` | Workflow file exists but isn't readable as text (`OSError`, `UnicodeDecodeError`) | — | 1 |\n| `workflow_not_api_format` | File parses but is neither UI nor API format | — | 1 |\n| `workflow_empty` | Workflow has no executable nodes (UI conversion produced `{}`, or API workflow is `{}`) | — | 1 |\n| `conversion_error` | UI→API converter raised `WorkflowConversionError` | — | 1 |\n| `conversion_crash` | UI→API converter raised an unexpected exception | `exception_type` (str) | 1 |\n| `server_not_running` | Pre-flight probe found no ComfyUI on host:port | `host` (str), `port` (int) | 1 |\n| `object_info_unavailable` | `/object_info` returned an HTTP error, or HTTP 200 with an unparseable body | `status` (int), `body` (str) | 1 |\n| `connection_error` | Server unreachable mid-flow: `URLError`, `TimeoutError`, or other `OSError` (including on `/object_info`) | — | 1 |\n| `workflow_unknown_nodes` | Pre-submit validation found unknown class_types / shape mismatches | `errors` (array), `warnings` (array) | 1 |\n| `partner_node_requires_credential` | Workflow uses a partner-API node and no `api_key_comfy_org` credential is available | `partner_nodes` (array of str, capped at 20 entries × 64 chars each), `partner_node_count` (int, the exact total — read this, not `len(partner_nodes)`), `host`, `port` | 1 |\n| `spend_consent_required` | Workflow embeds partner-API (paid) nodes and `--allow-spend` was not passed (machine mode) or interactive consent was declined; re-run with `--allow-spend`. Free (non-partner) workflows are unaffected. | `partner_nodes` (array of str, capped at 20 entries × 64 chars each), `partner_node_count` (int, the exact total — read this, not `len(partner_nodes)`); local path also carries `host`, `port`, the cloud path carries `where: \"cloud\"` | 1 |\n| `prompt_rejected` | Server returned HTTP 400 with `node_errors` | `status` (400), `node_errors` (array — [shape](#node_errors-shape)) | 1 |\n| `client_error` | Server returned another HTTP 4xx response (including 429; `cloud_rate_limited` is Cloud only) | `status` (int, 4xx), `body` (str) | 1 |\n| `server_error` | Server returned an HTTP 5xx response | `status` (int, 5xx), `body` (str) | 1 |\n| `invalid_response` | Server returned HTTP 2xx but body was unparseable or lacked `prompt_id` | `status` (int, 2xx) | 1 |\n| `ws_timeout` | WebSocket `recv` idle past `--timeout` | `timeout` (int, seconds) | 1 |\n| `ws_disconnected` | WebSocket connection dropped mid-execution | — | 1 |\n| `cancelled` | Run was interrupted — client `SIGINT` (Ctrl-C) or the server's `execution_interrupted` (e.g. `/interrupt`) | — | 130 |\n| `execution_error` | A node raised during execution (server emitted `execution_error`) | `node_id` (str), `class_type` (str), `title` (str), `exception_type` (str), `traceback` (str) | 1 |\n| `transient_auth` | The `execution_error` cause was an API node's server-side session token expiring mid-execution — transient, so resubmitting the same workflow succeeds. Local credentials are fine; `comfy cloud login` does not help | Same fields as `execution_error` | 1 |" + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-error-codes-cli-wide-codes", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Error codes", + "CLI-wide codes" + ], + "source": "docs/json-output.md", + "source_line": 650, + "content": "Two codes can end any command's `--json` stream, not only `comfy run`:\n\n| `code` | Triggered when | `details` | Exit |\n| ---------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ---- |\n| `usage_error` | argv did not parse (unknown option or command, missing value); nothing ran | `command` (str), `exit_code` (int); `option` and `did_you_mean` for a near-miss option | 2 |\n| `internal_error` | The command crashed on an exception it did not handle (a comfy-cli bug) | `exception` (str, the exception type), `command` (str), `traceback` (array of up to 3 `file:line:func` strings, innermost last) | 1 |\n\n`internal_error`'s `message` is `\": \"`, capped at 500 characters.\nURL query strings, bearer tokens, `key=value` token pairs and `user:pass@`\nuserinfo are replaced with `***`. The full traceback still goes to stderr.\nWhether anything was written depends on where the command crashed, so re-read\nstate before retrying." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-error-codes-workflow-edit-refusal-fields", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Error codes", + "Workflow-edit refusal fields" + ], + "source": "docs/json-output.md", + "source_line": 665, + "content": "`workflow set-widget` / `set-slot` / `ls-nodes` add these fields for agents:\n\n| Where | Field | Meaning |\n| ----- | ----- | ------- |\n| `unknown_enum_value` finding (the `set-widget` error's `details`, `validate` findings) | `best_match` (str, optional) | The ONE option sharing the rejected value's leading token (`'16:9 (Landscape)'` → `'16:9 (Widescreen)'`). It is also first in `did_you_mean`. It is never auto-applied, and is absent for filenames and ambiguous tokens |\n| `unknown_dynamic_sub_input` warning (`set-slot`) | `revealed_by` (array of str, optional) | The options of the dynamic combo that reveal the requested sub-widget (`model.prompt_expansion_mode` → `[\"MiniMax H3 Max\", \"MiniMax H3 Max Turbo\"]`). Set the selector to one of them first |\n| `workflow ls-nodes` rows | `ui_only` (true, optional) | A frontend-only node (Reroute, Note, MarkdownNote, PrimitiveNode, GetNode, SetNode). It is readable on the canvas but cannot be added with `add-node` or shown with `nodes show` |\n| `workflow ls-nodes` rows | `subgraph` (true, optional) | A subgraph instance: its `type` is the definition uuid, not a node class |" + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-error-codes-exception_type-field", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Error codes", + "`exception_type` field" + ], + "source": "docs/json-output.md", + "source_line": 676, + "content": "Provided for diagnostic and observability purposes (e.g., metrics\nbucketing). **Open set** — the format is whatever ComfyUI sends,\ntypically the bare class name for builtins (`RuntimeError`,\n`ValueError`) and a dotted module path for non-builtins. May be `\"\"`\nwhen the server omits it. Don't key retry or routing logic on it; use\n`error.code` for coarse dispatch." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-error-codes-traceback-field", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Error codes", + "`traceback` field" + ], + "source": "docs/json-output.md", + "source_line": 685, + "content": "A single multi-line string carrying the formatted stack frames as\nreported by ComfyUI (joined from the server's `traceback.format_tb()`\noutput). It does NOT include the `\"Traceback (most recent call last):\"`\nheader or the final `\"ExceptionType: message\"` summary line. May be\nempty (`\"\"`)." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-error-codes-node_errors-shape", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Error codes", + "`node_errors` shape" + ], + "source": "docs/json-output.md", + "source_line": 693, + "content": "Used for `prompt_rejected`'s `details.node_errors` and for\n`queued.validation_warnings`. The value is an array of self-contained\nrecords, one per affected node. Each record carries `node_id` (str —\nsame identifier as in the per-node events) plus the per-node fields\nComfyUI emits:\n\n```json\n\"node_errors\": [\n {\n \"node_id\": \"1\",\n \"errors\": [\n {\n \"type\": \"value_not_in_list\",\n \"message\": \"Value not in list\",\n \"details\": \"resolution: '5K' not in ['1K','2K','4K']\",\n \"extra_info\": {\"input_name\": \"resolution\", \"received_value\": \"5K\"}\n }\n ],\n \"dependent_outputs\": [\"2\"],\n \"class_type\": \"GeminiNanoBanana2\"\n }\n]\n```\n\nThe inner per-node fields are defined by ComfyUI's `validate_prompt()`\nand may evolve with ComfyUI versions — agents should ignore unknown\nfields. The CLI guarantees only that the outer value is an array of\ndicts, each carrying a `node_id` (str).\n\nIf a server reports a bare value instead of the per-node dict above (e.g.\n`{\"1\": \"missing input\"}`), the CLI does not drop the record — it wraps the\nvalue as `{\"node_id\": \"1\", \"errors\": [\"missing input\"]}` so the count in the\nmessage always matches the array and the diagnostic survives. `errors` items\nare objects in the normal case; treat a non-object item as an opaque message.\n`node_id` is always taken from the payload's own map key, so a server-supplied\n`node_id` field inside a record cannot override it." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-output-object", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Output object" + ], + "source": "docs/json-output.md", + "source_line": 732, + "content": "Entries of `executed.outputs`:\n\n| Field | Type | Description |\n| ------------ | ---- | ---------------------------------------------------------------------------------- |\n| `category` | str | Output category as keyed by ComfyUI's `executed.output` dict. **Open set** (`images`, `audio`, `3d`, `latents`, …) |\n| `node_id` | str | Node that produced the output |\n| `class_type` | str | Node class name |\n| `title` | str | Display label |\n| `filename` | str | Raw filename as reported by the server |\n| `subfolder` | str | Subfolder within the output root. Defaults to `\"\"` |\n| `type` | str | ComfyUI output folder discriminator. **Open set** (`output`, `temp`, `input`). Defaults to `\"output\"` |\n| `url` | str | `http(s)://:/view?...` URL — fetch this to get the bytes |" + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-process-level-termination", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Process-level termination" + ], + "source": "docs/json-output.md", + "source_line": 747, + "content": "The CLI may be terminated by the operating system or a parent process\n(SIGKILL, SIGTERM, OOM-kill, segmentation fault). In these cases the\nenvelope may never be emitted and the stream may be truncated. Agents\nshould treat the run as failed when **both**:\n- the process exit code is non-zero, and\n- the last line on stdout is not a `type: \"envelope\"` line, or stdout is\n empty.\n\nStderr may contain a Python traceback in these cases.\n\nAn exception inside the CLI itself is not one of these. It ends the stream\nwith an [`internal_error`](#cli-wide-codes) envelope." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-examples-successful-run-ui-format-input---wait", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Examples", + "Successful run (UI-format input, `--wait`)" + ], + "source": "docs/json-output.md", + "source_line": 764, + "content": "```json\n{\"schema\":\"event/1\",\"type\":\"converted\",\"node_count\":2}\n{\"schema\":\"event/1\",\"type\":\"prompt_preview\",\"prompt\":{\"1\":{\"class_type\":\"GeminiNanoBanana2\",\"inputs\":{\"prompt\":\"a banana\"},\"_meta\":{\"title\":\"Nano Banana 2\"}},\"2\":{\"class_type\":\"SaveImage\",\"inputs\":{\"filename_prefix\":\"banana_test\",\"images\":[\"1\",0]},\"_meta\":{\"title\":\"Save Image\"}}}}\n{\"schema\":\"event/1\",\"type\":\"queued\",\"prompt_id\":\"9b1c…\",\"client_id\":\"fe2a…\",\"validation_warnings\":[],\"nodes\":[{\"node_id\":\"1\",\"class_type\":\"GeminiNanoBanana2\",\"title\":\"Nano Banana 2\"},{\"node_id\":\"2\",\"class_type\":\"SaveImage\",\"title\":\"Save Image\"}]}\n{\"schema\":\"event/1\",\"type\":\"executing\",\"node\":\"1\",\"title\":\"Nano Banana 2\",\"class_type\":\"GeminiNanoBanana2\",\"prompt_id\":\"9b1c…\"}\n{\"schema\":\"event/1\",\"type\":\"progress\",\"node\":\"1\",\"completed\":4,\"total\":4,\"prompt_id\":\"9b1c…\"}\n{\"schema\":\"event/1\",\"type\":\"executing\",\"node\":\"2\",\"title\":\"Save Image\",\"class_type\":\"SaveImage\",\"prompt_id\":\"9b1c…\"}\n{\"schema\":\"event/1\",\"type\":\"executed\",\"node\":\"2\",\"title\":\"Save Image\",\"class_type\":\"SaveImage\",\"outputs\":[{\"category\":\"images\",\"node_id\":\"2\",\"class_type\":\"SaveImage\",\"title\":\"Save Image\",\"filename\":\"banana_test_00001_.png\",\"subfolder\":\"\",\"type\":\"output\",\"url\":\"http://127.0.0.1:8188/view?filename=banana_test_00001_.png&subfolder=&type=output\"}],\"prompt_id\":\"9b1c…\"}\n{\"schema\":\"event/1\",\"type\":\"output\",\"url\":\"http://127.0.0.1:8188/view?filename=banana_test_00001_.png&subfolder=&type=output\",\"prompt_id\":\"9b1c…\"}\n{\"schema\":\"envelope/1\",\"type\":\"envelope\",\"ok\":true,\"command\":\"run\",\"version\":\"1.6.1\",\"where\":\"local\",\"data\":{\"workflow\":\"/path/wf.json\",\"status\":\"completed\",\"prompt_id\":\"9b1c…\",\"client_id\":\"fe2a…\",\"outputs\":[\"http://127.0.0.1:8188/view?filename=banana_test_00001_.png&subfolder=&type=output\"],\"cached_node_ids\":[],\"executed_node_ids\":[\"1\",\"2\"],\"elapsed_seconds\":8.342,\"host\":\"127.0.0.1\",\"port\":8188,\"state_file\":\"…\"},\"error\":null}\n```\n\nExit code: `0`." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-examples-successful-cloud-run---where-cloud---wait", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Examples", + "Successful cloud run (`--where cloud --wait`)" + ], + "source": "docs/json-output.md", + "source_line": 780, + "content": "Same prefix as the local stream; no per-node events, because the cloud path\npolls for a terminal record instead of streaming a WebSocket session.\n\n```json\n{\"schema\":\"event/1\",\"type\":\"prompt_preview\",\"prompt\":{\"1\":{\"class_type\":\"GeminiNanoBanana2\",\"inputs\":{\"prompt\":\"a banana\"}},\"2\":{\"class_type\":\"SaveImage\",\"inputs\":{\"filename_prefix\":\"banana_test\",\"images\":[\"1\",0]}}}}\n{\"schema\":\"event/1\",\"type\":\"queued\",\"prompt_id\":\"9b1c…\",\"client_id\":\"fe2a…\",\"validation_warnings\":[],\"nodes\":[{\"node_id\":\"1\",\"class_type\":\"GeminiNanoBanana2\",\"title\":\"GeminiNanoBanana2\"},{\"node_id\":\"2\",\"class_type\":\"SaveImage\",\"title\":\"SaveImage\"}],\"base_url\":\"https://api.comfy.org\"}\n{\"schema\":\"envelope/1\",\"type\":\"envelope\",\"ok\":true,\"command\":\"run\",\"version\":\"1.6.1\",\"where\":\"cloud\",\"data\":{\"workflow\":\"/path/wf.json\",\"status\":\"completed\",\"prompt_id\":\"9b1c…\",\"client_id\":\"fe2a…\",\"outputs\":[\"https://…/banana_test_00001_.png\"],\"outputs_by_node\":{\"2\":[\"https://…/banana_test_00001_.png\"]},\"outputs_by_item\":{},\"warnings\":[],\"elapsed_seconds\":21.7,\"base_url\":\"https://api.comfy.org\",\"state_file\":\"…\"},\"error\":null}\n```\n\nExit code: `0`." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-examples-failure-workflow-file-missing", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Examples", + "Failure: workflow file missing" + ], + "source": "docs/json-output.md", + "source_line": 793, + "content": "```json\n{\"schema\":\"envelope/1\",\"type\":\"envelope\",\"ok\":false,\"command\":\"run\",\"version\":\"1.6.1\",\"where\":\"local\",\"data\":null,\"error\":{\"code\":\"workflow_not_found\",\"message\":\"Specified workflow file not found: /tmp/missing.json\",\"hint\":\"check the path; pass the API-format JSON exported from ComfyUI\",\"details\":null}}\n```\n\nExit code: `1`." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-examples-failure-server-returned-validation-errors", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Examples", + "Failure: server returned validation errors" + ], + "source": "docs/json-output.md", + "source_line": 801, + "content": "```json\n{\"schema\":\"event/1\",\"type\":\"prompt_preview\",\"prompt\":{\"…\":\"…\"}}\n{\"schema\":\"envelope/1\",\"type\":\"envelope\",\"ok\":false,\"command\":\"run\",\"version\":\"1.6.1\",\"where\":\"local\",\"data\":null,\"error\":{\"code\":\"prompt_rejected\",\"message\":\"Workflow has 1 validation error(s)\",\"hint\":\"inspect `details.node_errors` and fix the workflow\",\"details\":{\"status\":400,\"node_errors\":[{\"node_id\":\"1\",\"errors\":[{\"type\":\"value_not_in_list\",\"message\":\"Value not in list\",\"details\":\"resolution: '5K' not in ['1K','2K','4K']\"}],\"dependent_outputs\":[\"2\"],\"class_type\":\"GeminiNanoBanana2\"}]}}}\n```\n\nExit code: `1`." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-examples-failure-node-raised-during-execution", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Examples", + "Failure: node raised during execution" + ], + "source": "docs/json-output.md", + "source_line": 810, + "content": "```json\n{\"schema\":\"event/1\",\"type\":\"prompt_preview\",\"prompt\":{\"…\":\"…\"}}\n{\"schema\":\"event/1\",\"type\":\"queued\",\"prompt_id\":\"9b1c…\",\"client_id\":\"fe2a…\",\"validation_warnings\":[],\"nodes\":[{\"…\":\"…\"}]}\n{\"schema\":\"event/1\",\"type\":\"executing\",\"node\":\"1\",\"title\":\"Nano Banana 2\",\"class_type\":\"GeminiNanoBanana2\",\"prompt_id\":\"9b1c…\"}\n{\"schema\":\"event/1\",\"type\":\"execution_error\",\"prompt_id\":\"9b1c…\",\"details\":{\"node_id\":\"1\",\"exception_message\":\"API key invalid\",\"…\":\"…\"}}\n{\"schema\":\"envelope/1\",\"type\":\"envelope\",\"ok\":false,\"command\":\"run\",\"version\":\"1.6.1\",\"where\":\"local\",\"data\":null,\"error\":{\"code\":\"execution_error\",\"message\":\"API key invalid\",\"hint\":\"inspect the per-node fields in details; re-run with `--wait --verbose`\",\"details\":{\"node_id\":\"1\",\"class_type\":\"GeminiNanoBanana2\",\"title\":\"Nano Banana 2\",\"exception_type\":\"RuntimeError\",\"traceback\":\" File \\\"/path/to/node.py\\\", line 42, in execute\\n raise RuntimeError(\\\"API key invalid\\\")\\n\"}}}\n```\n\nExit code: `1`." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-examples-cancellation-ctrl-c-or-server-interrupt", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Examples", + "Cancellation (Ctrl-C or server interrupt)" + ], + "source": "docs/json-output.md", + "source_line": 822, + "content": "```json\n{\"schema\":\"envelope/1\",\"type\":\"envelope\",\"ok\":false,\"command\":\"run\",\"version\":\"1.6.1\",\"where\":\"local\",\"data\":null,\"error\":{\"code\":\"cancelled\",\"message\":\"Cancelled by user\",\"hint\":null,\"details\":null}}\n```\n\nExit code: `130`." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-validating-data-against-the-shipped-schemas", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Validating `data` against the shipped schemas" + ], + "source": "docs/json-output.md", + "source_line": 830, + "content": "The per-command schemas live in `comfy_cli/schemas/`. Most are self-contained,\nbut the five discovery schemas — `templates.json`, `nodes.json`, `models.json`,\n`generate_list.json`, `generate_schema.json` — reference a shared one:\n\n```json\n\"knowledge\": { \"$ref\": \"knowledge_block.json\" }\n```\n\nEach schema carries an `$id` under `https://comfy.org/schemas/`. That namespace\nis an identifier, not a location; nothing is served there. A validator built on\none schema file alone therefore cannot resolve the reference, and validating a\n`templates ls` payload that carries a `knowledge` block fails with\n`Unresolvable: knowledge_block.json` rather than a validation error.\n\nBuild a registry from the whole directory first:\n\n```python\nimport json\nfrom pathlib import Path\n\nimport jsonschema\nfrom referencing import Registry, Resource\n\nSCHEMAS = Path(\"comfy_cli/schemas\") # or wherever you vendored them\nregistry = Registry().with_resources(\n (s[\"$id\"], Resource.from_contents(s))\n for s in (json.loads(p.read_text()) for p in SCHEMAS.glob(\"*.json\"))\n if \"$id\" in s\n)\n\nschema = json.loads((SCHEMAS / \"templates.json\").read_text())\njsonschema.Draft202012Validator(schema, registry=registry).validate(envelope[\"data\"])\n```\n\nAny validator works the same way: load every `*.json` in the directory into\nwhatever the library calls its store, keyed by `$id`. Ship the directory as a\nunit — a single schema file copied out on its own is not self-sufficient." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-stability-what-is-stable", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Stability", + "What is stable" + ], + "source": "docs/json-output.md", + "source_line": 872, + "content": "- The two-schema framing: `event/1` lines + a final `envelope/1` /\n `type: \"envelope\"` line. Bump rule: additive optional fields = no bump;\n rename/remove/retype a field or changed exit semantics = bump.\n- The set of event `type`s listed above and the field names within them.\n- The set of `error.code` values listed above, their registration in the\n error-code registry, and the per-code `details` documented for each.\n- The exit code mapping: `0` on `ok: true`, `130` on `cancelled`, `1` on\n every other failure.\n- The stdout/stderr separation: stdout carries only NDJSON." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-stability-what-may-change-in-a-non-breaking-way", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Stability", + "What may change in a non-breaking way" + ], + "source": "docs/json-output.md", + "source_line": 884, + "content": "- New event types being added (ignore unknown `type` values).\n- New `error.code` values being added (default-handle unknown codes).\n- New optional fields being added to existing events or to `data`\n (ignore unknown fields)." + }, + { + "id": "json-output:comfy-run---json-machine-readable-output-ndjson-legacy-dialect-mapping", + "title": "Machine-readable JSON output", + "headings": [ + "`comfy run --json`: Machine-Readable Output (NDJSON)", + "Legacy dialect mapping" + ], + "source": "docs/json-output.md", + "source_line": 891, + "content": "For consumers migrating from the pre-`event/1` `comfy run --json` dialect\n(removed; was `{\"event\": …, \"schema_version\": 1}` with `error.kind`):\n\n| Legacy event | Current |\n| ---------------- | ------------------------------------------------------------ |\n| `converted` | `type: \"converted\"` |\n| `prompt_preview` | `type: \"prompt_preview\"` |\n| `queued` | `type: \"queued\"` |\n| `node_executing` | `type: \"executing\"` (`node_id` → `node`) |\n| `node_cached` | `type: \"execution_cached\"` (`node_id` → `node`) |\n| `node_progress` | `type: \"progress\"` (`value`/`max` → `completed`/`total`; `class_type`/`title` dropped — read them from the `executing` event) |\n| `node_executed` | `type: \"executed\"` (+ one `output` event per file) |\n| `completed` | envelope `ok: true` (`outputs` → `data.outputs` as URLs; `cached_node_ids` / `executed_node_ids` preserved in `data`) |\n| `failed` | envelope `ok: false` with `error.code` |\n\n| Legacy `error.kind` | Current `error.code` | Exit |\n| -------------------------- | --------------------------- | ---- |\n| `workflow_not_found` | `workflow_not_found` | 1 |\n| `workflow_invalid_json` | `workflow_invalid_json` | 1 |\n| `workflow_read_error` | `workflow_read_error` | 1 |\n| `workflow_format_invalid` | `workflow_not_api_format` | 1 |\n| `workflow_empty` | `workflow_empty` | 1 |\n| `conversion_error` | `conversion_error` | 1 |\n| `conversion_crash` | `conversion_crash` | 1 |\n| `connection_error` (probe) | `server_not_running` | 1 |\n| `connection_error` (network) | `connection_error` | 1 |\n| `object_info_unavailable` | `object_info_unavailable` | 1 |\n| `validation_error` | `prompt_rejected` | 1 |\n| `client_error` | `client_error` | 1 |\n| `server_error` | `server_error` | 1 |\n| `invalid_response` | `invalid_response` | 1 |\n| `timeout` | `ws_timeout` | 1 |\n| `connection_lost` | `ws_disconnected` | 1 |\n| `execution_interrupted` | `cancelled` | 130 (was 1) |\n| `execution_error` | `execution_error` | 1 |\n\nOther framing changes: `schema_version: 1` → `schema: \"event/1\"`;\nper-kind error extras moved under `error.details`; stdout is now UTF-8\n(was ASCII-escaped); `--print-prompt` and `--no-wait` streams now end\nwith an explicit `ok: true` envelope instead of ending at\n`prompt_preview` / `queued`." + }, + { + "id": "comfy:ground-rules-output-contract-the-envelope", + "title": "comfy agent guide", + "headings": [ + "Ground rules", + "Output contract (the envelope)" + ], + "source": "comfy_cli/skills/comfy/SKILL.md", + "source_line": 53, + "content": "Every command emits the same JSON shape:\n\n```json\n{\n \"ok\": true,\n \"command\": \"...\",\n \"version\": \"0.0.0\",\n \"where\": \"local\" | \"cloud\" | null,\n \"data\": { ... },\n \"error\": null | { \"code\": \"...\", \"message\": \"...\", \"hint\": \"...\", \"details\": {...} }\n}\n```\n\nWhen `error` is present, **read the `hint` and act on it**. Don't guess." + }, + { + "id": "comfy:ground-rules-curated-knowledge-data.knowledge", + "title": "comfy agent guide", + "headings": [ + "Ground rules", + "Curated knowledge (`data.knowledge`)" + ], + "source": "comfy_cli/skills/comfy/SKILL.md", + "source_line": 70, + "content": "Discovery commands (`generate schema|list`, `templates ls|show|get`,\n`nodes search|ls`, `models search`) may carry a `knowledge` object inside\n`data`: `models[]` (per-model `status`, `tier`, `route`, `best_for`,\n`pitfalls`, `routing`, `warnings`, `superseded_by`), `picks[]` (ranked\nmodels per capability, rank 1 first), `capabilities_available[]`, and on a\nquery that matched nothing a `nudge`.\nEnrichment reads the cached bundle only, so a turn never waits on a fetch.\n`comfy launch` and `comfy skills install` refresh the cache when it has\nexpired, and `comfy knowledge status` refreshes it on demand. An unfiltered\nlisting carries no `knowledge` key at all: its rows are the whole catalog\nrather than an answer to anything. Five rules:\n\n1. **Which model is a data question.** Ask it before choosing, rather than\n picking a name out of a listing. Run `comfy --json knowledge pick \"\"`; spelling, spacing and phrasing are\n normalized, and a hit is the ranked table with caveats, rank 1 first. Pass\n the phrase as one argument and escape it first: `$(...)`, backticks and `\"`\n still expand inside double quotes, and those words can come from a channel\n you do not control. Do not dodge a miss by listing first. A miss records the\n gap and is still an `ok` envelope: `zero_hit: true`, a `nudge`, and\n `capabilities[]` carrying the ids to retry with. When the user has already\n named a model, run\n `comfy --json knowledge resolve ` instead and build what they asked\n for: rank is a preference, and their request outranks it. Override an\n explicit request only for correctness, where `status: deprecated` plus\n `superseded_by` means say so and use the successor. `knowledge.picks` and\n `knowledge.models` inside `data` carry the same rows whenever a command\n includes them.\n2. **`available_locally: false` means \"not here\", not \"not curated\".** The row\n or pick is still the right answer; this install lacks the templates or nodes\n it resolves to. A row flagged this way also pulls in `picks[]` for the\n capabilities that rank it, so the highest-ranked entry *without* the flag is\n the runnable alternative. Say what is missing, then name that alternative.\n When routing is local, add `--check-local` to `knowledge pick`: it also\n flags an `oss` pick whose model files are missing, with `missing_models`\n counting them, and `comfy --json templates check