diff --git a/.dsh-version.json b/.dsh-version.json index 83d02e4..855c225 100644 --- a/.dsh-version.json +++ b/.dsh-version.json @@ -177,6 +177,29 @@ "NOTHING is vendored, downloaded or installed: the daemon is the user's own service, and this package ships the HTTP client, one argv for `ollama --version`, and the arithmetic" ] }, + "dsh-comfyui": { + "version": "0.1.0-alpha.1", + "rows": [ + "comfyui" + ], + "rowOverrides": [], + "role": "ComfyUI as a surface the agent can BUILD against: seven `comfy_*` tools over the machine's own ComfyUI (Desktop, portable, or a server on loopback) that turn a small readable project spec into a real workflow.json + prompt.json - nodes by KEY, values by NAME, wires by `.`, `@bindings` for anything that belongs to a machine - validate them against the live node catalog the server reports (`/object_info`), with ComfyUI's own error vocabulary (required_input_missing, return_type_mismatch, value_not_in_list, dependency_cycle, prompt_no_outputs), queue them (`/prompt`) and report what came out of `/history`, and a `comfy_test` that compiles the whole shipped example library and, when a server answers, runs it - every item reporting the rung it actually reached (v1-structural, v2-schema, v3-queued, v4-executed), so 'it compiles' is never printed as 'it runs'. `comfy_cli` drives the user's own comfy-cli as a SECOND witness: `comfy run --workflow` converts the generated canvas with comfy-cli's own converter, `comfy node deps-in-workflow` names the node packs a graph needs, `comfy launch --background` / `comfy stop` give a server to test against; it never runs `comfy install`, installs a node, downloads a model or removes anything. Four model-free-or-model-bound examples and six skills (the fundamentals, the two workflow dialects and the `control_after_generate` shift that silently moves every later `widgets_values` entry, the HTTP API with the twelve validation error types, comfy-cli across platforms, authoring a node class, and this project dialect). Host-only: one row, no route, no browser half, zero npm dependencies, no bundled engine, nothing started on its own. See packages/dsh-comfyui/README.md.", + "uses": [ + "@deepseek-ai/dsh-tools (the registry the seven tools are registered into)", + "@deepseek-ai/dsh-skill (ctx.skills, resolved lazily; the six skills are also copied into $DSH_HOME/skills by both installers)", + "the user's own ComfyUI server on loopback (8188, and the Desktop ports 8000-8003, probed in order)", + "the user's own comfy-cli (`comfy`, from `pip install comfy-cli`) for `comfy_cli`, argv-only with a deadline" + ], + "requires": [ + "ComfyUI installed by the user (Desktop, portable or a checkout) - `comfy_status` finds it or names where it looked; nothing here installs one", + "a RUNNING server for /object_info (the full catalog), for comfy_run and for comfy_test action=run; compiling and validating a project need no server at all", + "the model files a graph names for it to run - `comfy_validate` reports a missing one by name and nothing here downloads it", + "comfy-cli only for the comfy_cli tool: without it the seven HTTP tools are unaffected and the tool says so with the install line" + ], + "vendors": [ + "NOTHING is vendored, downloaded or installed: ComfyUI and comfy-cli are the user's own programs, and this package ships the spec compiler, the canvas/prompt reader, the validator, the HTTP client and eighteen core node signatures transcribed from ComfyUI 0.21.1 (with /object_info always overruling them)" + ] + }, "dsh-media": { "version": "0.1.0-alpha.4", "rows": [ diff --git a/.gitignore b/.gitignore index 1709ecc..6a9631a 100644 --- a/.gitignore +++ b/.gitignore @@ -77,6 +77,19 @@ packages/dsh-rust-dev/checks/fixtures/**/target/ # check removes it itself, and this is the belt for the run that is killed. packages/dsh-proto-lab/checks/.tmp/ +# A COMFYUI PROJECT FOLDER (`dsh-comfyui`) is workshop material, the same shape as +# the lab above: `comfy_project` action=new writes `/comfyui//` +# (spec, generated canvas, generated prompt, README, build receipt) for a person to +# edit and run, and a repository that accumulated every graph anyone ever built +# would stop being a plugin pack. What ships is the compiler and the checked example +# library under `packages/dsh-comfyui/examples/`, which IS committed. +# +# Anchored to the repository root, for the reason the `/dsh-diagrams/` rule below +# records: an unanchored `comfyui/` would also match any `comfyui/` inside a package. +# `DSH_COMFYUI_ROOT` points the projects somewhere else entirely; this rule is what +# keeps the DEFAULT location out of every commit. +/comfyui/ + # The vendoring DOWNLOAD CACHE, the same shape as the diagrams rule further down: # `vendor/build.mjs` installs the pinned p5 once into `vendor/node_modules` and # reads two published files out of it. What is committed is the generated @@ -124,3 +137,11 @@ packages/dsh-frontend-craft/vendor/impeccable/.cache/ Thumbs.db .vscode/ .idea/ + +# A DEFENSIVE belt for a plugin that resolves its own cache root from +# `$DSH_HOME`: `dsh-comfyui` caches the node catalog it read from a server under +# `/dsh-comfyui/schema/`, and a run whose environment had no home once wrote +# `/.dsh/...` instead. `lib/client.js` now falls back to the OS home and +# then the temp dir, NEVER the working directory - this rule is the belt for the +# case where a future change or a stripped environment gets it wrong again. +packages/*/.dsh/ diff --git a/AGENTS.md b/AGENTS.md index e497751..e5a3e32 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -131,6 +131,18 @@ for its behaviour, `SECURITY.md` before touching credentials or the launcher, an confirmed pull/delete, embeddings with cosine similarity - three skills whose examples a check parses/compiles, and a loopback fence that refuses a daemon on another machine before any request; host-only, zero npm dependencies), + `dsh-comfyui` (ComfyUI as a surface the agent can BUILD against: seven + `comfy_*` tools that turn a small readable project spec - nodes by key, values + by name, wires by `.`, `@bindings` for anything machine-specific - + into a real `workflow.json` + `prompt.json`, validate it against the server's + own `/object_info` with ComfyUI's own error types, queue it and report what + `/history` says came out, and compile/run the whole shipped example library at + a stated rung - `comfy_status`, `comfy_nodes`, `comfy_project`, + `comfy_validate`, `comfy_run`, `comfy_test`, `comfy_cli` - plus six skills + (the fundamentals, the two workflow dialects and the `control_after_generate` + shift in `widgets_values`, the HTTP API, comfy-cli across platforms, authoring + a node class, this project dialect); host-only, zero npm dependencies, no + bundled engine, and `comfy_cli` never installs anything), `dsh-research` (a run is a folder with a `passport.json` recording the user's own words; nine `rs_*` tools over an append-only claim and source ledger, a claim's numbers recorded as a validated `statistic` rather than left in the prose, a @@ -161,12 +173,12 @@ for its behaviour, `SECURITY.md` before touching credentials or the launcher, an - A package may carry its OWN checks under `packages//checks/`, run with `npm run check` in that folder. They travel with the package (which is what makes them useful outside this repository) and they are ADDITIONAL to - `scripts/checks/`, never a replacement for it: today eleven packages ship their + `scripts/checks/`, never a replacement for it: today twelve packages ship their own (`dsh-supercollider` with four checks, `dsh-research` with seven, `dsh-rust-dev` with two, plus `dsh-diagrams`, `dsh-frontend-craft`, - `dsh-proto-lab`, `dsh-ocr`, `dsh-wsl`, `dsh-docker`, `dsh-ollama` and - `dsh-image-upscale`), and the pack-wide checks still own the routes, the bundle - and the manifest. + `dsh-proto-lab`, `dsh-ocr`, `dsh-wsl`, `dsh-docker`, `dsh-ollama`, + `dsh-image-upscale` and `dsh-comfyui`), and the pack-wide checks still own the + routes, the bundle and the manifest. - `scripts/` — the launcher (`run-web.*`), and four folders: `console/` (the shared console layer), `setup/` (install and uninstall, which a fresh machine runs once), `tools/` (maintainer-only: the fork re-sync for the client bundles this pack vendors) diff --git a/README.md b/README.md index 26fde62..027bb71 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ way and what it touches. The exact versions are in | [`dsh-audio`](packages/dsh-audio/README.md) | A waveform surface for WAV, AIFF and FLAC: one track per channel, dBFS, selection and playback. It also draws the Media panel, which lists every audio, image, video and GIF file in the workspace. No microphone, no device list, no output routing. | | [`dsh-browser`](packages/dsh-browser/README.md) | The Browser tab, replacing the shipped iframe one: a page rendered on the host in a disposable engine behind an https-only egress gate. It answers with a screenshot, post-script text and measured styles, for the tab and for three `browser_*` tools. Built and shipped but turned OFF, because the master layer disables the row. | | [`dsh-cmdbar`](packages/dsh-cmdbar/README.md) | The command bar: the agent's own commands in a bottom dock, as a read-only transcript of the conversation log. It follows whichever conversation is on screen. | +| [`dsh-comfyui`](packages/dsh-comfyui/README.md) | ComfyUI as a surface the agent can build against: seven `comfy_*` tools turn a small readable project spec into the canvas the app opens and the prompt `/prompt` accepts, validate it against the server's own `/object_info` with ComfyUI's own error types, and report what a run produced. Every answer names the rung it reached (`v1-structural` to `v4-executed`), so a graph that compiles is never called one that runs, and with no server it still checks the files on disk and names a missing checkpoint beside the nearest one. `comfy_cli` drives comfy-cli as a second, independent path, and six skills teach the fundamentals, the two workflow formats and how to write a node class. | | [`dsh-deckcraft`](packages/dsh-deckcraft/README.md) | Slides from the chat: four `deck_*` tools over the DeckCraft CLI (MIT OR Apache-2.0). `deck_commands` lists the command ids the build offers, `deck_run` saves a `.deckcraft` in the workspace, `deck_export` renders the slides to PNG so you can look at them. Nothing is hardcoded: DeckCraft's "every button is a command" contract is the API. | | [`dsh-diagrams`](packages/dsh-diagrams/README.md) | Mermaid, TikZ and the Diagram Design kit as tabs and as seven `diagram_*` tools. The kit 204 examples and 44 documented types are vendored at a pinned commit and browsable on the index page. Every write, including a self-contained HTML document, is validated before it is stored. | | [`dsh-docker`](packages/dsh-docker/README.md) | Docker or Podman as a surface: nine `docker_*` tools over the machine's own CLI, argv-only, with every removal confirmed by repeating the target. `docker_start` launches Docker Desktop or a podman machine and waits for the **daemon**. A Docker tab lists containers and images with their logs, and there is no `exec`, no `system prune` and no free-form `run`. | diff --git a/packages/dsh-comfyui/README.md b/packages/dsh-comfyui/README.md new file mode 100644 index 0000000..4e2ff7d --- /dev/null +++ b/packages/dsh-comfyui/README.md @@ -0,0 +1,162 @@ +# dsh-comfyui + +ComfyUI as a surface the agent can **build against**: a project spec becomes a +real `workflow.json` + `prompt.json`, is validated against the server's own node +catalog with ComfyUI's own error vocabulary, is queued, and reports what came +out. One row, seven tools, six skills, no browser half, zero npm dependencies, no +bundled engine. + +## Why it exists + +A ComfyUI workflow is a graph saved in **two dialects that are not +interchangeable**: + +- the **canvas** the app saves — integer node ids, links as array positions, and + `widgets_values`, an *unnamed* positional array; +- the **API prompt** `/prompt` accepts — ids as keys, wires as + `["", ]`, values by name. + +Nothing in the harness could turn one into the other, so nothing could tell a +reader *which* of the two things a broken workflow does: fail to open, or fail to +run. And the quietest defect in the whole format lives in that unnamed array — +measured on ComfyUI 0.21.1, `KSampler` declares `control_after_generate` on +`seed`, so its array is seven long: + +``` +[42, "fixed", 4, 1.5, "lcm", "sgm_uniform", 1.0] + seed │ steps cfg sampler scheduler denoise + └─ the value a converter forgets, shifting every later widget by one +``` + +A graph converted with that shift still opens, still runs, and produces the wrong +image with nothing reporting it. This row exists to make that impossible. + +## The seven tools + +| Tool | Answers | +|---|---| +| `comfy_status` | four facts that fail independently: an **install** on disk (Desktop base path, portable folder, checkout — version, python, model counts), a **server** answering on loopback (`/system_stats`, device, VRAM), the **catalog** in force (`/object_info`, a cache, or the built-in core table), and the **projects** in the workspace. It probes 8188 *and* the Desktop ports 8000-8003 — Desktop does not use 8188. Starts nothing. | +| `comfy_nodes` | the catalog: categories, one class's exact inputs and outputs (widget vs link, default/min/max, the option list), or a search. Every answer says which catalog it read. | +| `comfy_project` | `new` (from a shipped template or an inline spec, **rebinding** model filenames to what this machine has), `list`, `show`, `build`, `import` | +| `comfy_validate` | ComfyUI's own checks, offline, with `/prompt`'s `type` strings (`required_input_missing`, `return_type_mismatch`, `value_not_in_list`, `dependency_cycle`, `prompt_no_outputs`, …) plus the node KEY and input NAME. Never queues, never writes | +| `comfy_run` | the only tool that executes: builds, refuses a graph with errors, submits, waits for `/history`, reports files with `/view` URLs — or the node that raised | +| `comfy_test` | the ladder over the shipped library: compile always (writes nothing), run when a server answers | +| `comfy_cli` | comfy-cli as a **second witness**: `run` (which converts the canvas itself), `deps` (which node packs a graph needs), `launch`/`stop`, `status`. Never `install` | + +## The ladder — every answer names the rung it reached + +| Rung | Means | +|---|---| +| `v1-structural` | the spec compiles and the wires type-check, against the built-in core table (eighteen nodes) | +| `v2-schema` | the same against a **complete** server catalog: every class exists, every value is in the server's list | +| `v3-queued` | `/prompt` accepted it and returned a `prompt_id` | +| `v4-executed` | a `/history` entry finished and named files | + +`v1` says one thing plainly: *no server catalog was in force*. "It compiles" is +never printed as "it runs". + +## What it checks with no server at all + +A server's `/object_info` is what turns a dropdown into a file list, so with the +app closed nothing used to check that a graph's checkpoint exists. This row reads +the **install** instead — the base path `comfy_status` found, `models//`, +`input/`, plus any extra model root comfy-cli reports — and reports a missing +file with ComfyUI's own type: + +``` +ERROR value_not_in_list (node 2 · input lora_name): models/loras/lcm-lora-sdXL.safetensors +does not exist on this machine (1 file(s) there; nearest: lcm-lora-sd15.safetensors). +ComfyUI refuses a prompt naming a file it does not have with value_not_in_list, so +this graph cannot run yet. +``` + +It runs on the **compiled prompt**, where `@bindings` are already filenames, and +only for a file input whose option list the catalog did not know — when a server +did answer, its list is the truth and this stays quiet. A folder that does not +exist is a warning, not a missing file: nothing can be claimed about a path that +is not there. + +So `v1-structural` on a machine whose models happen to be present is now a +claim somebody made, and a missing model is named, with the nearest file beside +it, before anything is queued. + +## A project is a folder + +``` +comfyui// + project.json the SOURCE — nodes by key, values by name, wires by ., @bindings for anything machine-specific + workflow.json GENERATED — drag it onto the canvas + prompt.json GENERATED — what /prompt accepts + README.md GENERATED — what it is, what it needs, what was checked + build.json GENERATED — the receipt: spec sha256, catalog, rung, findings +``` + +`comfy_project action=new template=text-to-image` on a machine with a different +checkpoint does not fail: it rebinds `@checkpoint` — only on an exact +case-insensitive match or when the server lists exactly one file, never by +guessing between two — and prints every rebinding it made. An unresolvable +binding is an ERROR, because a graph built against a model nobody chose fails one +step from the cause. + +## The shipped examples + +| Slug | Graph | Needs | +|---|---|---| +| `smoke-image` | `EmptyImage` → `SaveImage` | **nothing** | +| `smoke-video` | `EmptyImage` → `RepeatImageBatch` → `CreateVideo` → `SaveVideo` | **nothing** | +| `text-to-image` | the 8-node class build: checkpoint → LCM LoRA → 2× CLIP → latent → KSampler (4 steps, cfg 1.5) → VAE decode → save | a checkpoint + a LoRA | +| `image-to-image` | the same graph with `LoadImage` → `ImageScale` → `VAEEncode` and denoise 0.55 | both + an input image | + +The two model-free ones exist so a person proves the server, the queue, the +output folder and this row's compiler work **before** a 2 GB download is blamed. +`comfy_test action=compile` checks all four with nothing running. + +## The six skills + +`comfyui-fundamentals` (the mental model: graph is a program, latent arithmetic, +the dials, the six failures) · `comfyui-workflow-json` (both dialects and the +positional trap) · `comfyui-api` (the endpoints, the `node_errors` body, the +twelve error types, polling) · `comfyui-cli` (comfy-cli across platforms — +install, launch, run, deps, nodes, models, `--json`) · `comfyui-node-class` +(writing a node: classic `INPUT_TYPES`, the V3 `IO.ComfyNode` schema, the +verification step) · `comfyui-projects` (this row's dialect and the rung ladder). + +Every fenced example in them is checked by this package's own check: JSON must +parse, JavaScript must pass `node --check`, Python must pass `ast.parse`, and +every `curl` must name a documented route and every `comfy` line a real +subcommand. + +## What it deliberately does not do + +No UI of its own (the app is the UI), no installing ComfyUI / a node pack / a +model, no starting a server except through `comfy launch --background`, no +WebSocket (it polls `/history`), no remote servers unless +`DSH_COMFYUI_ALLOW_REMOTE=1`, and no lowering of a subgraph export — it names the +ungroup step instead, because a subgraph has virtual input/output nodes and a +guess would produce a prompt that runs and means something else. + +## Where things live + +| | | +|---|---| +| projects | `/comfyui/` (`DSH_COMFYUI_ROOT` moves it) | +| catalog cache | `$DSH_HOME/dsh-comfyui/schema/.json` — one per server read | +| the server this row talks to | `DSH_COMFYUI_URL` (loopback only, unless opted in) | +| the install, if it is somewhere unusual | `DSH_COMFYUI_DIR` | +| the comfy-cli binary | `DSH_COMFY_CLI` | +| the port ComfyUI Desktop picked | discovered, not assumed — 8188 and 8000-8003 are probed | + +## Checking it + +```bash +node checks/check-comfyui-node.mjs +``` + +363 assertions with no server and no CLI: a fake ComfyUI answers the real routes +with real-shaped bodies, a fake runner answers `comfy --version`, the four +examples compile, the canvas round-trips back to the same prompt, every refusal +is produced by name, and the live half runs only when a real server answers +(`DSH_COMFYUI_CHECK_LIVE=0` skips it). + +This is **additional** to `scripts/checks/` — it travels with the package, which +is what makes it useful outside this repository. diff --git a/packages/dsh-comfyui/checks/check-comfyui-node.mjs b/packages/dsh-comfyui/checks/check-comfyui-node.mjs new file mode 100644 index 0000000..909862b --- /dev/null +++ b/packages/dsh-comfyui/checks/check-comfyui-node.mjs @@ -0,0 +1,1179 @@ +// check-comfyui-node.mjs - dsh-comfyui's own contract, driven end to end. +// +// ComfyUI is the user's own application and it is not running on a fresh +// machine, so the only way to exercise the compiler, the validator, the rungs +// and the refusals deterministically is a FAKE server: a `node:http` server on +// 127.0.0.1:0 that answers the real routes with real-shaped bodies - a classic +// `/object_info` entry, a V3 one, a `prompt_id`, a `history` entry with +// `status.messages`, and a 400 carrying `node_errors`. +// +// What that makes an ASSERTION rather than an observation: +// +// - KSampler's widgets_values is [42, "fixed", 4, 1.5, "lcm", "sgm_uniform", 1] +// - the control_after_generate value sits at index 1, and a compiler that +// dropped it would shift cfg, sampler and scheduler by one with no error; +// - a wire is ["", ] with the id as a STRING; +// - the canvas round-trips back to the same prompt through the decoder; +// - `value_not_in_list` is produced for a combo value the server does not +// have, and only when a COMPLETE catalog is in force. +// +// Four sections need the real world and each says so when it cannot: +// +// - the SKILL EXAMPLES: every fenced ```json block must parse, every ```js +// block must pass `node --check`, every ```python block must pass Python's +// own `ast.parse` when a Python is on PATH, and every `curl` / `comfy` line +// must name a route or a subcommand this package documents; +// - `comfy_cli` needs no CLI here: a fake runner answers the argv, which also +// proves the argv this row builds; +// - the LIVE half: only when a real server answers at the default port or +// DSH_COMFYUI_URL, one compile is checked against the catalog it reports. +// +// Run: node checks/check-comfyui-node.mjs +// DSH_COMFYUI_CHECK_LIVE=0 node checks/check-comfyui-node.mjs # pure half +import { createServer } from 'node:http' +import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { spawnSync } from 'node:child_process' + +import { + CORE_NODES, + SOURCES, + catalogFromObjectInfo, + coreCatalog, + categoriesIn, + nodeFromTable, + nodeIn, + outputSlot, + parseNodeInfo, + searchCatalog, + widgetInputs, +} from '../lib/nodes.js' +import { readSpec, slugify, typesCompatible } from '../lib/spec.js' +import { compileProject, coerce, describeCatalog, CONTROL_AFTER_GENERATE } from '../lib/compile.js' +import { validatePrompt, parseWorkflow, workflowToPrompt, decodeWidgetValues, outputsOf, errorsOf } from '../lib/graph.js' +import { checkPromptFiles, inventory } from '../lib/files.js' +import { buildFromSpec, createProject, projectPaths, projectsRoot, listProjects, readJson } from '../lib/projects.js' +import { listExamples, readExample } from '../lib/examples.js' +import { buildTools, rebindToCatalog } from '../lib/tools.js' +import { activationLine, createDeps, parseSkillFile, __internals } from '../lib/index.js' +import { cliVersion, parseEnvelope, envFacts, whichFacts, promptIdFromRunText, depsArgv, runArgv, argvFor, explainCliFailure } from '../lib/cli.js' +import { discoverInstall, resolveServers, isLoopbackHost, formatBytes } from '../lib/client.js' + +const here = path.dirname(fileURLToPath(import.meta.url)) +const packageRoot = path.join(here, '..') +const manifest = JSON.parse(readFileSync(path.join(packageRoot, 'package.json'), 'utf8')) + +let checks = 0 +let failures = 0 +let skipped = 0 +const check = (label, actual, expected) => { + checks += 1 + const ok = expected === undefined ? Boolean(actual) : actual === expected + if (!ok) failures += 1 + console.log((ok ? 'ok ' : 'FAIL ') + label.padEnd(62) + (expected === undefined ? '' : ' ' + JSON.stringify(actual))) + return ok +} +const skip = (label, reason) => { + skipped += 1 + console.log('skip ' + label.padEnd(62) + ' (' + reason + ')') +} + +// --------------------------------------------------------------------------- +// The manifest +// --------------------------------------------------------------------------- +check('the package is a dsh bundle with a patch layer', manifest.dsh && manifest.dsh.bundle && manifest.dsh.bundle.patch, './cordis.patch.yml') +check('the row owns no browser half', manifest.dsh.client === undefined, true) +check('the row has no npm dependency', manifest.dependencies === undefined && manifest.peerDependencies === undefined, true) +check('the version is the alpha this check knows', manifest.version, __internals.PLUGIN_VERSION) +check('package.json ships lib, examples, skills, checks', ['lib', 'examples', 'skills', 'checks', 'cordis.patch.yml'].every((entry) => manifest.files.includes(entry)), true) +check('seven tools are declared', __internals.CAPABILITIES.tools.length, 7) +check('six skills are declared', __internals.CAPABILITIES.skills.length, 6) +check('the rung ladder is the four this check drives', __internals.CAPABILITIES.rungs.join(','), 'v1-structural,v2-schema,v3-queued,v4-executed') +check('the four examples are declared', __internals.CAPABILITIES.examples.join(','), 'smoke-image,smoke-video,text-to-image,image-to-image') +check('the endpoints are loopback API paths', __internals.CAPABILITIES.endpoints.every((entry) => entry.startsWith('/')), true) + +// --------------------------------------------------------------------------- +// The /object_info parser - both shapes in one document +// --------------------------------------------------------------------------- +// Transcribed from ComfyUI 0.21.1 (`nodes.py`): the classic `[type, options]` +// tuple, a combo declared as a LIST, a combo declared as "COMBO" with options +// (the V3 form `RepeatImageBatch` answers with), the control_after_generate +// flag, forceInput, optional inputs and hidden inputs. +const FIXTURE = { + KSampler: { + input: { + required: { + model: ['MODEL', {}], + seed: ['INT', { default: 0, min: 0, max: 18446744073709551615, control_after_generate: true }], + steps: ['INT', { default: 20, min: 1, max: 10000 }], + cfg: ['FLOAT', { default: 8.0, min: 0.0, max: 100.0, step: 0.1 }], + sampler_name: [['euler', 'euler_ancestral', 'dpmpp_2m', 'lcm'], {}], + scheduler: [['normal', 'karras', 'sgm_uniform'], {}], + positive: ['CONDITIONING', {}], + negative: ['CONDITIONING', {}], + latent_image: ['LATENT', {}], + denoise: ['FLOAT', { default: 1.0, min: 0.0, max: 1.0, step: 0.01 }], + }, + }, + input_order: { required: ['model', 'seed', 'steps', 'cfg', 'sampler_name', 'scheduler', 'positive', 'negative', 'latent_image', 'denoise'] }, + output: ['LATENT'], + output_name: ['LATENT'], + output_node: false, + name: 'KSampler', + display_name: 'KSampler', + category: 'sampling', + }, + SaveImage: { + input: { + required: { images: ['IMAGE', {}], filename_prefix: ['STRING', { default: 'ComfyUI' }] }, + hidden: { prompt: 'PROMPT', extra_pnginfo: 'EXTRA_PNGINFO' }, + }, + input_order: { required: ['images', 'filename_prefix'] }, + output: [], + output_name: [], + output_node: true, + name: 'SaveImage', + display_name: 'Save Image', + category: 'image', + }, + LoadImage: { + input: { required: { image: [['example.png', 'photo.png'], { image_upload: true }] } }, + input_order: { required: ['image'] }, + output: ['IMAGE', 'MASK'], + output_name: ['IMAGE', 'MASK'], + output_node: false, + name: 'LoadImage', + category: 'image', + }, + CheckpointLoaderSimple: { + input: { required: { ckpt_name: [['v1-5-pruned-emaonly-fp16.safetensors'], {}] } }, + input_order: { required: ['ckpt_name'] }, + output: ['MODEL', 'CLIP', 'VAE'], + output_name: ['MODEL', 'CLIP', 'VAE'], + output_node: false, + name: 'CheckpointLoaderSimple', + category: 'loaders', + }, + LoraLoader: { + input: { + required: { + model: ['MODEL', {}], + clip: ['CLIP', {}], + lora_name: [['lcm-lora-sd15.safetensors'], {}], + strength_model: ['FLOAT', { default: 1.0, min: -100.0, max: 100.0, step: 0.01 }], + strength_clip: ['FLOAT', { default: 1.0, min: -100.0, max: 100.0, step: 0.01 }], + }, + }, + input_order: { required: ['model', 'clip', 'lora_name', 'strength_model', 'strength_clip'] }, + output: ['MODEL', 'CLIP'], + output_name: ['MODEL', 'CLIP'], + output_node: false, + name: 'LoraLoader', + category: 'loaders', + }, + ImageScale: { + input: { + required: { + image: ['IMAGE', {}], + upscale_method: [['nearest-exact', 'bilinear', 'area', 'bicubic', 'lanczos'], {}], + width: ['INT', { default: 512, min: 0, max: 16384, step: 1 }], + height: ['INT', { default: 512, min: 0, max: 16384, step: 1 }], + crop: [['disabled', 'center'], {}], + }, + }, + input_order: { required: ['image', 'upscale_method', 'width', 'height', 'crop'] }, + output: ['IMAGE'], + output_name: ['IMAGE'], + output_node: false, + name: 'ImageScale', + category: 'image/upscaling', + }, + EmptyImage: { + input: { + required: { + width: ['INT', { default: 512, min: 1, max: 16384, step: 1 }], + height: ['INT', { default: 512, min: 1, max: 16384, step: 1 }], + batch_size: ['INT', { default: 1, min: 1, max: 4096 }], + color: ['INT', { default: 0, min: 0, max: 16777215, step: 1, display: 'color' }], + }, + }, + input_order: { required: ['width', 'height', 'batch_size', 'color'] }, + output: ['IMAGE'], + output_name: ['IMAGE'], + output_node: false, + name: 'EmptyImage', + category: 'image', + }, + // The V3 shape: COMBO with `options`, an optional input, and is_output_node. + RepeatImageBatch: { + input: { required: { image: ['IMAGE', {}], amount: ['INT', { default: 1, min: 1, max: 4096 }] } }, + input_order: { required: ['image', 'amount'] }, + output: ['IMAGE'], + output_name: ['IMAGE'], + output_node: false, + name: 'RepeatImageBatch', + category: 'image/batch', + }, + CreateVideo: { + input: { + required: { images: ['IMAGE', {}], fps: ['FLOAT', { default: 30.0, min: 1.0, max: 120.0, step: 1.0 }] }, + optional: { audio: ['AUDIO', { optional: true }] }, + }, + input_order: { required: ['images', 'fps'], optional: ['audio'] }, + output: ['VIDEO'], + output_name: ['VIDEO'], + output_node: false, + name: 'CreateVideo', + category: 'video', + }, + SaveVideo: { + input: { + required: { + video: ['VIDEO', {}], + filename_prefix: ['STRING', { default: 'video/ComfyUI' }], + format: ['COMBO', { options: ['auto', 'mp4', 'webm'], default: 'auto' }], + codec: ['COMBO', { options: ['auto', 'h264', 'vp9'], default: 'auto' }], + }, + hidden: { prompt: 'PROMPT', extra_pnginfo: 'EXTRA_PNGINFO' }, + }, + input_order: { required: ['video', 'filename_prefix', 'format', 'codec'] }, + output: [], + output_name: [], + output_node: true, + name: 'SaveVideo', + display_name: 'Save Video', + category: 'video', + }, +} + +/** The rest of the classes, in `/object_info` shape, from the core table. */ +function objectInfoFromTable(classType) { + const node = nodeFromTable(classType, CORE_NODES[classType]) + const input = { required: {}, optional: {}, hidden: {} } + const order = { required: [], optional: [] } + for (const entry of node.inputs) { + if (entry.kind === 'hidden') { + input.hidden[entry.name] = entry.type + continue + } + const section = entry.optional ? 'optional' : 'required' + const type = entry.enum !== null ? entry.enum : entry.type + const options = entry.controlAfterGenerate ? { ...entry.options, control_after_generate: true } : { ...entry.options } + input[section][entry.name] = [type, options] + order[section].push(entry.name) + } + return { + input, + input_order: order, + output: node.outputs.map((output) => output.type), + output_name: node.outputs.map((output) => output.name), + output_node: node.outputNode, + name: classType, + display_name: node.displayName, + category: node.category, + description: node.description, + } +} + +/** The whole fixture catalog: the hand-written entries plus the table's rest. */ +function fullFixture() { + const raw = { ...FIXTURE } + for (const classType of Object.keys(CORE_NODES)) if (!(classType in raw)) raw[classType] = objectInfoFromTable(classType) + return raw +} + +const ks = parseNodeInfo('KSampler', FIXTURE.KSampler) +check('the parser keeps the input ORDER', ks.inputs.map((input) => input.name).join(','), 'model,seed,steps,cfg,sampler_name,scheduler,positive,negative,latent_image,denoise') +check('a MODEL input is a link, not a widget', ks.inputs.find((input) => input.name === 'model').kind, 'link') +check('a LIST type is a combo widget', ks.inputs.find((input) => input.name === 'sampler_name').kind, 'widget') +check('...and its options are the list', ks.inputs.find((input) => input.name === 'sampler_name').enum.join(','), 'euler,euler_ancestral,dpmpp_2m,lcm') +check('control_after_generate is read from the options', ks.inputs.find((input) => input.name === 'seed').controlAfterGenerate, true) +check('min and max are kept', ks.inputs.find((input) => input.name === 'steps').options.min + '..' + ks.inputs.find((input) => input.name === 'steps').options.max, '1..10000') +check('an output node says so', parseNodeInfo('SaveImage', FIXTURE.SaveImage).outputNode, true) +check('hidden inputs are marked hidden', parseNodeInfo('SaveImage', FIXTURE.SaveImage).inputs.filter((input) => input.kind === 'hidden').map((input) => input.name).join(','), 'prompt,extra_pnginfo') +check('output NAMES are read, not just types', parseNodeInfo('LoadImage', FIXTURE.LoadImage).outputs.map((output) => output.name).join(','), 'IMAGE,MASK') +check('an image-upload combo is still a widget', parseNodeInfo('LoadImage', FIXTURE.LoadImage).inputs[0].kind, 'widget') +check('the V3 COMBO shape reads its options', parseNodeInfo('SaveVideo', FIXTURE.SaveVideo).inputs.find((input) => input.name === 'format').enum.join(','), 'auto,mp4,webm') +check('an optional input is optional', parseNodeInfo('CreateVideo', FIXTURE.CreateVideo).inputs.find((input) => input.name === 'audio').optional, true) +check('an optional input is still a link', parseNodeInfo('CreateVideo', FIXTURE.CreateVideo).inputs.find((input) => input.name === 'audio').kind, 'link') + +// The table is the fallback every offline compile uses, so its ORDER is a +// contract: assert the seven classes whose order is the trap. +for (const classType of ['KSampler', 'SaveImage', 'LoadImage', 'ImageScale', 'EmptyImage', 'RepeatImageBatch', 'CreateVideo']) { + const fromFixture = parseNodeInfo(classType, FIXTURE[classType]) + const fromTable = nodeFromTable(classType, CORE_NODES[classType]) + check('the core table agrees with /object_info on ' + classType, fromTable.inputs.map((input) => input.name + ':' + input.kind).join(','), fromFixture.inputs.map((input) => input.name + ':' + input.kind).join(',')) +} +check('the core table covers the examples it must', ['KSampler', 'SaveImage', 'EmptyImage', 'SaveVideo', 'LoadImage'].every((name) => name in CORE_NODES), true) +check('the core catalog says it is NOT complete', coreCatalog().complete, false) +check('a server catalog says it IS complete', catalogFromObjectInfo(FIXTURE).complete, true) +check('the parser skips an entry it cannot read', catalogFromObjectInfo({ Bad: 42 }).nodes.size, 0) + +// --------------------------------------------------------------------------- +// The spec: every refusal, by name +// --------------------------------------------------------------------------- +const completeCatalog = catalogFromObjectInfo(fullFixture(), { origin: 'http://127.0.0.1:8188', version: '0.21.1', fetchedAt: 'now' }) + +/** The findings of a spec, read against a catalog. */ +function specFindings(spec, catalog = completeCatalog) { + try { + return readSpec(spec, catalog).findings + } catch (error) { + return [{ severity: 'error', type: error.code ?? 'THREW', message: error.message }] + } +} +const errorTypes = (findings) => findings.filter((entry) => entry.severity === 'error').map((entry) => entry.type).join(',') + +const baseSpec = { + name: 'probe', + nodes: [ + { key: 'empty', class: 'EmptyImage', widgets: { width: 64, height: 64, batch_size: 1, color: 0 } }, + { key: 'save', class: 'SaveImage', title: 'Save', widgets: { filename_prefix: 'x' }, wires: { images: 'empty.IMAGE' } }, + ], +} +check('a minimal spec has no errors', errorTypes(specFindings(baseSpec)), '') +check('a name is required', errorTypes(specFindings({ ...baseSpec, name: '' })), 'missing_name') +check('nodes are required', errorTypes(specFindings({ ...baseSpec, nodes: [] })), 'missing_nodes') +check('a duplicate key is refused', errorTypes(specFindings({ ...baseSpec, nodes: [baseSpec.nodes[0], baseSpec.nodes[0], baseSpec.nodes[1]] })), 'duplicate_key') +check('a bad key is refused', errorTypes(specFindings({ ...baseSpec, nodes: [{ key: '9 bad', class: 'SaveImage' }] })), 'bad_key') +check('a class the server lacks is an ERROR when the catalog is complete', errorTypes(specFindings({ ...baseSpec, nodes: [{ key: 'x', class: 'NoSuchNode' }, ...baseSpec.nodes] })), 'missing_node_type') +check('...and only a WARNING against the core table', specFindings({ ...baseSpec, nodes: [{ key: 'x', class: 'NoSuchNode' }, ...baseSpec.nodes] }, coreCatalog()).filter((entry) => entry.type === 'class_unverified').length, 1) +check('an unknown widget is refused, and names the real ones', specFindings({ ...baseSpec, nodes: [{ key: 'empty', class: 'EmptyImage', widgets: { widht: 64 } }, baseSpec.nodes[1]] })[0].message.includes('width'), true) +check('an unknown output is refused, and lists the slots', specFindings({ ...baseSpec, nodes: [baseSpec.nodes[0], { key: 'save', class: 'SaveImage', wires: { images: 'empty.IMAGE0' } }] })[0].message.includes('0=IMAGE:IMAGE'), true) +check('a wire from a key that does not exist is refused', errorTypes(specFindings({ ...baseSpec, nodes: [baseSpec.nodes[0], { key: 'save', class: 'SaveImage', wires: { images: 'ghost.0' } }] })), 'bad_linked_input') +check('a type mismatch is refused in the spec too', errorTypes(specFindings({ ...baseSpec, nodes: [baseSpec.nodes[0], { key: 'save', class: 'SaveImage', widgets: { filename_prefix: 'x' }, wires: { images: 'empty.0', filename_prefix: 'empty.IMAGE' } }] })), 'return_type_mismatch') +check('a graph with no output node is refused', errorTypes(specFindings({ name: 'p', nodes: [{ key: 'a', class: 'EmptyImage' }] })), 'prompt_no_outputs') +check('a cycle is refused', errorTypes(specFindings({ name: 'p', nodes: [{ key: 'a', class: 'LoraLoader', widgets: { lora_name: 'l', strength_model: 1, strength_clip: 1 }, wires: { model: 'b.MODEL' } }, { key: 'b', class: 'LoraLoader', widgets: { lora_name: 'l', strength_model: 1, strength_clip: 1 }, wires: { model: 'a.MODEL' } }] })).includes('dependency_cycle'), true) +check('an unknown field is only a warning', specFindings({ ...baseSpec, wat: 1 }).filter((entry) => entry.type === 'unknown_field').length, 1) +check('a wire may name a numeric slot', specFindings({ ...baseSpec, nodes: [baseSpec.nodes[0], { key: 'save', class: 'SaveImage', widgets: { filename_prefix: 'x' }, wires: { images: 'empty.0' } }] }).filter((entry) => entry.severity === 'error').length, 0) + +// The type rule is ComfyUI's own: union types, `*` matches anything. +check('identical types match', typesCompatible('IMAGE', 'IMAGE'), true) +check('a union input accepts one of its members', typesCompatible('IMAGE', 'IMAGE,MASK'), true) +check('`*` accepts anything', typesCompatible('*', 'LATENT') && typesCompatible('LATENT', '*'), true) +check('IMAGE does not feed LATENT', typesCompatible('IMAGE', 'LATENT'), false) + +// --------------------------------------------------------------------------- +// The compiler: the four shipped examples, and the widget trap +// --------------------------------------------------------------------------- +const dryPaths = { dir: '(memory)', spec: '', workflow: '', prompt: '', readme: '', build: '' } +const examples = listExamples() +check('the four examples are on disk', examples.map((entry) => entry.slug).join(','), 'smoke-image,smoke-video,text-to-image,image-to-image') +const compiled = new Map() +for (const example of examples) { + const built = buildFromSpec({ raw: readExample(example.slug), paths: dryPaths, catalog: coreCatalog(), dryRun: true }) + compiled.set(example.slug, built) + check('example ' + example.slug + ' compiles against the core table', built.rung, 'v1-structural') + check('...with no errors', built.counts.errors, 0) +} +const ksNode = compiled.get('text-to-image').workflow.nodes.find((node) => node.type === 'KSampler') +check('KSampler widgets_values carries the control value at index 1', JSON.stringify(ksNode.widgets_values), JSON.stringify([42, 'fixed', 4, 1.5, 'lcm', 'sgm_uniform', 1])) +check('...so the array is one longer than the widget count', ksNode.widgets_values.length, widgetInputs(nodeIn(completeCatalog, 'KSampler')).length + 1) +check('...and the prompt does NOT carry the control value', String(compiled.get('text-to-image').prompt[String(ksNode.id)].inputs.control_after_generate ?? 'absent'), 'absent') +check('a wire is ["id", slot] with a STRING id', JSON.stringify(compiled.get('smoke-image').prompt['2'].inputs.images), JSON.stringify(['1', 0])) +check('ids are strings in the prompt', Object.keys(compiled.get('smoke-image').prompt).every((key) => typeof key === 'string'), true) +check('the canvas links are OBJECTS (the 0.4 form)', Array.isArray(compiled.get('smoke-image').workflow.links) && typeof compiled.get('smoke-image').workflow.links[0] === 'object' && !Array.isArray(compiled.get('smoke-image').workflow.links[0]), true) +check('the canvas version is 0.4', compiled.get('smoke-image').workflow.version, 0.4) +check('target_slot points into the target node inputs', compiled.get('text-to-image').workflow.links.every((link) => { + const target = compiled.get('text-to-image').workflow.nodes.find((node) => node.id === link.target_id) + return target.inputs[link.target_slot] !== undefined +}), true) +check('every node has a position off the origin', compiled.get('text-to-image').workflow.nodes.every((node) => node.pos[0] > 0), true) +check('an output node with no outputs has an empty OUT list', compiled.get('smoke-image').workflow.nodes.find((node) => node.type === 'SaveImage').outputs.length, 0) +check('a hidden input never reaches the prompt', Object.keys(compiled.get('smoke-image').prompt['2'].inputs).includes('prompt'), false) +check('the widget order comes from the catalog in force', compiled.get('smoke-image').widgetOrder, 'core-table') +check('a complete catalog is recorded as such', buildFromSpec({ raw: readExample('smoke-image'), paths: dryPaths, catalog: completeCatalog, dryRun: true }).widgetOrder, 'server') +check('the dry run WROTE nothing', existsSync(path.join(packageRoot, 'workflow.json')), false) + +// The round-trip: canvas -> prompt, through the decoder, with a complete catalog. +const roundTripCatalog = { ...coreCatalog(), complete: true } +const roundTripped = workflowToPrompt(parseWorkflow(compiled.get('text-to-image').workflow), roundTripCatalog) +/** JSON with sorted keys, so a comparison is about VALUES and not key order. */ +const canonical = (value) => JSON.stringify(value, (_key, entry) => (entry !== null && typeof entry === 'object' && !Array.isArray(entry) ? Object.fromEntries(Object.entries(entry).sort(([left], [right]) => left.localeCompare(right))) : entry)) +check('a compiled canvas lowers back to the same prompt', canonical(roundTripped.prompt), canonical(compiled.get('text-to-image').prompt)) +check('...and the round-trip reports no errors', roundTripped.findings.filter((entry) => entry.severity === 'error').length, 0) +const legacyLinks = compiled.get('smoke-image').workflow.links.map((link) => [link.id, link.origin_id, link.origin_slot, link.target_id, link.target_slot, link.type]) +const legacyWorkflow = { ...compiled.get('smoke-image').workflow, links: legacyLinks } +check('legacy ARRAY links are read too', workflowToPrompt(parseWorkflow(legacyWorkflow), roundTripCatalog).prompt['2'].inputs.images.join(','), '1,0') +check('a canvas without a complete catalog is REFUSED, by name', (() => { + try { + workflowToPrompt(parseWorkflow(compiled.get('smoke-image').workflow), coreCatalog()) + return 'accepted' + } catch (error) { + return error.code + } +})(), 'SCHEMA_REQUIRED') +check('decodeWidgetValues stops the control value from shifting the rest', decodeWidgetValues(nodeIn(completeCatalog, 'KSampler'), [7, 'randomize', 9, 2.5, 'euler', 'karras', 0.5]).steps, 9) +check('a subgraph-only export is refused with the ungroup advice', (() => { + try { + parseWorkflow({ nodes: [], links: [], definitions: { subgraphs: [{ name: 'Sub', id: 'x' }] } }) + return 'accepted' + } catch (error) { + return error.code + ':' + /ungroup/i.test(error.message) + } +})(), 'SUBGRAPH_ONLY:true') + +// Coercion: the server's own spelling wins, and a wrong value is named. +const scaleSpec = nodeIn(completeCatalog, 'ImageScale') +check('a case-insensitive combo match normalizes to the server spelling', coerce('Lanczos', scaleSpec.inputs.find((input) => input.name === 'upscale_method')).value, 'lanczos') +check('a value not in the list is refused as value_not_in_list', coerce('magic', scaleSpec.inputs.find((input) => input.name === 'upscale_method')).type, 'value_not_in_list') +check('an INTEGER below min is refused', coerce(0 - 1, scaleSpec.inputs.find((input) => input.name === 'width')).type, 'value_smaller_than_min') +check('a fractional INT is refused', coerce(1.5, ks.inputs.find((input) => input.name === 'steps')).type, 'invalid_input_type') +check('a numeric string is coerced', coerce('42', ks.inputs.find((input) => input.name === 'steps')).value, 42) + +// --------------------------------------------------------------------------- +// The prompt validator: ComfyUI's own error types +// --------------------------------------------------------------------------- +const promptOf = (slug) => JSON.parse(JSON.stringify(compiled.get(slug).prompt)) +const typesOf = (findings) => findings.filter((entry) => entry.severity === 'error').map((entry) => entry.type).sort().join(',') +const findIn = (prompt, classType) => Object.entries(prompt).find(([, node]) => node.class_type === classType) + +check('a compiled prompt validates clean against a complete catalog', typesOf(validatePrompt(promptOf('smoke-image'), completeCatalog).findings), '') +check('...and against the core table', typesOf(validatePrompt(promptOf('smoke-image'), coreCatalog()).findings), '') +{ + const prompt = promptOf('smoke-image') + const [id, node] = findIn(prompt, 'SaveImage') + delete node.inputs.filename_prefix + delete node.inputs.images + check('a missing required input is required_input_missing', typesOf(validatePrompt(prompt, completeCatalog).findings), 'required_input_missing,required_input_missing') + check('...on the node that is missing it', validatePrompt(prompt, completeCatalog).nodeErrors[id].length, 2) +} +{ + const prompt = promptOf('smoke-image') + findIn(prompt, 'SaveImage')[1].inputs.images = ['99', 0] + check('a wire from a node not in the prompt is bad_linked_input', typesOf(validatePrompt(prompt, completeCatalog).findings), 'bad_linked_input') +} +{ + const prompt = promptOf('smoke-image') + findIn(prompt, 'SaveImage')[1].inputs.images = ['1', 7] + check('a slot that does not exist is bad_linked_input', typesOf(validatePrompt(prompt, completeCatalog).findings), 'bad_linked_input') +} +{ + const prompt = { + '1': { class_type: 'CheckpointLoaderSimple', inputs: { ckpt_name: 'v1-5-pruned-emaonly-fp16.safetensors' } }, + '2': { class_type: 'CLIPTextEncode', inputs: { text: 'a', clip: ['1', 1] } }, + '3': { class_type: 'CLIPTextEncode', inputs: { text: 'b', clip: ['1', 1] } }, + '4': { class_type: 'EmptyLatentImage', inputs: { width: 512, height: 512, batch_size: 1 } }, + '5': { + class_type: 'KSampler', + inputs: { model: ['1', 0], seed: 1, steps: 4, cfg: 1.5, sampler_name: 'nonsense', scheduler: 'sgm_uniform', positive: ['2', 0], negative: ['3', 0], latent_image: ['4', 0], denoise: 1 }, + }, + '6': { class_type: 'VAEDecode', inputs: { samples: ['5', 0], vae: ['1', 2] } }, + '7': { class_type: 'SaveImage', inputs: { images: ['6', 0], filename_prefix: 'x' } }, + } + check('a combo value the server lacks is value_not_in_list', typesOf(validatePrompt(prompt, completeCatalog).findings), 'value_not_in_list') + check('...and is NOT reported against the core table (no options known)', typesOf(validatePrompt(prompt, coreCatalog()).findings), '') +} +{ + const prompt = { + '1': { class_type: 'EmptyImage', inputs: { width: 8, height: 8, batch_size: 1, color: 0 } }, + '2': { class_type: 'SaveImage', inputs: { images: ['2', 0], filename_prefix: 'x' } }, + } + check('a self-wire is a dependency_cycle', typesOf(validatePrompt(prompt, completeCatalog).findings).includes('dependency_cycle'), true) +} +{ + const prompt = { '1': { class_type: 'EmptyImage', inputs: { width: 8, height: 8, batch_size: 1, color: 0 } } } + check('no output node is prompt_no_outputs', typesOf(validatePrompt(prompt, completeCatalog).findings), 'prompt_no_outputs') +} +{ + const prompt = promptOf('smoke-image') + prompt['9'] = { class_type: 'EmptyImage', inputs: { width: 8, height: 8, batch_size: 1, color: 0 } } + const findings = validatePrompt(prompt, completeCatalog).findings + check('an orphan node is a warning, not an error', findings.filter((entry) => entry.type === 'unreachable_node').length + '/' + findings.filter((entry) => entry.severity === 'error').length, '1/0') +} +{ + const prompt = promptOf('smoke-image') + prompt['1'].inputs.width = 0 + check('a value below min is value_smaller_than_min', typesOf(validatePrompt(prompt, completeCatalog).findings), 'value_smaller_than_min') +} +check('an empty prompt is refused', typesOf(validatePrompt({}, completeCatalog).findings), 'prompt_empty') +check('a non-object prompt is refused', typesOf(validatePrompt([], completeCatalog).findings), 'prompt_invalid') + +// --------------------------------------------------------------------------- +// History: outputs and failures, whatever the node calls them +// --------------------------------------------------------------------------- +const historyEntry = { + outputs: { '2': { images: [{ filename: 'smoke_00001_.png', subfolder: 'dsh-comfyui', type: 'output' }] } }, + status: { status_str: 'success', completed: true, messages: [['execution_start', {}], ['execution_success', {}]] }, +} +check('an output file is found without knowing the key', outputsOf(historyEntry).length, 1) +check('...with a /view url', outputsOf(historyEntry)[0].url, '/view?filename=smoke_00001_.png&subfolder=dsh-comfyui&type=output') +check('an AUDIO output is found the same way', outputsOf({ outputs: { '3': { audio: [{ filename: 'a.flac', subfolder: 'audio', type: 'output' }] } } }).length, 1) +check('no outputs is an empty list', outputsOf({}).length, 0) +const failedEntry = { outputs: {}, status: { status_str: 'error', completed: false, messages: [['execution_error', { node_id: '5', node_type: 'KSampler', exception_message: 'CUDA out of memory', exception_type: 'torch.OutOfMemoryError' }]] } } +check('an execution error is read out of status.messages', errorsOf(failedEntry).length, 1) +check('...with the node and the exception', errorsOf(failedEntry)[0].node + ':' + errorsOf(failedEntry)[0].exceptionType, '5:torch.OutOfMemoryError') +check('a success entry has no errors', errorsOf(historyEntry).length, 0) + +// --------------------------------------------------------------------------- +// Rebindings: the template follows the machine, never guessing +// --------------------------------------------------------------------------- +{ + const ckptInfo = (names) => ({ ...FIXTURE.CheckpointLoaderSimple, input: { required: { ckpt_name: [names, {}] } }, input_order: { required: ['ckpt_name'] } }) + const one = catalogFromObjectInfo({ CheckpointLoaderSimple: ckptInfo(['only-one.safetensors']) }) + const rebound = rebindToCatalog({ name: 'p', bindings: { checkpoint: 'missing.safetensors' }, nodes: [{ key: 'ckpt', class: 'CheckpointLoaderSimple', widgets: { ckpt_name: '@checkpoint' } }] }, one) + check('a single candidate is taken', rebound.spec.bindings.checkpoint, 'only-one.safetensors') + check('...and the change is REPORTED', rebound.changes.length + ':' + rebound.changes[0].from, '1:missing.safetensors') + const several = catalogFromObjectInfo({ CheckpointLoaderSimple: ckptInfo(['a.safetensors', 'b.safetensors', 'c.safetensors']) }) + const ambiguous = rebindToCatalog({ name: 'p', bindings: { checkpoint: 'missing.safetensors' }, nodes: [{ key: 'ckpt', class: 'CheckpointLoaderSimple', widgets: { ckpt_name: '@checkpoint' } }] }, several) + check('three candidates are not guessed between', ambiguous.spec.bindings.checkpoint, 'missing.safetensors') + check('...and a note says why', ambiguous.notes.length, 1) + const insensitive = rebindToCatalog({ name: 'p', bindings: { checkpoint: 'A.SAFETENSORS' }, nodes: [{ key: 'ckpt', class: 'CheckpointLoaderSimple', widgets: { ckpt_name: '@checkpoint' } }] }, several) + check('a case-insensitive match IS taken, in the server spelling', insensitive.spec.bindings.checkpoint, 'a.safetensors') +} + +// --------------------------------------------------------------------------- +// The fake ComfyUI server +// --------------------------------------------------------------------------- +const OBJECT_INFO = fullFixture() +let refuseNext = null +let historyEntryFor = null +const requests = [] +function readAll(request) { + return new Promise((resolve) => { + let text = '' + request.on('data', (chunk) => { + text += chunk + }) + request.on('end', () => resolve(text)) + }) +} +async function startFakeComfy() { + const server = createServer(async (request, response) => { + const url = new URL(request.url, 'http://127.0.0.1') + const raw = await readAll(request) + let body = null + try { + body = raw === '' ? null : JSON.parse(raw) + } catch (error) { + body = null + } + requests.push({ method: request.method, path: url.pathname, body }) + const json = (status, value) => { + response.writeHead(status, { 'content-type': 'application/json' }) + response.end(JSON.stringify(value)) + } + if (url.pathname === '/system_stats') { + return json(200, { + system: { os: 'nt', ram_total: 16 * 1024 ** 3, ram_free: 8 * 1024 ** 3, comfyui_version: '0.21.1', python_version: '3.12.11 (main)', pytorch_version: '2.9.0+cu128', argv: ['main.py'] }, + devices: [{ name: 'cuda:0 NVIDIA GeForce RTX 4060', type: 'cuda', vram_total: 8 * 1024 ** 3, vram_free: 6 * 1024 ** 3 }], + }) + } + if (url.pathname === '/object_info') return json(200, OBJECT_INFO) + if (url.pathname.startsWith('/object_info/')) { + const classType = decodeURIComponent(url.pathname.slice('/object_info/'.length)) + return json(200, classType in OBJECT_INFO ? { [classType]: OBJECT_INFO[classType] } : {}) + } + if (url.pathname === '/prompt' && request.method === 'POST') { + if (refuseNext !== null) { + const refusal = refuseNext + refuseNext = null + return json(400, refusal) + } + const promptId = 'prompt-0001' + historyEntryFor = { promptId, prompt: body?.prompt ?? {} } + return json(200, { prompt_id: promptId, number: 1, node_errors: {} }) + } + if (url.pathname === '/prompt') return json(200, { queue_running: [], queue_pending: [] }) + if (url.pathname === '/queue') return json(200, { queue_running: [], queue_pending: [] }) + if (url.pathname.startsWith('/history/')) { + const promptId = url.pathname.slice('/history/'.length) + if (historyEntryFor !== null && historyEntryFor.promptId === promptId) { + const saved = Object.values(historyEntryFor.prompt).filter((node) => node.class_type === 'SaveImage' || node.class_type === 'SaveVideo') + const outputs = {} + for (const node of Object.values(historyEntryFor.prompt)) { + if (node.class_type === 'SaveImage') outputs[Object.keys(historyEntryFor.prompt).find((key) => historyEntryFor.prompt[key] === node)] = { images: [{ filename: 'smoke_00001_.png', subfolder: 'dsh-comfyui', type: 'output' }] } + if (node.class_type === 'SaveVideo') outputs[Object.keys(historyEntryFor.prompt).find((key) => historyEntryFor.prompt[key] === node)] = { images: [{ filename: 'smoke_00001_.mp4', subfolder: 'dsh-comfyui', type: 'output' }] } + } + if (saved.length === 0) return json(200, {}) + return json(200, { [promptId]: { prompt: [1, promptId, historyEntryFor.prompt, {}, []], outputs, status: { status_str: 'success', completed: true, messages: [['execution_success', { prompt_id: promptId }]] } } }) + } + return json(200, {}) + } + return json(404, { error: '404 page not found' }) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + return { origin: 'http://127.0.0.1:' + server.address().port, close: () => new Promise((resolve) => server.close(resolve)) } +} + +const fake = await startFakeComfy() +const sandbox = mkdtempSync(path.join(os.tmpdir(), 'dsh-comfyui-check-')) +const home = path.join(sandbox, 'home') +const workspace = path.join(sandbox, 'ws') +const projectsRootDir = path.join(workspace, 'comfyui') +mkdirSync(home, { recursive: true }) +mkdirSync(workspace, { recursive: true }) + +/** A fake comfy-cli: it answers the argv, and writes a deps file when asked. */ +/** + * A fake comfy-cli that answers with the REAL 1.29.0 envelope shapes. + * + * Transcribed from the measured output: `comfy --version` and `comfy --json env` + * both print `{schema:"envelope/1", type:"envelope", ok, command, version, + * where, data, error}`. `state.mode` drives the variants: 'ok' (comfy-cli's + * default workspace does not exist, but the Desktop install it names does), + * 'gone' (the install folder is gone too), 'no-manager' (deps refuses), + * 'no-workspace' (run refuses before reading the graph), 'installed-manager' + * (deps writes its file). + */ +function fakeRunner(state) { + state.calls = state.calls ?? [] + state.mode = state.mode ?? 'ok' + if (state.workspaceExists === undefined) state.workspaceExists = false + if (state.installExists === undefined) state.installExists = true + const envelope = (command, data, extra = {}) => JSON.stringify({ schema: 'envelope/1', type: 'envelope', ok: true, command, version: '1.29.0', where: null, data, error: null, ...extra }) + const envelopeError = (command, code, message, extra = {}) => + JSON.stringify({ schema: 'envelope/1', type: 'envelope', ok: false, command, version: '1.29.0', where: null, data: null, error: { code, message, ...extra } }) + return async (argv, options = {}) => { + state.calls.push(argv) + const joined = argv.join(' ') + const installExists = state.installExists === true && state.mode !== 'gone' + const workspaceExists = state.workspaceExists === true && state.mode !== 'gone' + const envData = { + python: { version: '3.12.11', executable: 'C:\\ComfyUI\\.venv\\Scripts\\python.exe', virtualenv: null, conda_env: null }, + config: { path: 'C:\\Users\\x\\AppData\\Local\\comfy-cli\\config.ini', default_workspace: null, recent_workspace: null, tracking_enabled: false, background: null }, + server: { running: state.serverRunning === true, url: state.serverRunning === true ? 'http://127.0.0.1:8188' : null }, + hardware: { os: 'Windows', os_version: '11', arch: 'AMD64', cpu: 'AMD64 Family', ram_bytes: 34265317376, gpu: { vendor: 'nvidia', model: 'NVIDIA GeForce RTX 3090', vram_bytes: 25769803776, unified_memory: false } }, + workspace: { + path: state.workspace ?? 'C:\\Users\\x\\Documents\\comfy\\ComfyUI', + type: 'default', + exists: workspaceExists, + desktop: { + install_id: null, + name: null, + code_dir: null, + data_dir: null, + custom_nodes_dir: null, + python: null, + model_roots: state.modelRoots ?? [], + comfyui_version: null, + comfy_commit: null, + selected_reason: null, + installs: [ + { + install_id: 'inst-1', + name: 'sdf', + code_dir: state.installCode ?? 'C:\\Users\\x\\ComfyUI-Installs\\sdf\\ComfyUI', + data_dir: state.installData ?? 'C:\\Users\\x\\ComfyUI-Installs\\sdf\\ComfyUI', + comfyui_version: '0.21.1', + last_launched_at: null, + status: null, + exists: installExists, + selected: false, + }, + ], + app_data_dir: 'C:\\Users\\x\\AppData\\Roaming\\Comfy Desktop', + }, + manager_mode: state.mode === 'installed-manager' ? 'enabled' : 'not-installed', + manager_detected: state.mode === 'installed-manager' ? 'comfyui-manager' : 'none', + uv_compile_default: false, + }, + warnings: state.mode === 'gone' ? [{ code: 'workspace_not_found', message: 'Workspace directory does not exist: ' + (state.workspace ?? 'C:\\Users\\x\\Documents\\comfy\\ComfyUI') }] : [], + } + if (joined.endsWith('--version')) return { status: 0, stdout: envelope('version', { version: '1.29.0' }) + '\n', stderr: '' } + if (argv.includes('env')) return { status: 0, stdout: envelope('env', envData) + '\n', stderr: '' } + if (argv.includes('which')) return { status: 0, stdout: envelope('which', { workspace_path: envData.workspace.path, workspace_type: 'default', exists: envData.workspace.exists }) + '\n', stderr: '' } + if (argv.includes('deps-in-workflow')) { + if (state.mode === 'no-manager') return { status: 1, stdout: '', stderr: "ComfyUI-Manager not found. 'cm-cli' command is not available.\n" } + const outputArg = argv.find((entry) => entry.startsWith('--output=')) + if (outputArg !== undefined) writeFileSync(outputArg.slice('--output='.length), JSON.stringify({ custom_nodes: ['comfyui-impact-pack'], models: [{ url: 'https://example.invalid/m.safetensors' }] }), 'utf8') + return { status: 0, stdout: envelope('node deps-in-workflow', { output: outputArg === undefined ? '' : outputArg.slice('--output='.length) }) + '\n', stderr: '' } + } + if (argv.includes('run')) { + if (state.mode === 'no-workspace') return { status: 1, stdout: '', stderr: "'C:\\Users\\x\\Documents\\comfy\\ComfyUI' is not a valid ComfyUI workspace.\nRun comfy install to set up ComfyUI, or use --workspace to specify a valid path.\n" } + return { status: 0, stdout: envelope('run', { prompt_id: '9f2c1d4e-0000-4000-8000-000000000000', number: 3 }) + '\n', stderr: '' } + } + if (argv.includes('download')) return { status: 0, stdout: envelope('download', { files: ['out.png'] }) + '\n', stderr: '' } + if (argv.includes('launch')) return { status: 0, stdout: envelope('launch', { background: true }) + '\n', stderr: '' } + if (argv.includes('stop')) return { status: 0, stdout: envelope('stop', { stopped: true }) + '\n', stderr: '' } + return { status: 1, stdout: envelopeError('unknown', 'usage_error', 'unexpected argv: ' + joined) + '\n', stderr: 'unexpected argv: ' + joined } + } +} + +const stubCtx = { logger: { info() {}, warn() {} }, get: () => undefined, effect: (fn) => fn() } +const exec = { agent: { session: { id: 's1', header: { cwd: workspace } } }, signal: new AbortController().signal } +/** Deps whose ENV is merged, never replaced: the temp DSH_HOME must survive a test that only moves the URL. */ +const makeDeps = (overrides = {}) => { + const { env: envOverrides, ...rest } = overrides + return createDeps(stubCtx, { + sleep: async () => {}, + ...rest, + env: { DSH_HOME: home, DSH_COMFYUI_ROOT: projectsRootDir, DSH_COMFYUI_URL: fake.origin, ...(envOverrides ?? {}) }, + }) +} +const deps = makeDeps() +const tools = buildTools(deps) +const tool = (name) => tools.find((entry) => entry.name === name) + +try { + // ------------------------------------------------------------------------- + // The registration + // ------------------------------------------------------------------------- + check('seven tools are registered', tools.map((entry) => entry.name).join(','), __internals.CAPABILITIES.tools.join(',')) + check( + 'every tool declares a JSON-schema surface', + tools.every((entry) => entry.parameters && entry.parameters.type === 'object' && entry.output && typeof entry.output.render === 'function' && typeof entry.execute === 'function'), + true, + ) + check('every tool has an execute and a card', tools.every((entry) => typeof entry.execute === 'function' && typeof entry.presentCall === 'function'), true) + check('the activation line names the loopback ports', /127\.0\.0\.1:8188/.test(activationLine(makeDeps({ env: { DSH_COMFYUI_URL: '' } }))), true) + check('...and says nothing is started', /nothing is started/.test(activationLine(deps)), true) + check('an off-machine URL is refused before a request', resolveServers({ DSH_COMFYUI_URL: 'http://10.0.0.5:8188' }).allowed, false) + check('...with the opt-in named', resolveServers({ DSH_COMFYUI_URL: 'http://10.0.0.5:8188' }).reason.includes('DSH_COMFYUI_ALLOW_REMOTE'), true) + check('the opt-in allows it', resolveServers({ DSH_COMFYUI_URL: 'http://10.0.0.5:8188', DSH_COMFYUI_ALLOW_REMOTE: '1' }).allowed, true) + check('loopback detection is the ollama rule', isLoopbackHost('127.0.0.2') && isLoopbackHost('localhost') && !isLoopbackHost('example.com'), true) + + // ------------------------------------------------------------------------- + // comfy_status + // ------------------------------------------------------------------------- + const status = await tool('comfy_status').execute({}, exec) + check('status answers against the fake server', status.view.ok, true) + check('...naming its origin', status.view.server.origin, fake.origin) + check('...its version', status.view.server.version, '0.21.1') + check('...its device', /RTX 4060/.test(status.view.server.device), true) + check('...the catalog from the server', status.view.catalog.source, SOURCES.server) + check('...and that the catalog is complete', status.view.catalog.complete, true) + check('...the class count', status.view.catalog.classes, Object.keys(OBJECT_INFO).length) + check('the catalog was cached for offline use', existsSync(status.view.catalog.file), true) + const noCliStatus = await buildTools(makeDeps({ env: { DSH_COMFYUI_URL: fake.origin }, runner: async () => ({ status: null, stdout: '', stderr: '', error: 'not found' }) })) + .find((entry) => entry.name === 'comfy_status') + .execute({}, exec) + check('status names the CLI gap when there is no comfy', /comfy-cli: no `comfy` on PATH/.test(noCliStatus.text), true) + const downStatus = await buildTools(makeDeps({ env: { DSH_COMFYUI_URL: 'http://127.0.0.1:1' } })).find((entry) => entry.name === 'comfy_status').execute({}, exec) + check('status says nothing was started', /Nothing was started/.test(downStatus.text), true) + + // A machine with nothing: no server, and the cache written above is used. + const offline = buildTools(makeDeps({ env: { DSH_COMFYUI_URL: 'http://127.0.0.1:1' } })) + const offlineStatus = await offline.find((entry) => entry.name === 'comfy_status').execute({}, exec) + check('with no server the cached catalog is used', offlineStatus.view.catalog.source, SOURCES.cache) + check('...and it says so', /no server answered/.test(offlineStatus.view.catalog.described) || /no server/i.test(offlineStatus.text), true) + + // ------------------------------------------------------------------------- + // comfy_nodes + // ------------------------------------------------------------------------- + const cats = await tool('comfy_nodes').execute({ action: 'categories' }, exec) + check('categories lists them', /sampling/.test(cats.text) && /image\/upscaling/.test(cats.text), true) + const one = await tool('comfy_nodes').execute({ action: 'node', node: 'KSampler' }, exec) + check('node prints the input table', /INPUT\s+TYPE\s+KIND/.test(one.text), true) + check('...and the widget order with the control value', /widgets_values order: seed, steps, cfg, sampler_name, scheduler, denoise/.test(one.text), true) + check('...marking control_after_generate', /control_after_generate value right after seed/.test(one.text), true) + check('...and the output slots', /LATENT/.test(one.text), true) + check('an unknown class is refused with the nearest', (await tool('comfy_nodes').execute({ action: 'node', node: 'KSamplr' }, exec)).view.code, 'NO_NODE') + const search = await tool('comfy_nodes').execute({ action: 'search', query: 'sampler' }, exec) + check('search finds KSampler', search.view.hits.includes('KSampler'), true) + check('search with no match is refused', (await tool('comfy_nodes').execute({ action: 'search', query: 'zzzznothing' }, exec)).view.code, 'NO_MATCH') + + // ------------------------------------------------------------------------- + // comfy_project: new, build, show, list, import + // ------------------------------------------------------------------------- + const created = await tool('comfy_project').execute({ action: 'new', template: 'smoke-image', name: 'first-run' }, exec) + check('a project is created from a template', created.view.ok, true) + check('...reaching v2-schema against a live server', created.view.rung, 'v2-schema') + check('...and it writes the five files', ['project.json', 'workflow.json', 'prompt.json', 'README.md', 'build.json'].every((name) => existsSync(path.join(projectsRootDir, 'first-run', name))), true) + check('the build receipt records the catalog', readJson(path.join(projectsRootDir, 'first-run', 'build.json')).catalog.source, SOURCES.server) + check('the README says the canvas is generated', /GENERATED/.test(readFileSync(path.join(projectsRootDir, 'first-run', 'README.md'), 'utf8')), true) + check('creating it again is refused, not overwritten', (await tool('comfy_project').execute({ action: 'new', template: 'smoke-image', name: 'first-run' }, exec)).view.code, 'PROJECT_EXISTS') + const listed = await tool('comfy_project').execute({ action: 'list' }, exec) + check('list shows it', listed.view.projects.map((entry) => entry.slug).join(','), 'first-run') + const shown = await tool('comfy_project').execute({ action: 'show', project: 'first-run' }, exec) + check('show prints the nodes and the receipt', /Empty Image/.test(shown.text) && /built:/.test(shown.text), true) + const rebuilt = await tool('comfy_project').execute({ action: 'build', project: 'first-run' }, exec) + check('build rewrites the generated files', rebuilt.view.rung, 'v2-schema') + const dry = await tool('comfy_project').execute({ action: 'build', project: 'first-run', dryRun: true }, exec) + check('a dry build reports without writing', dry.view.files !== undefined && Object.keys(dry.view.files).length === 0, true) + const imported = await tool('comfy_project').execute({ action: 'import', source: path.join(projectsRootDir, 'first-run', 'workflow.json'), name: 'imported' }, exec) + check('a canvas is imported as a workflow project', imported.view.kind, 'workflow') + check('...and lowered to a prompt', imported.view.rung, 'v2-schema') + check('...with the same wires', readJson(path.join(projectsRootDir, 'imported', 'prompt.json'))['2'].inputs.images.join(','), '1,0') + check('importing a prompt.json works too', (await tool('comfy_project').execute({ action: 'import', source: path.join(projectsRootDir, 'first-run', 'prompt.json'), name: 'imported-prompt' }, exec)).view.kind, 'prompt') + check('new needs a template or a spec', (await tool('comfy_project').execute({ action: 'new' }, exec)).view.code, 'BAD_ARGUMENT') + const inline = await tool('comfy_project').execute({ action: 'new', name: 'inline', spec: { name: 'inline', nodes: [{ key: 'e', class: 'EmptyImage', widgets: { width: 64, height: 64, batch_size: 1, color: 0 } }, { key: 's', class: 'SaveImage', widgets: { filename_prefix: 'x' }, wires: { images: 'e.IMAGE' } }] } }, exec) + check('a spec written inline becomes a project', inline.view.ok, true) + + // ------------------------------------------------------------------------- + // comfy_validate + // ------------------------------------------------------------------------- + const valid = await tool('comfy_validate').execute({ project: 'first-run' }, exec) + check('validate answers with the rung', valid.view.rung, 'v2-schema') + check('...and no findings', valid.view.findings.length, 0) + check('...saying what that proves', /every class exists in this server/.test(valid.text), true) + check('validate needs exactly one target', (await tool('comfy_validate').execute({}, exec)).view.code, 'BAD_ARGUMENT') + check('a file that is not there is refused by name', (await tool('comfy_validate').execute({ file: 'nope.json' }, exec)).view.code, 'NO_FILE') + const canvasFile = path.join(projectsRootDir, 'first-run', 'workflow.json') + const validatedCanvas = await tool('comfy_validate').execute({ file: canvasFile }, exec) + check('a canvas validates as a canvas', validatedCanvas.view.kind, 'workflow') + const promptFile = path.join(projectsRootDir, 'first-run', 'prompt.json') + check('a prompt validates as a prompt', (await tool('comfy_validate').execute({ file: promptFile }, exec)).view.kind, 'prompt') + + // ------------------------------------------------------------------------- + // comfy_run + // ------------------------------------------------------------------------- + const ran = await tool('comfy_run').execute({ project: 'first-run' }, exec) + check('a run answers', ran.view.ok, true) + check('...at v4-executed', ran.view.rung, 'v4-executed') + check('...with the prompt id', ran.view.promptId, 'prompt-0001') + check('...and the file it produced', ran.view.files.length + ':' + ran.view.files[0].filename, '1:smoke_00001_.png') + check('...naming the node that saved it', ran.view.files[0].nodeTitle, 'Save Image') + check('...and a /view url', /\/view\?filename=/.test(ran.text), true) + check('the run posted the compiled prompt', requests.some((entry) => entry.method === 'POST' && entry.path === '/prompt' && entry.body.prompt['1'].class_type === 'EmptyImage'), true) + check('a project with an error is NOT queued', (await tool('comfy_run').execute({ project: 'imported-prompt' }, exec)).view.ok, true) + // A refusal from /prompt keeps the server's own words. + refuseNext = { + error: { type: 'prompt_outputs_failed_validation', message: 'Prompt outputs failed validation', details: '' }, + node_errors: { '1': { errors: [{ type: 'value_not_in_list', message: 'Value not in list', details: "ckpt_name: 'nope.safetensors' not in ['v1-5.safetensors']" }], dependent_outputs: ['2'], class_type: 'CheckpointLoaderSimple' } }, + } + const refused = await tool('comfy_run').execute({ project: 'first-run' }, exec) + check('a 400 from /prompt is a typed refusal', refused.view.code, 'PROMPT_REFUSED') + check('...keeping the node_errors', refused.view.findings[0].type, 'value_not_in_list') + check('...and the server sentence', /Value not in list/.test(refused.text), true) + + // ------------------------------------------------------------------------- + // comfy_test: the library, compile and run + // ------------------------------------------------------------------------- + const compileAll = await tool('comfy_test').execute({ action: 'compile' }, exec) + check('compile answers for the whole library', compileAll.view.total, 4) + check('...with every example at v2 against a live catalog', compileAll.view.results.every((entry) => entry.rung === 'v2-schema'), true) + check('...and a rung tally', compileAll.view.rungs['v2-schema'], 4) + check('...printed as a tally', /Rungs: v2-schema/.test(compileAll.text), true) + check('compile writes nothing', existsSync(path.join(projectsRootDir, 'text-to-image')), false) + const subset = await tool('comfy_test').execute({ action: 'compile', examples: ['smoke-image'] }, exec) + check('a subset compiles just those', subset.view.total, 1) + const withProjects = await tool('comfy_test').execute({ action: 'compile', examples: ['smoke-image'], includeProjects: true }, exec) + check('includeProjects adds the workspace ones', withProjects.view.total > 1, true) + const runAll = await tool('comfy_test').execute({ action: 'run', examples: ['smoke-image', 'smoke-video'] }, exec) + check('run queues each example', runAll.view.results.length, 2) + check('...and reports v4 for the ones that produced files', runAll.view.results.map((entry) => entry.rung).join(','), 'v4-executed,v4-executed') + check('run with no server is a refusal naming the compile path', (await buildTools(makeDeps({ env: { DSH_COMFYUI_URL: 'http://127.0.0.1:1' } })).find((entry) => entry.name === 'comfy_test').execute({ action: 'run' }, exec)).view.code, 'SERVER_DOWN') + + // ------------------------------------------------------------------------- + // comfy_cli - against the REAL 1.29.0 envelope shapes + // ------------------------------------------------------------------------- + const cliState = { calls: [], mode: 'ok', installCode: path.join(sandbox, 'comfy-install', 'ComfyUI'), installData: path.join(sandbox, 'comfy-install', 'ComfyUI') } + mkdirSync(cliState.installCode, { recursive: true }) + writeFileSync(path.join(cliState.installCode, 'main.py'), '# comfyui\n', 'utf8') + writeFileSync(path.join(cliState.installCode, 'comfyui_version.py'), "__version__ = '0.21.1'\n", 'utf8') + const cliDeps = makeDeps({ runner: fakeRunner(cliState) }) + const cliTools = buildTools(cliDeps) + const cli = (name) => cliTools.find((entry) => entry.name === name) + + const cliStatus = await cli('comfy_cli').execute({ action: 'status' }, exec) + check('the CLI is found and versioned from the envelope', cliStatus.view.version, '1.29.0') + check('...reading the workspace from env', cliStatus.view.workspace, 'C:\\Users\\x\\Documents\\comfy\\ComfyUI') + check('...and which agrees', cliStatus.view.which, 'C:\\Users\\x\\Documents\\comfy\\ComfyUI') + check('...the GPU it reports', /RTX 3090/.test(cliStatus.text), true) + check('...the workspace it names, marked as missing', /ComfyUI \(DOES NOT EXIST\)/.test(cliStatus.text), true) + check('...the Desktop install it knows, with its code dir', cliStatus.view.installs.map((entry) => entry.name + ':' + entry.codeDir).join(','), 'sdf:' + cliState.installCode) + check('...and that the Manager is missing', /not-installed/.test(cliStatus.text), true) + check('the argv puts the global --json before the subcommand', argvFor('comfy', ['env']).join(' '), 'comfy --json env') + check('...and --workspace before it too', argvFor('comfy', ['env'], { workspace: 'C:\\ws' }).join(' '), 'comfy --workspace=C:\\ws --json env') + + const cliDepsRun = await cli('comfy_cli').execute({ action: 'deps', project: 'first-run' }, exec) + check('deps reports the node packs a workflow needs', /comfyui-impact-pack/.test(cliDepsRun.text), true) + check('...from the file the CLI wrote', cliDepsRun.view.deps.custom_nodes[0], 'comfyui-impact-pack') + check('...and passes the install as --workspace, because the default does not exist', cliDepsRun.view.workspace, cliState.installCode) + check('...naming why in the answer', /does not exist/.test(cliDepsRun.text), true) + + const cliRun = await cli('comfy_cli').execute({ action: 'run', project: 'first-run' }, exec) + check('run hands the canvas to the CLI', cliRun.view.exitCode, 0) + check('...and reads the prompt_id out of the envelope', cliRun.view.promptId, '9f2c1d4e-0000-4000-8000-000000000000') + check('...reporting the independent rung', cliRun.view.rung, 'v4-executed') + check('the argv is `comfy --json run --workflow --wait`', runArgv('comfy', 'w.json').join(' '), 'comfy --json run --workflow w.json --wait') + check('the argv is `comfy --json node deps-in-workflow --workflow= --output=`', depsArgv('comfy', 'w.json', 'd.json').join(' '), 'comfy --json node deps-in-workflow --workflow=w.json --output=d.json') + check('launch starts a background instance', (await cli('comfy_cli').execute({ action: 'launch' }, exec)).view.exitCode, 0) + check('stop stops it', (await cli('comfy_cli').execute({ action: 'stop' }, exec)).view.exitCode, 0) + check('an explicit workspace wins over the auto-pick', (await cli('comfy_cli').execute({ action: 'deps', project: 'first-run', workspace: 'D:\\mine' }, exec)).view.workspace, 'D:\\mine') + + // The two refusals comfy-cli gives BEFORE it reads a graph, as sentences. + cliState.mode = 'no-manager' + const noManager = await cli('comfy_cli').execute({ action: 'deps', project: 'first-run' }, exec) + check('a workspace without ComfyUI-Manager is explained', /no ComfyUI-Manager/.test(noManager.text), true) + check('...and the answer still names the exit code', /exit code: 1/.test(noManager.text), true) + cliState.mode = 'no-workspace' + const noWorkspace = await cli('comfy_cli').execute({ action: 'run', project: 'first-run' }, exec) + check('a missing workspace is explained with the fix', /could not resolve a ComfyUI workspace/.test(noWorkspace.view.explanation), true) + check('...and the run reports failure, not success', noWorkspace.view.ok, false) + cliState.mode = 'gone' + const goneInstall = await cli('comfy_cli').execute({ action: 'status' }, exec) + check('a Desktop install whose folder is gone says so', /the folder is GONE/.test(goneInstall.text), true) + check('...and comfy-cli\'s own warning is repeated', /Workspace directory does not exist/.test(goneInstall.text), true) + cliState.mode = 'ok' + + const noCli = buildTools(makeDeps({ runner: async () => ({ status: null, stdout: '', stderr: '', error: 'ENOENT' }) })).find((entry) => entry.name === 'comfy_cli') + const missing = await noCli.execute({ action: 'status' }, exec) + check('no CLI is an ANSWER, not a failure', missing.view.code, 'CLI_MISSING') + check('...naming the install line', /pip install comfy-cli/.test(missing.text), true) + check('...and saying the HTTP tools need no CLI', /HTTP tools need none of it/.test(missing.text), true) + check( + 'a CLI never runs install: no argv here can', + cliState.calls.every((argv) => { + const subcommand = argv.slice(1).find((token) => !token.startsWith('-')) ?? '' + return subcommand !== 'install' + }), + true, + ) + + // ------------------------------------------------------------------------- + // The CLI helpers, pure - the envelope, not a guess at it + // ------------------------------------------------------------------------- + // Verbatim 1.29.0 output for `comfy --json env` on a machine whose Desktop + // install is gone. Every field this row reads is asserted against it. + const REAL_ENV = { + schema: 'envelope/1', + type: 'envelope', + ok: true, + command: 'env', + version: '1.29.0', + where: null, + data: { + python: { version: '3.14.3', executable: 'C:\\uv\\Scripts\\python.exe', virtualenv: null, conda_env: null }, + config: { path: 'C:\\Users\\me\\AppData\\Local\\comfy-cli\\config.ini', default_workspace: null, recent_workspace: null, tracking_enabled: false, background: null }, + server: { running: false, url: null }, + hardware: { os: 'Windows', os_version: '11', arch: 'AMD64', cpu: 'AMD64 Family 25', ram_bytes: 34265317376, gpu: { vendor: 'nvidia', model: 'NVIDIA GeForce RTX 3090', vram_bytes: 25769803776, unified_memory: false } }, + workspace: { + path: 'C:\\Users\\me\\Documents\\comfy\\ComfyUI', + type: 'default', + exists: false, + desktop: { + install_id: null, + name: null, + code_dir: null, + data_dir: null, + custom_nodes_dir: null, + python: null, + model_roots: [], + comfyui_version: null, + comfyui_commit: null, + selected_reason: null, + installs: [{ install_id: 'inst-1', name: 'sdf', code_dir: 'C:\\Users\\me\\ComfyUI-Installs\\sdf\\ComfyUI', data_dir: 'C:\\Users\\me\\ComfyUI-Installs\\sdf\\ComfyUI', comfyui_version: null, last_launched_at: null, status: null, exists: false, selected: false }], + app_data_dir: 'C:\\Users\\me\\AppData\\Roaming\\Comfy Desktop', + }, + manager_mode: 'not-installed', + manager_detected: 'none', + uv_compile_default: false, + }, + warnings: [{ code: 'workspace_not_found', message: 'Workspace directory does not exist: C:\\Users\\me\\Documents\\comfy\\ComfyUI' }], + }, + error: null, + } + const realFacts = envFacts(REAL_ENV.data) + check('the workspace path is read from data.workspace.path', realFacts.workspace, 'C:\\Users\\me\\Documents\\comfy\\ComfyUI') + check('...and that it does NOT exist', realFacts.workspaceExists, false) + check('the server flag comes from data.server.running', realFacts.serverRunning, false) + check('the python is data.python.executable', /Scripts\\python\.exe$/.test(realFacts.python), true) + check('the GPU is data.hardware.gpu.model', realFacts.gpu, 'NVIDIA GeForce RTX 3090') + check('the VRAM travels', realFacts.vramBytes, 25769803776) + check('the Manager mode travels', realFacts.managerMode, 'not-installed') + check('the Desktop installs are read whole', realFacts.installs.length + ':' + realFacts.installs[0].name + ':' + realFacts.installs[0].exists, '1:sdf:false') + check('the warnings are read', /Workspace directory does not exist/.test(realFacts.warnings[0].message), true) + check('a config path is never mistaken for the workspace', realFacts.workspace.includes('config.ini'), false) + check('which reads workspace_path', whichFacts({ workspace_path: '/w/ComfyUI', exists: true }).workspace, '/w/ComfyUI') + check('a version comes from the envelope top level, not a regex', (await cliVersion(async () => ({ status: 0, stdout: JSON.stringify({ schema: 'envelope/1', type: 'envelope', ok: true, version: '2.0.1', data: { version: '2.0.1' } }) + '\n', stderr: '' }), {})).version, '2.0.1') + check('a CLI that cannot start is found:false', (await cliVersion(async () => ({ status: null, stdout: '', stderr: '', error: 'ENOENT' }), {})).found, false) + check('an envelope with a log line before it still parses', parseEnvelope('INFO starting\n{"workspace": "/x"}').data.workspace, '/x') + check('a run envelope carries the prompt id', promptIdFromRunText('{"ok":true,"data":{"prompt_id":"9f2c1d4e-0000-4000-8000-000000000000"}}'), '9f2c1d4e-0000-4000-8000-000000000000') + check('a prompt_id is still read out of prose', promptIdFromRunText('submitted prompt_id: 9f2c1d4e-0000-4000-8000-000000000000'), '9f2c1d4e-0000-4000-8000-000000000000') + check('the workspace refusal is explained', /comfy install/.test(explainCliFailure("'C:\\x' is not a valid ComfyUI workspace.\nRun comfy install to set up ComfyUI")), true) + check('the Manager refusal is explained', /Desktop install keeps its Manager/.test(explainCliFailure("ComfyUI-Manager not found. 'cm-cli' command is not available.")), true) + check('an unknown failure gets no invented explanation', explainCliFailure('something else'), '') + check('bytes read like a person writes them', formatBytes(8 * 1024 ** 3), '8.0 GiB') + + // ------------------------------------------------------------------------- + // The files on disk - the check that only matters once models exist + // ------------------------------------------------------------------------- + // A base path with one checkpoint, one LoRA and one input image, and a + // project that names the RIGHT checkpoint and the WRONG lora. + const fileBase = path.join(sandbox, 'ComfyUI') + mkdirSync(path.join(fileBase, 'models', 'checkpoints'), { recursive: true }) + mkdirSync(path.join(fileBase, 'models', 'loras'), { recursive: true }) + mkdirSync(path.join(fileBase, 'input'), { recursive: true }) + writeFileSync(path.join(fileBase, 'models', 'checkpoints', 'v1-5-pruned-emaonly-fp16.safetensors'), 'x', 'utf8') + writeFileSync(path.join(fileBase, 'models', 'loras', 'lcm-lora-sd15.safetensors'), 'x', 'utf8') + writeFileSync(path.join(fileBase, 'input', 'example.png'), 'x', 'utf8') + const presentInstall = { found: true, base: fileBase, baseSource: 'test', app: '', version: '0.21.1', python: '', models: {}, modelRoots: [], customNodes: [], notes: [] } + check('the files are found where ComfyUI would look', checkPromptFiles({ prompt: {}, catalog: coreCatalog(), install: presentInstall, requires: { models: { checkpoints: ['v1-5-pruned-emaonly-fp16.safetensors'] }, inputFiles: ['example.png'] } }).findings.length, 0) + const missingLora = checkPromptFiles({ + prompt: { '2': { class_type: 'LoraLoader', inputs: { lora_name: 'lcm-lora-sdXL.safetensors', strength_model: 1, strength_clip: 1 } } }, + catalog: coreCatalog(), + install: presentInstall, + requires: { models: {}, inputFiles: [] }, + }) + check('a missing model is value_not_in_list, the server type', missingLora.findings[0].type, 'value_not_in_list') + check('...naming the folder and the count', /models\/loras\/lcm-lora-sdXL\.safetensors does not exist .*1 file\(s\) there/.test(missingLora.findings[0].message), true) + check('...and the nearest real name', /nearest: lcm-lora-sd15\.safetensors/.test(missingLora.findings[0].message), true) + check('...with the node and input it belongs to', missingLora.findings[0].node + '/' + missingLora.findings[0].input, '2/lora_name') + check('a complete catalog answers for itself, so no second opinion', checkPromptFiles({ prompt: { '2': { class_type: 'LoraLoader', inputs: { lora_name: 'not-there.safetensors' } } }, catalog: completeCatalog, install: presentInstall, requires: {} }).findings.length, 0) + const absentFolder = checkPromptFiles({ prompt: {}, catalog: coreCatalog(), install: presentInstall, requires: { models: { vae: ['thing.safetensors'] } } }) + check('an absent FOLDER is a warning, not a missing file', absentFolder.findings[0].type, 'model_folder_absent') + const noBase = checkPromptFiles({ prompt: {}, catalog: coreCatalog(), install: { found: false, base: '' }, requires: { models: { checkpoints: ['x.safetensors'] } } }) + check('with no base path nothing is claimed at all', noBase.findings.length + ':' + /no ComfyUI base path/.test(noBase.skipped), '0:true') + // And the same check through a real build: the shipped text-to-image example + // against a base path that HAS its checkpoint but NOT its LoRA. + const partialBase = path.join(sandbox, 'ComfyUI-partial') + mkdirSync(path.join(partialBase, 'models', 'checkpoints'), { recursive: true }) + mkdirSync(path.join(partialBase, 'models', 'loras'), { recursive: true }) + writeFileSync(path.join(partialBase, 'models', 'checkpoints', 'v1-5-pruned-emaonly-fp16.safetensors'), 'x', 'utf8') + const partialInstall = { ...presentInstall, base: partialBase } + const partialBuild = buildFromSpec({ raw: readExample('text-to-image'), paths: dryPaths, catalog: coreCatalog(), dryRun: true, install: partialInstall }) + check('a build reports the missing file by name', partialBuild.findings.filter((entry) => entry.type === 'value_not_in_list').map((entry) => entry.input).join(','), 'lora_name') + check('...so the project is not called runnable', partialBuild.ok, false) + const fullBuild = buildFromSpec({ raw: readExample('text-to-image'), paths: dryPaths, catalog: coreCatalog(), dryRun: true, install: presentInstall }) + check('with both files present the build is clean again', fullBuild.ok, true) + check('...and records what it checked', fullBuild.fileCheck.checked, 2) + check('...against the folders it read', fullBuild.fileCheck.roots.length, 2) + const inventoryFacts = inventory(presentInstall) + check('the inventory counts per folder', inventoryFacts.folders.checkpoints.count + '/' + inventoryFacts.folders.loras.count + '/' + inventoryFacts.folders.input.count, '1/1/1') + check('...and names the first file', inventoryFacts.folders.checkpoints.first[0], 'v1-5-pruned-emaonly-fp16.safetensors') + check('...with a file total', inventoryFacts.files, 2) + + // ------------------------------------------------------------------------- + // Install discovery, without a server - and with comfy-cli's help + // ------------------------------------------------------------------------- + const bareHome = path.join(sandbox, 'nohome') + const install = discoverInstall({ env: { USERPROFILE: bareHome, HOME: bareHome, APPDATA: path.join(bareHome, 'AppData', 'Roaming') }, platform: 'linux' }) + check('a machine with nothing found says so', install.found, false) + check('...and still answers with the fields', install.base === '' && install.app === '' && install.notes.length > 0, true) + check('the slugifier refuses a name that is not one', slugify(' *** '), '') + // comfy-cli knows a Desktop install whose folder DOES exist: that becomes the base. + const cliFacts = envFacts(REAL_ENV.data) + cliFacts.installs[0].exists = true + cliFacts.installs[0].dataDir = fileBase + const fromCli = discoverInstall({ env: { USERPROFILE: bareHome, HOME: bareHome, APPDATA: path.join(bareHome, 'AppData', 'Roaming') }, platform: 'linux', cli: cliFacts }) + check("comfy-cli's install becomes the base path", fromCli.base, fileBase) + check('...and says where it came from', /comfy-cli/.test(fromCli.baseSource), true) + // ------------------------------------------------------------------------- + // The skills: frontmatter, and every fenced example + // ------------------------------------------------------------------------- + const skillsRoot = path.join(packageRoot, 'skills') + const skillDirs = readdirSync(skillsRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort() + check('six skill folders ship', skillDirs.length, 6) + const docs = [] + for (const dir of skillDirs) { + const file = path.join(skillsRoot, dir, 'SKILL.md') + const text = readFileSync(file, 'utf8') + const parsed = parseSkillFile(text) + check('skill ' + dir + ' has frontmatter with the right name', parsed.meta.name, dir) + check('skill ' + dir + ' has a description over 80 characters', typeof parsed.meta.description === 'string' && parsed.meta.description.length > 80, true) + check('skill ' + dir + ' says when to use it', typeof parsed.meta.whenToUse === 'string' && parsed.meta.whenToUse.length > 40, true) + check('skill ' + dir + ' has a real body', parsed.content.length > 2000, true) + docs.push({ dir, file, text }) + } + check('the six skills are the six registered', skillDirs.join(','), __internals.CAPABILITIES.skills.slice().sort().join(',')) + + /** The fenced blocks of one document, with the no-check convention. */ + function fences(text) { + const lines = String(text).split('\n') + const blocks = [] + let open = null + for (let index = 0; index < lines.length; index += 1) { + const match = /^\s*```([A-Za-z0-9_+-]*)\s*(.*)$/.exec(lines[index]) + if (!match) { + if (open) open.body.push(lines[index]) + continue + } + if (open === null) open = { lang: match[1].toLowerCase(), line: index + 1, body: [], skip: /no-check/i.test(match[2]) } + else { + blocks.push(open) + open = null + } + } + return blocks + } + + const knownRoutes = __internals.CAPABILITIES.endpoints + /** A route with any concrete class/id/folder folded back to its placeholder. */ + const routeKey = (route) => + route + .replace(/^\/object_info\/[^/]+$/, '/object_info/{class}') + .replace(/^\/history\/[^/]+$/, '/history/{prompt_id}') + .replace(/^\/models\/[^/]+$/, '/models/{folder}') + const KNOWN_VERBS = new Set(['install', 'update', 'launch', 'stop', 'run', 'jobs', 'download', 'upload', 'env', 'which', 'set-default', 'node', 'nodes', 'model', 'models', 'manager', 'extension', 'system-stats', 'free', 'tracking', 'cloud', 'generate', 'templates', 'skills', 'knowledge', 'setup', 'pr-cache']) + const blocks = docs.flatMap((doc) => fences(doc.text).map((block) => ({ doc, block }))) + let jsonCount = 0 + let jsCount = 0 + let pyCount = 0 + let curlCount = 0 + let comfyCount = 0 + const pythonAvailable = spawnSync('python', ['-c', 'import ast'], { encoding: 'utf8' }).status === 0 + for (const { doc, block } of blocks) { + const where = doc.dir + ':' + block.line + if (block.skip) { + skip(where, 'no-check') + continue + } + const body = block.body.join('\n') + if (block.lang === 'json') { + jsonCount += 1 + let parsed = null + try { + parsed = JSON.parse(body) + } catch (error) { + parsed = null + } + check(where + ' is valid JSON', parsed !== null && typeof parsed === 'object', true) + } else if (block.lang === 'js' || block.lang === 'javascript') { + jsCount += 1 + const file = path.join(sandbox, 'block-' + jsCount + '.mjs') + writeFileSync(file, body, 'utf8') + const result = spawnSync('node', ['--check', file], { encoding: 'utf8' }) + check(where + ' passes node --check', result.status === 0, true) + } else if (block.lang === 'python' || block.lang === 'py') { + pyCount += 1 + if (!pythonAvailable) { + skip(where + ' parses as Python', 'no python on PATH') + continue + } + const result = spawnSync('python', ['-c', 'import ast,sys; ast.parse(sys.stdin.read())'], { input: body, encoding: 'utf8' }) + check(where + ' parses as Python', result.status === 0, true) + } else if (['bash', 'sh', 'shell', 'console'].includes(block.lang)) { + for (const line of body.split('\n')) { + const trimmed = line.trim() + if (/^curl\s/.test(trimmed)) { + curlCount += 1 + const urlMatch = /(https?:\/\/[^\s"']+)/.exec(trimmed) + check(where + ' curl names a loopback URL', urlMatch !== null && /^http:\/\/(127\.0\.0\.1|localhost):(8188|800[0-3])\//.test(urlMatch[1]), true) + if (urlMatch !== null) { + const route = urlMatch[1].replace(/^https?:\/\/(127\.0\.0\.1|localhost):\d+/, '').split('?')[0] + check(where + ' curl names a documented route (' + route + ')', knownRoutes.includes(routeKey(route)), true) + } + } + if (/^comfy\s/.test(trimmed)) { + comfyCount += 1 + const tokens = trimmed.split(/\s+/).slice(1).filter((token) => !token.startsWith('-')) + const verb = tokens[0] ?? '' + const bareFlag = /^comfy\s+--(version|install-completion)\b/.test(trimmed) + check(where + ' comfy names a real subcommand (' + (verb === '' ? trimmed.split(/\s+/)[1] : verb) + ')', bareFlag || KNOWN_VERBS.has(verb), true) + } + } + } + } + check('the skills carry JSON examples', jsonCount >= 6, true) + check('the skills carry JavaScript examples', jsCount >= 1, true) + check('the skills carry Python examples', pyCount >= 3, true) + check('the skills carry curl examples', curlCount >= 3, true) + check('the skills carry comfy-cli commands', comfyCount >= 10, true) + + // ------------------------------------------------------------------------- + // The optional live half: a real server, if one is running + // ------------------------------------------------------------------------- + if (process.env.DSH_COMFYUI_CHECK_LIVE === '0') skip('live ComfyUI', 'DSH_COMFYUI_CHECK_LIVE=0') + else { + const liveEnv = { DSH_HOME: home, DSH_COMFYUI_ROOT: path.join(workspace, 'live'), ...(process.env.DSH_COMFYUI_URL ? { DSH_COMFYUI_URL: process.env.DSH_COMFYUI_URL } : {}) } + const liveTools = buildTools(createDeps(stubCtx, { env: liveEnv })) + const liveStatus = await liveTools.find((entry) => entry.name === 'comfy_status').execute({}, exec) + if (liveStatus.view.server === null) skip('live ComfyUI', 'no server answered') + else { + const liveTest = await liveTools.find((entry) => entry.name === 'comfy_test').execute({ action: 'compile' }, exec) + check('live: the library compiles against a real catalog', liveTest.view.results.every((entry) => entry.rung === 'v2-schema' || entry.rung === 'v1-structural'), true) + check('live: every example reached at least v1', liveTest.view.results.every((entry) => entry.rung !== 'v0-failed'), true) + } + } +} finally { + await fake.close() + rmSync(sandbox, { recursive: true, force: true }) +} + +console.log('') +console.log(checks + ' checks, ' + failures + ' failure(s), ' + skipped + ' skipped') +process.exit(failures === 0 ? 0 : 1) diff --git a/packages/dsh-comfyui/cordis.patch.yml b/packages/dsh-comfyui/cordis.patch.yml new file mode 100644 index 0000000..bf0a201 --- /dev/null +++ b/packages/dsh-comfyui/cordis.patch.yml @@ -0,0 +1,53 @@ +# dsh-comfyui bundle layer (alpha). +# +# One row ('comfyui') owns the whole plugin: its Node half registers SEVEN tools +# over the machine's own ComfyUI and six bundled skills. +# +# comfy_status what exists here (Desktop/portable install, base path, the +# venv python, the model folders), which loopback server +# answers, its version and device, and the node catalog's +# state - from the server, from the cache, or the built-in +# core table. Read-only, and nothing is started. +# comfy_nodes the node catalog: categories, one class's exact inputs and +# outputs, or a search by name/type/category. +# comfy_project new | list | show | build | import - a project is a folder +# whose project.json is the SOURCE OF TRUTH and whose +# workflow.json + prompt.json are GENERATED from it. +# comfy_validate the same checks `/prompt` applies, run offline, reported +# with ComfyUI's own error types (required_input_missing, +# return_type_mismatch, value_not_in_list, dependency_cycle, +# prompt_no_outputs) and a file:field path per finding. +# comfy_run queue a compiled prompt on the server and report what the +# history says came out - the one tool that executes work. +# comfy_test compile the shipped example library (and any project in the +# workspace), and with a server RUN it; every item reports the +# rung it reached, so "it compiles" is never printed as +# "it runs". +# comfy_cli the SECOND test path: comfy-cli (`pip install comfy-cli`) as +# `comfy run --workflow --wait` (it converts the canvas +# itself), `comfy node deps-in-workflow` (which node packs a graph +# needs), `comfy launch --background` / `comfy stop`, and its own +# `env`/`which` view - which is also a discovery source, because it +# names Desktop installs whose data dirs this row can then check. +# It never runs `comfy install`, installs a node, downloads a model +# or removes anything. +# +# Host-only: the answers are graphs, JSON and prose, so there is no route to +# serve and no browser half to load - the package declares no dsh.client, and +# the boot graph gains one row. Like dsh-ollama, dsh-docker and dsh-sql-server, +# not like dsh-research: no UI follows, and none is hidden behind an +# unregistered route. +# +# Nothing shipped is patched and no core row is disabled: core DSH has no +# ComfyUI surface, no tool reads /object_info, and nothing in the pack can turn +# a spec into a workflow the app will actually open. The harness's `bash` / +# `pwsh` tools could POST to 127.0.0.1:8188 by hand, but they cannot report +# which node class in a graph does not exist, which widget value is not in the +# server's own list, or which link carries IMAGE into a LATENT slot. +# +# Nothing for scripts/sync-vendored.ps1 either: no engine is vendored, forked or +# downloaded. ComfyUI is the user's own application; this package ships the +# compiler, the validator, the HTTP client and the example specs. +- insert: + - id: comfyui + name: 'dsh-comfyui' diff --git a/packages/dsh-comfyui/examples/image-to-image/project.json b/packages/dsh-comfyui/examples/image-to-image/project.json new file mode 100644 index 0000000..749c109 --- /dev/null +++ b/packages/dsh-comfyui/examples/image-to-image/project.json @@ -0,0 +1,120 @@ +{ + "name": "image-to-image", + "title": "Image to Image (denoise 0.55)", + "description": "The same graph as text-to-image with three nodes changed: Load Image -> Upscale Image (512, centre crop) -> VAE Encode, and the KSampler denoises that latent instead of an empty one. denoise 0.55 is a repaint, 0.35 is a filter, 0.85 is a new picture in the same pose. The Upscale node is the lesson: remove it and a phone photo takes minutes, because the cost follows the pixel count and nothing else. Needs an image in ComfyUI's input/ folder - set `bindings.inputImage` to its filename.", + "tags": ["image", "needs-models", "needs-input", "class-example"], + "requires": { + "nodes": ["LoadImage", "ImageScale", "CheckpointLoaderSimple", "LoraLoader", "CLIPTextEncode", "VAEEncode", "KSampler", "VAEDecode", "SaveImage"], + "models": { + "checkpoints": ["v1-5-pruned-emaonly-fp16.safetensors"], + "loras": ["lcm-lora-sd15.safetensors"] + }, + "inputFiles": ["example.png"] + }, + "bindings": { + "checkpoint": "v1-5-pruned-emaonly-fp16.safetensors", + "lora": "lcm-lora-sd15.safetensors", + "inputImage": "example.png", + "prompt": "warm evening light, painted from a photograph", + "negative": "blurry, extra fingers, text", + "width": 512, + "height": 512, + "steps": 4, + "cfg": 1.5, + "seed": 42, + "sampler": "lcm", + "scheduler": "sgm_uniform", + "denoise": 0.55 + }, + "nodes": [ + { + "key": "input", + "class": "LoadImage", + "title": "Load Image", + "pos": [40, 40], + "widgets": { "image": "@inputImage" } + }, + { + "key": "scale", + "class": "ImageScale", + "title": "Upscale to 512 (centre crop)", + "pos": [400, 40], + "widgets": { "upscale_method": "lanczos", "width": "@width", "height": "@height", "crop": "center" }, + "wires": { "image": "input.IMAGE" } + }, + { + "key": "ckpt", + "class": "CheckpointLoaderSimple", + "title": "Load Checkpoint", + "pos": [40, 300], + "widgets": { "ckpt_name": "@checkpoint" } + }, + { + "key": "lora", + "class": "LoraLoader", + "title": "Load LoRA (LCM)", + "pos": [400, 300], + "widgets": { "lora_name": "@lora", "strength_model": 1.0, "strength_clip": 1.0 }, + "wires": { "model": "ckpt.MODEL", "clip": "ckpt.CLIP" } + }, + { + "key": "positive", + "class": "CLIPTextEncode", + "title": "Positive prompt", + "pos": [780, 280], + "widgets": { "text": "@prompt" }, + "wires": { "clip": "lora.CLIP" } + }, + { + "key": "negative", + "class": "CLIPTextEncode", + "title": "Negative prompt", + "pos": [780, 540], + "widgets": { "text": "@negative" }, + "wires": { "clip": "lora.CLIP" } + }, + { + "key": "encode", + "class": "VAEEncode", + "title": "VAE Encode", + "pos": [780, 40], + "wires": { "pixels": "scale.IMAGE", "vae": "ckpt.VAE" } + }, + { + "key": "sampler", + "class": "KSampler", + "title": "KSampler (denoise 0.55)", + "pos": [1180, 200], + "widgets": { + "seed": "@seed", + "steps": "@steps", + "cfg": "@cfg", + "sampler_name": "@sampler", + "scheduler": "@scheduler", + "denoise": "@denoise" + }, + "controlAfterGenerate": { "seed": "fixed" }, + "wires": { + "model": "lora.MODEL", + "positive": "positive.CONDITIONING", + "negative": "negative.CONDITIONING", + "latent_image": "encode.LATENT" + } + }, + { + "key": "decode", + "class": "VAEDecode", + "title": "VAE Decode", + "pos": [1580, 200], + "wires": { "samples": "sampler.LATENT", "vae": "ckpt.VAE" } + }, + { + "key": "save", + "class": "SaveImage", + "title": "Save Image", + "pos": [1940, 200], + "widgets": { "filename_prefix": "dsh-comfyui/image-to-image" }, + "wires": { "images": "decode.IMAGE" } + } + ] +} diff --git a/packages/dsh-comfyui/examples/smoke-image/project.json b/packages/dsh-comfyui/examples/smoke-image/project.json new file mode 100644 index 0000000..cd24910 --- /dev/null +++ b/packages/dsh-comfyui/examples/smoke-image/project.json @@ -0,0 +1,29 @@ +{ + "name": "smoke-image", + "title": "Smoke: an empty image and a PNG", + "description": "The smallest graph that proves a ComfyUI server works end to end: Empty Image -> Save Image. No checkpoint, no LoRA, no input file, no custom node - so if this one runs, the server, the queue, the output folder and this package's compiler are all working, and a failure is never about a missing 2 GB download. Run it with `comfy_test` action=run first on any new machine.", + "tags": ["smoke", "no-models"], + "requires": { + "nodes": ["EmptyImage", "SaveImage"], + "models": {}, + "inputFiles": [] + }, + "bindings": {}, + "nodes": [ + { + "key": "empty", + "class": "EmptyImage", + "title": "Empty Image 512x512", + "pos": [40, 120], + "widgets": { "width": 512, "height": 512, "batch_size": 1, "color": 0 } + }, + { + "key": "save", + "class": "SaveImage", + "title": "Save Image", + "pos": [440, 120], + "widgets": { "filename_prefix": "dsh-comfyui/smoke" }, + "wires": { "images": "empty.IMAGE" } + } + ] +} diff --git a/packages/dsh-comfyui/examples/smoke-video/project.json b/packages/dsh-comfyui/examples/smoke-video/project.json new file mode 100644 index 0000000..ad605a8 --- /dev/null +++ b/packages/dsh-comfyui/examples/smoke-video/project.json @@ -0,0 +1,45 @@ +{ + "name": "smoke-video", + "title": "Smoke: 30 frames into an MP4", + "description": "One image repeated into a one-second clip: Empty Image -> Repeat Image Batch -> Create Video -> Save Video. Still no model and no input file, and it exercises the parts of the API a still image does not: an OPTIONAL input (`Create Video`'s audio, deliberately left unwired) and a node whose output is a VIDEO rather than an IMAGE. If this runs, ffmpeg and the video pack inside ComfyUI work too.", + "tags": ["smoke", "no-models", "video"], + "requires": { + "nodes": ["EmptyImage", "RepeatImageBatch", "CreateVideo", "SaveVideo"], + "models": {}, + "inputFiles": [] + }, + "bindings": {}, + "nodes": [ + { + "key": "empty", + "class": "EmptyImage", + "title": "Empty Image 512x512", + "pos": [40, 120], + "widgets": { "width": 512, "height": 512, "batch_size": 1, "color": 3368601 } + }, + { + "key": "repeat", + "class": "RepeatImageBatch", + "title": "Repeat to 30 frames", + "pos": [420, 120], + "widgets": { "amount": 30 }, + "wires": { "image": "empty.IMAGE" } + }, + { + "key": "video", + "class": "CreateVideo", + "title": "Create Video (30 fps)", + "pos": [800, 120], + "widgets": { "fps": 30 }, + "wires": { "images": "repeat.IMAGE" } + }, + { + "key": "save", + "class": "SaveVideo", + "title": "Save Video", + "pos": [1180, 120], + "widgets": { "filename_prefix": "dsh-comfyui/smoke", "format": "auto", "codec": "auto" }, + "wires": { "video": "video.VIDEO" } + } + ] +} diff --git a/packages/dsh-comfyui/examples/text-to-image/project.json b/packages/dsh-comfyui/examples/text-to-image/project.json new file mode 100644 index 0000000..831b18c --- /dev/null +++ b/packages/dsh-comfyui/examples/text-to-image/project.json @@ -0,0 +1,103 @@ +{ + "name": "text-to-image", + "title": "Text to Image (SD 1.5 + LCM-LoRA, 4 steps)", + "description": "The class build: Load Checkpoint -> Load LoRA -> two CLIP Text Encode -> Empty Latent -> KSampler -> VAE Decode -> Save Image. Four steps and cfg 1.5 because the LCM-LoRA is trained for four; a 512px image is 10-25 s on a CPU-only laptop. Every value that belongs to a machine rather than to the graph is a BINDING, so a machine with a different checkpoint rebinds instead of editing the graph: set `bindings.checkpoint` and `bindings.lora` to files that exist in ComfyUI's models/checkpoints and models/loras.", + "tags": ["image", "needs-models", "class-example"], + "requires": { + "nodes": ["CheckpointLoaderSimple", "LoraLoader", "CLIPTextEncode", "EmptyLatentImage", "KSampler", "VAEDecode", "SaveImage"], + "models": { + "checkpoints": ["v1-5-pruned-emaonly-fp16.safetensors"], + "loras": ["lcm-lora-sd15.safetensors"] + }, + "inputFiles": [] + }, + "bindings": { + "checkpoint": "v1-5-pruned-emaonly-fp16.safetensors", + "lora": "lcm-lora-sd15.safetensors", + "prompt": "a lighthouse at dusk, 35mm photograph, soft light", + "negative": "blurry, extra fingers, text", + "width": 512, + "height": 512, + "steps": 4, + "cfg": 1.5, + "seed": 42, + "sampler": "lcm", + "scheduler": "sgm_uniform" + }, + "nodes": [ + { + "key": "ckpt", + "class": "CheckpointLoaderSimple", + "title": "Load Checkpoint", + "pos": [40, 60], + "widgets": { "ckpt_name": "@checkpoint" } + }, + { + "key": "lora", + "class": "LoraLoader", + "title": "Load LoRA (LCM)", + "pos": [420, 60], + "widgets": { "lora_name": "@lora", "strength_model": 1.0, "strength_clip": 1.0 }, + "wires": { "model": "ckpt.MODEL", "clip": "ckpt.CLIP" } + }, + { + "key": "positive", + "class": "CLIPTextEncode", + "title": "Positive prompt", + "pos": [800, 40], + "widgets": { "text": "@prompt" }, + "wires": { "clip": "lora.CLIP" } + }, + { + "key": "negative", + "class": "CLIPTextEncode", + "title": "Negative prompt", + "pos": [800, 300], + "widgets": { "text": "@negative" }, + "wires": { "clip": "lora.CLIP" } + }, + { + "key": "latent", + "class": "EmptyLatentImage", + "title": "Empty Latent 512x512", + "pos": [800, 560], + "widgets": { "width": "@width", "height": "@height", "batch_size": 1 } + }, + { + "key": "sampler", + "class": "KSampler", + "title": "KSampler (4 steps)", + "pos": [1200, 200], + "widgets": { + "seed": "@seed", + "steps": "@steps", + "cfg": "@cfg", + "sampler_name": "@sampler", + "scheduler": "@scheduler", + "denoise": 1.0 + }, + "controlAfterGenerate": { "seed": "fixed" }, + "wires": { + "model": "lora.MODEL", + "positive": "positive.CONDITIONING", + "negative": "negative.CONDITIONING", + "latent_image": "latent.LATENT" + } + }, + { + "key": "decode", + "class": "VAEDecode", + "title": "VAE Decode", + "pos": [1600, 200], + "wires": { "samples": "sampler.LATENT", "vae": "ckpt.VAE" } + }, + { + "key": "save", + "class": "SaveImage", + "title": "Save Image", + "pos": [1960, 200], + "widgets": { "filename_prefix": "dsh-comfyui/text-to-image" }, + "wires": { "images": "decode.IMAGE" } + } + ] +} diff --git a/packages/dsh-comfyui/lib/cli.js b/packages/dsh-comfyui/lib/cli.js new file mode 100644 index 0000000..9491231 --- /dev/null +++ b/packages/dsh-comfyui/lib/cli.js @@ -0,0 +1,353 @@ +/** + * dsh-comfyui — comfy-cli: one bounded child process, and the argv this row uses. + * + * WHY THE CLI AT ALL, when there is an HTTP API: comfy-cli is a SECOND + * implementation of the same idea, and that is what makes it worth driving. It + * resolves the workspace, converts a UI workflow to the API form, uploads what a + * graph needs, submits, waits and downloads - all of which this package does + * itself. When the server's `/prompt` accepts a prompt this row compiled AND + * `comfy run --workflow` accepts the canvas the same row generated, the two + * readings agree, and neither one is the only witness. + * + * MEASURED AGAINST comfy-cli 1.29.0 (not guessed - every shape below was read off + * the real program): + * + * - `--json` is a GLOBAL option that goes BEFORE the subcommand + * (`comfy --json env`, never `comfy env --json`, which is a usage error); + * - with stdout piped the CLI picks JSON on its own, but passing `--json` + * explicitly is what makes that a contract rather than a coincidence; + * - every JSON answer is an ENVELOPE: + * `{schema, type, ok, command, version, where, data, error}` - so a + * subcommand's payload lives under `data`, and the CLI's own version is a + * TOP-LEVEL field rather than something to scrape with a regex; + * - `comfy env` and `comfy which` report the workspace and whether it EXISTS, + * the Desktop installs comfy-cli knows about (`code_dir`, `data_dir`, + * `python`, `model_roots`), the running server and the hardware. That is a + * discovery source this row would otherwise have to guess at. + * + * RULES, all of them the same rule: argv ARRAY, no shell, a deadline, a byte + * ceiling, `--json` wherever the CLI offers it, and `--workspace` naming a REAL + * ComfyUI tree when this row found one (comfy-cli's default is + * `/comfy/ComfyUI`, which on a Desktop machine usually does not exist). + * This module never runs `comfy install`, never installs a node, never downloads + * a model and never deletes anything. + */ + +import { spawn } from 'node:child_process' + +/** The environment variable that pins a comfy binary PATH does not carry. */ +export const CLI_ENV = 'DSH_COMFY_CLI' + +/** The command name comfy-cli installs. */ +export const CLI_NAME = 'comfy' + +/** How long a read-only CLI call may take. */ +export const READ_TIMEOUT_MS = 20000 + +/** How long `comfy run` may take: a CPU render of a 30-step graph is minutes. */ +export const RUN_TIMEOUT_MS = 900000 + +/** The most output this row keeps from one child process. */ +export const MAX_STDOUT_BYTES = 4 * 1024 * 1024 + +/** The global flag that turns every answer into one JSON envelope. */ +export const JSON_FLAG = '--json' + +/** + * Run one argv array and collect its output. + * + * @param argv - the program and its arguments, one element each. + * @param options - `{ timeoutMs, maxBytes, env, cwd }`. + * @returns `{ status, stdout, stderr, timedOut, error }`; `status` is null when + * the program could not start at all. + */ +export function runProcess(argv, options = {}) { + const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 5000 + const maxBytes = Number.isFinite(options.maxBytes) && options.maxBytes > 0 ? options.maxBytes : MAX_STDOUT_BYTES + return new Promise((resolve) => { + let settled = false + let timedOut = false + let stdout = '' + let stderr = '' + const finish = (result) => { + if (settled) return + settled = true + resolve(result) + } + let child + try { + child = spawn(argv[0], argv.slice(1), { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, env: options.env ?? process.env, cwd: options.cwd }) + } catch (error) { + finish({ status: null, stdout: '', stderr: '', timedOut: false, error: error && error.message ? String(error.message) : String(error) }) + return + } + const timer = setTimeout(() => { + timedOut = true + try { + child.kill('SIGKILL') + } catch (error) { + /* already gone */ + } + }, timeoutMs) + child.stdout?.setEncoding('utf8') + child.stderr?.setEncoding('utf8') + child.stdout?.on('data', (chunk) => { + if (stdout.length < maxBytes) stdout += chunk + }) + child.stderr?.on('data', (chunk) => { + if (stderr.length < maxBytes) stderr += chunk + }) + child.on('error', (error) => { + clearTimeout(timer) + finish({ status: null, stdout, stderr, timedOut, error: error && error.message ? String(error.message) : String(error) }) + }) + child.on('close', (code) => { + clearTimeout(timer) + finish({ status: code, stdout, stderr, timedOut }) + }) + }) +} + +/** The binary this row will try: the pinned one, else the name on PATH. */ +export function cliCommand(env = process.env) { + const pinned = String(env[CLI_ENV] ?? '').trim() + return pinned === '' ? CLI_NAME : pinned +} + +/** + * The argv for one `comfy` invocation. + * + * `--json` and `--workspace` are GLOBAL options, so they go before the + * subcommand - `comfy env --json` is a usage error on 1.29.0, and putting it + * after the verb is the mistake this helper exists to prevent. + * + * @param command - the binary. + * @param args - the subcommand and its own arguments. + * @param options - `{ workspace }`. + */ +export function argvFor(command, args, options = {}) { + const argv = [command] + if (typeof options.workspace === 'string' && options.workspace !== '') argv.push('--workspace=' + options.workspace) + argv.push(JSON_FLAG, ...args) + return argv +} + +/** + * `comfy --version`, and whether the CLI is usable at all. + * + * The envelope carries the version as a top-level string, which is read first; + * the regex is only the fallback for an older CLI that printed prose. + * + * @returns `{ found, command, version, envelope, error }`. + */ +export async function cliVersion(runner, env = process.env, options = {}) { + const command = cliCommand(env) + const result = await runner([command, '--version'], { timeoutMs: options.timeoutMs ?? 8000, env }) + if (result === null || result === undefined) return { found: false, command, version: '', envelope: null, error: 'the runner returned nothing' } + if (result.status === null) return { found: false, command, version: '', envelope: null, error: result.error ?? 'the command could not start' } + const text = String(result.stdout ?? '') + '\n' + String(result.stderr ?? '') + const parsed = parseEnvelope(String(result.stdout ?? '')) + const envelope = parsed.data !== null && typeof parsed.data === 'object' && parsed.data.type === 'envelope' ? parsed.data : null + const fromEnvelope = envelope !== null && typeof envelope.version === 'string' ? envelope.version : '' + const match = /(\d+\.\d+\.\d+[0-9A-Za-z.+-]*)/.exec(text) + const version = fromEnvelope !== '' ? fromEnvelope : match === null ? '' : match[1] + if (version === '') return { found: false, command, version: '', envelope, error: (String(result.stderr ?? '').trim() || 'exit code ' + result.status).split('\n')[0] } + return { found: true, command, version, envelope, error: '' } +} + +/** Parse the JSON envelope one `--json` command emits, keeping the raw text. */ +export function parseEnvelope(text) { + const trimmed = String(text ?? '').trim() + if (trimmed === '') return { data: null, text: trimmed } + try { + return { data: JSON.parse(trimmed), text: trimmed } + } catch (error) { + // Some commands print a log line before the envelope. Take the last object + // that parses, which is the envelope by construction. + const lines = trimmed.split('\n') + for (let index = lines.length - 1; index >= 0; index -= 1) { + const candidate = lines.slice(index).join('\n').trim() + if (!candidate.startsWith('{')) continue + try { + return { data: JSON.parse(candidate), text: trimmed } + } catch (err) { + continue + } + } + return { data: null, text: trimmed } + } +} + +/** + * One `--json` call, as `{ ok, data, envelope, error, stdout, stderr, status }`. + * + * A refusal is NOT an exception: comfy-cli answers a failure with `ok: false` + * and an `error.message` that is the sentence a person needs (`'' is not a + * valid ComfyUI workspace`, `ComfyUI-Manager not found`), so it is returned and + * reported rather than thrown. + */ +export async function cliJson(runner, args, options = {}) { + const command = options.command ?? cliCommand(options.env ?? process.env) + const argv = argvFor(command, args, { workspace: options.workspace }) + const result = await runner(argv, { timeoutMs: options.timeoutMs ?? READ_TIMEOUT_MS, env: options.env ?? process.env }) + if (result === null || result === undefined) return { ok: false, argv, envelope: null, data: null, error: 'the runner returned nothing', stdout: '', stderr: '', status: null } + if (result.status === null) return { ok: false, argv, envelope: null, data: null, error: result.error ?? 'the command could not start', stdout: '', stderr: '', status: null } + const parsed = parseEnvelope(String(result.stdout ?? '')) + const envelope = parsed.data !== null && typeof parsed.data === 'object' && parsed.data.type === 'envelope' ? parsed.data : null + const message = envelope !== null && envelope.error !== null && typeof envelope.error === 'object' && typeof envelope.error.message === 'string' ? envelope.error.message : '' + const stderrText = String(result.stderr ?? '').trim() + return { + ok: result.status === 0 && (envelope === null || envelope.ok !== false), + argv, + envelope, + data: envelope !== null && envelope.data !== null && typeof envelope.data === 'object' ? envelope.data : null, + error: message !== '' ? message : stderrText.split('\n')[0] ?? '', + stderr: stderrText, + stdout: String(result.stdout ?? '').trim(), + status: result.status, + } +} + +/** + * `comfy env` as the SIX things a reader needs. + * + * Read straight from the measured envelope (1.29.0): + * `data.workspace.{path,exists,type,manager_mode,desktop.{installs[],model_roots}}`, + * `data.server.{running,url}`, `data.python.{version,executable}`, + * `data.hardware.{os,ram_bytes,gpu.{model,vram_bytes}}`, `data.warnings[]`. + * Nothing is guessed by key-name heuristics any more: a walker that looked for + * "something with a slash in it" would happily report the config path as the + * workspace. + */ +export function envFacts(data) { + const facts = { workspace: '', workspaceExists: null, workspaceType: '', python: '', pythonVersion: '', comfyuiVersion: '', serverRunning: null, serverUrl: '', managerMode: '', gpu: '', vramBytes: null, ramBytes: null, os: '', warnings: [], installs: [], modelRoots: [] } + if (data === null || typeof data !== 'object') return facts + const workspace = data.workspace !== null && typeof data.workspace === 'object' ? data.workspace : {} + if (typeof workspace.path === 'string') facts.workspace = workspace.path + if (typeof workspace.exists === 'boolean') facts.workspaceExists = workspace.exists + if (typeof workspace.type === 'string') facts.workspaceType = workspace.type + if (typeof workspace.manager_mode === 'string') facts.managerMode = workspace.manager_mode + const desktop = workspace.desktop !== null && typeof workspace.desktop === 'object' ? workspace.desktop : {} + if (typeof desktop.comfyui_version === 'string') facts.comfyuiVersion = desktop.comfyui_version + if (Array.isArray(desktop.installs)) { + facts.installs = desktop.installs + .filter((entry) => entry !== null && typeof entry === 'object') + .map((entry) => ({ + name: typeof entry.name === 'string' ? entry.name : '', + codeDir: typeof entry.code_dir === 'string' ? entry.code_dir : '', + dataDir: typeof entry.data_dir === 'string' ? entry.data_dir : '', + version: typeof entry.comfyui_version === 'string' ? entry.comfyui_version : '', + exists: entry.exists === true, + selected: entry.selected === true, + })) + } + if (Array.isArray(desktop.model_roots)) facts.modelRoots = desktop.model_roots.filter((entry) => typeof entry === 'string') + const server = data.server !== null && typeof data.server === 'object' ? data.server : {} + if (typeof server.running === 'boolean') facts.serverRunning = server.running + if (typeof server.url === 'string') facts.serverUrl = server.url + const python = data.python !== null && typeof data.python === 'object' ? data.python : {} + if (typeof python.executable === 'string') facts.python = python.executable + if (typeof python.version === 'string') facts.pythonVersion = python.version + const hardware = data.hardware !== null && typeof data.hardware === 'object' ? data.hardware : {} + if (typeof hardware.os === 'string') facts.os = hardware.os + if (typeof hardware.ram_bytes === 'number') facts.ramBytes = hardware.ram_bytes + const gpu = hardware.gpu !== null && typeof hardware.gpu === 'object' ? hardware.gpu : {} + if (typeof gpu.model === 'string') facts.gpu = gpu.model + if (typeof gpu.vram_bytes === 'number') facts.vramBytes = gpu.vram_bytes + if (Array.isArray(data.warnings)) { + facts.warnings = data.warnings + .filter((entry) => entry !== null && typeof entry === 'object' && typeof entry.message === 'string') + .map((entry) => ({ code: typeof entry.code === 'string' ? entry.code : '', message: entry.message })) + } + return facts +} + +/** `comfy which` as the one fact it carries: the workspace path, and whether it exists. */ +export function whichFacts(data) { + if (data === null || typeof data !== 'object') return { workspace: '', exists: null } + return { + workspace: typeof data.workspace_path === 'string' ? data.workspace_path : '', + exists: typeof data.exists === 'boolean' ? data.exists : null, + } +} + +/** `comfy node deps-in-workflow` - the custom nodes one workflow needs. */ +export function depsArgv(command, workflowFile, outputFile, options = {}) { + return argvFor(command, ['node', 'deps-in-workflow', '--workflow=' + workflowFile, '--output=' + outputFile], options) +} + +/** `comfy run --workflow --wait` - the CLI's own test path. */ +export function runArgv(command, workflowFile, options = {}) { + return argvFor(command, ['run', '--workflow', workflowFile, '--wait'], options) +} + +/** `comfy launch --background`. */ +export function launchArgv(command, options = {}) { + return argvFor(command, ['launch', '--background'], options) +} + +/** `comfy stop`. */ +export function stopArgv(command, options = {}) { + return argvFor(command, ['stop'], options) +} + +/** `comfy which`. */ +export function whichArgv(command, options = {}) { + return argvFor(command, ['which'], options) +} + +/** `comfy env`. */ +export function envArgv(command, options = {}) { + return argvFor(command, ['env'], options) +} + +/** + * The two refusals comfy-cli gives before it can look at a graph, as sentences a + * reader can act on rather than raw stderr. + * + * Both were MEASURED on 1.29.0: the first when the default workspace + * (`/comfy/ComfyUI`) does not exist, the second when it does but has no + * ComfyUI-Manager - which is the state of a Desktop install, because Desktop + * ships its own Manager inside the app rather than in the tree. + */ +export function explainCliFailure(text) { + const value = String(text ?? '') + if (/server_not_running|ComfyUI not running on specified address/i.test(value)) { + return 'the CLI reached a real workspace but no server was listening. Start one: open the ComfyUI app, `comfy launch --background` (this row drives it as `comfy_cli` action=launch), or point the CLI at a server you started yourself with COMFY_LOCAL_URL=http://127.0.0.1:8188. `comfy_run` does the same job over HTTP and needs no CLI.' + } + if (/is not a valid ComfyUI workspace/i.test(value)) { + return 'comfy-cli could not resolve a ComfyUI workspace. Its default is /comfy/ComfyUI, which does not exist on a Desktop machine. Point it at a real tree with `--workspace` (this row passes the install `comfy_status` found), or create one with `comfy install`.' + } + if (/ComfyUI-Manager not found/i.test(value)) { + return 'the workspace has no ComfyUI-Manager, and `comfy node deps-in-workflow` resolves node packs through the Manager\'s `cm-cli`. A tree made by `comfy install` has one; a Desktop install keeps its Manager inside the app, so `deps` does not work against it. `comfy run --workflow` does not need it.' + } + if (/No such option: --json/i.test(value)) { + return 'this comfy-cli is older than the global `--json` flag; an answer without an envelope is still read, but the version should be checked.' + } + return '' +} + +/** A prompt_id out of `comfy run`'s output, whichever way it prints it. */ +export function promptIdFromRunText(text) { + const value = String(text ?? '') + const json = parseEnvelope(value) + if (json.data !== null && typeof json.data === 'object') { + const found = findPromptId(json.data) + if (found !== '') return found + } + const match = /(?:prompt[ _]?id["'\s:=]+)([0-9a-fA-F-]{16,})/i.exec(value) + return match ? match[1] : '' +} + +/** The first `prompt_id`-looking value inside an object tree. */ +function findPromptId(value, depth = 0) { + if (value === null || typeof value !== 'object' || depth > 4) return '' + for (const [key, entry] of Object.entries(value)) { + if (typeof entry === 'string' && /prompt_?id/i.test(key) && entry.length >= 8) return entry + if (entry !== null && typeof entry === 'object') { + const nested = findPromptId(entry, depth + 1) + if (nested !== '') return nested + } + } + return '' +} diff --git a/packages/dsh-comfyui/lib/client.js b/packages/dsh-comfyui/lib/client.js new file mode 100644 index 0000000..a660897 --- /dev/null +++ b/packages/dsh-comfyui/lib/client.js @@ -0,0 +1,665 @@ +/** + * dsh-comfyui — where ComfyUI is, and the HTTP calls this row makes. + * + * FOUR FACTS THAT FAIL INDEPENDENTLY, and the tools never merge them: + * + * 1. an INSTALL on disk - a Desktop base path, a portable folder, a git + * checkout. It answers "which models exist", "where is custom_nodes" and + * "which ComfyUI version is this" WITHOUT a server; + * 2. a SERVER answering on loopback - `/system_stats` is the only thing that + * proves it, and ComfyUI Desktop does not use 8188: it picks 8000 upwards, + * so a probe that only tried 8188 would report "not running" on a machine + * where the app is open; + * 3. a NODE CATALOG - `/object_info`, which is what makes a project + * compilable rather than merely well-shaped; + * 4. a PYTHON that can import the install's packages - needed to run a node + * CLASS, and never needed to compile a graph. + * + * The loopback fence is the same rule as `dsh-ollama`'s: these tools talk to the + * machine's own ComfyUI, and a URL naming another machine is REFUSED unless + * `DSH_COMFYUI_ALLOW_REMOTE=1` says the person means it. Prompts are not + * private, but the files they write and read are on somebody's disk. + */ + +import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs' +import { homedir, tmpdir } from 'node:os' +import path from 'node:path' + +import { ComfyError } from './errors.js' + +/** What ComfyUI's own server binds to by default. */ +export const DEFAULT_PORT = 8188 + +/** The ports ComfyUI Desktop picks from, lowest first. */ +export const DESKTOP_PORTS = [8000, 8001, 8002, 8003] + +/** The one environment variable that allows a server on another machine. */ +export const ALLOW_REMOTE_ENV = 'DSH_COMFYUI_ALLOW_REMOTE' + +/** The one environment variable that pins the server this row talks to. */ +export const URL_ENV = 'DSH_COMFYUI_URL' + +/** The one environment variable that pins the install directory. */ +export const DIR_ENV = 'DSH_COMFYUI_DIR' + +/** A response body is capped here; a full `/object_info` is the largest real one. */ +export const MAX_BODY_BYTES = 24 * 1024 * 1024 + +/** A probe gives up here: a server that is there answers in milliseconds. */ +export const PROBE_TIMEOUT_MS = 2500 + +/** Reading the node catalog is the one slow call on a big install. */ +export const SCHEMA_TIMEOUT_MS = 30000 + +/** + * The conversation home, resolved exactly like the pack's other rows. + * + * `os.homedir()` is the last REAL home, and `os.tmpdir()` is the last resort + * rather than `process.cwd()`. A cache written into whatever directory the + * process happened to start in drops a `.dsh/` folder into somebody's project - + * measured here: a harness with a stripped environment wrote + * `packages/dsh-comfyui/.dsh/dsh-comfyui/schema/*.json` during a check run. + * A catalog cache is never worth a file in the working tree. + */ +export function resolveHome(env = process.env) { + const fromEnv = env.DSH_HOME + if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return path.resolve(fromEnv.trim()) + const home = env.USERPROFILE ?? env.HOME ?? homedir() + if (typeof home === 'string' && home.trim() !== '') return path.join(home.trim(), '.dsh') + return path.join(tmpdir(), 'dsh-home') +} + +/** Where this row keeps what it must remember: the node catalogs it has read. */ +export function cacheRoot(env = process.env) { + return path.join(resolveHome(env), 'dsh-comfyui', 'schema') +} + +/** One origin as a file name. */ +export function cacheFileFor(env, origin) { + const safe = String(origin).replace(/^https?:\/\//, '').replace(/[^A-Za-z0-9._-]+/g, '_') + return path.join(cacheRoot(env), safe + '.json') +} + +/** The truthy spellings a person actually types for an opt-in. */ +function isTruthy(value) { + return /^(1|true|yes|on)$/i.test(String(value ?? '').trim()) +} + +/** Whether a hostname names this machine (the same rule `dsh-ollama` uses). */ +export function isLoopbackHost(hostname) { + const name = String(hostname).toLowerCase() + if (name === 'localhost' || name === 'localhost.' || name === '0.0.0.0' || name === '::1' || name === '::') return true + if (name.endsWith('.localhost')) return true + if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(name)) return true + return false +} + +/** + * Which origins this row will try, in order, and whether the person pinned one. + * + * It makes NO request: this is the fence, so a caller can ask "would this be + * allowed" before a socket exists. + * + * @param env - the environment (injectable for the check). + * @returns `{ explicit, origins, allowed, code, reason }`. + */ +export function resolveServers(env = process.env) { + const raw = String(env[URL_ENV] ?? '').trim() + const optIn = isTruthy(env[ALLOW_REMOTE_ENV]) + if (raw === '') { + return { + explicit: false, + origins: ['http://127.0.0.1:' + DEFAULT_PORT, ...DESKTOP_PORTS.map((port) => 'http://127.0.0.1:' + port)], + allowed: true, + code: '', + reason: '', + remote: false, + optIn, + } + } + const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : 'http://' + raw + let url + try { + url = new URL(withScheme) + } catch (error) { + return { explicit: true, origins: [], allowed: false, code: 'HOST_INVALID', reason: URL_ENV + ' is "' + raw + '", which is not an address. Use http://host:port.', remote: false, optIn } + } + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + return { explicit: true, origins: [], allowed: false, code: 'HOST_INVALID', reason: URL_ENV + ' is "' + raw + '"; this row speaks http(s), so a "' + url.protocol + '" address is refused.', remote: false, optIn } + } + const host = url.hostname.replace(/^\[/, '').replace(/\]$/, '') + const local = isLoopbackHost(host) + const allowed = local || optIn + const origin = url.origin + (url.pathname === '/' || url.pathname === '' ? '' : url.pathname.replace(/\/+$/, '')) + return { + explicit: true, + origins: allowed ? [origin] : [], + allowed, + code: allowed ? '' : 'REMOTE_REFUSED', + reason: allowed + ? '' + : URL_ENV + + ' is ' + + host + + ', which is not this machine. These tools talk to the local ComfyUI only: set ' + + ALLOW_REMOTE_ENV + + '=1 for a server you run elsewhere, or unset ' + + URL_ENV + + ' to try 127.0.0.1:' + + DEFAULT_PORT + + ' and the Desktop ports.', + remote: !local, + optIn, + } +} + +/** The base path ComfyUI Desktop recorded, per platform. */ +export function desktopConfigFile(env, platform) { + const home = env.USERPROFILE ?? env.HOME ?? '' + if (platform === 'win32') return env.APPDATA ? path.join(env.APPDATA, 'ComfyUI', 'config.json') : path.join(home, 'AppData', 'Roaming', 'ComfyUI', 'config.json') + if (platform === 'darwin') return path.join(home, 'Library', 'Application Support', 'ComfyUI', 'config.json') + return env.XDG_CONFIG_HOME ? path.join(env.XDG_CONFIG_HOME, 'ComfyUI', 'config.json') : path.join(home, '.config', 'ComfyUI', 'config.json') +} + +/** The Desktop app's own folder, whose `resources/ComfyUI` is the source tree. */ +export function desktopAppDirs(env, platform) { + const home = env.USERPROFILE ?? env.HOME ?? '' + if (platform === 'win32') { + const local = env.LOCALAPPDATA ?? path.join(home, 'AppData', 'Local') + return [path.join(local, 'Programs', 'ComfyUI'), path.join(local, 'ComfyUI'), path.join(home, 'AppData', 'Local', 'Programs', 'ComfyUI')] + } + if (platform === 'darwin') return ['/Applications/ComfyUI.app/Contents', path.join(home, 'Applications', 'ComfyUI.app', 'Contents')] + return ['/opt/ComfyUI', '/usr/local/ComfyUI', path.join(home, 'Applications', 'ComfyUI')] +} + +/** Whether a folder looks like a ComfyUI base path (user data) rather than a source tree. */ +function looksLikeBase(dir) { + return existsSync(path.join(dir, 'models')) || existsSync(path.join(dir, 'custom_nodes')) || existsSync(path.join(dir, 'user')) +} + +/** Whether a folder looks like the ComfyUI source tree. */ +function looksLikeApp(dir) { + return existsSync(path.join(dir, 'main.py')) || existsSync(path.join(dir, 'comfyui_version.py')) +} + +/** The version in a `comfyui_version.py`, or ''. */ +export function versionFromFile(file) { + try { + const text = readFileSync(file, 'utf8') + const match = /__version__\s*=\s*['"]([^'"]+)['"]/.exec(text) + return match ? match[1] : '' + } catch (error) { + return '' + } +} + +/** The interpreter a base path's environment carries, or ''. */ +export function pythonIn(base, platform) { + const candidates = + platform === 'win32' + ? [path.join(base, '.venv', 'Scripts', 'python.exe'), path.join(base, 'python_embeded', 'python.exe'), path.join(base, 'venv', 'Scripts', 'python.exe')] + : [path.join(base, '.venv', 'bin', 'python'), path.join(base, 'venv', 'bin', 'python'), path.join(base, 'python_embeded', 'bin', 'python')] + return candidates.find((candidate) => existsSync(candidate)) ?? '' +} + +/** The names of one model folder, without reading gigabytes of anything. */ +export function modelFiles(base, folder) { + const dir = path.join(base, 'models', folder) + if (!existsSync(dir)) return [] + const found = [] + const walk = (current, prefix, depth) => { + let entries + try { + entries = readdirSync(current, { withFileTypes: true }) + } catch (error) { + return + } + for (const entry of entries) { + if (entry.name.startsWith('.')) continue + const relative = prefix === '' ? entry.name : prefix + '/' + entry.name + if (entry.isDirectory()) { + if (depth < 2 && folder !== 'diffusion_models') walk(path.join(current, entry.name), relative, depth + 1) + else if (depth < 3 && folder === 'diffusion_models') walk(path.join(current, entry.name), relative, depth + 1) + continue + } + if (/\.(safetensors|ckpt|pt|pth|bin|gguf|sft)$/i.test(entry.name)) found.push(relative) + } + } + walk(dir, '', 0) + return found.sort() +} + +/** Whether a path is a directory, without throwing. */ +function isDir(candidate) { + try { + return statSync(candidate).isDirectory() + } catch (error) { + return false + } +} + +/** + * Everything this machine can be asked about ComfyUI WITHOUT a server. + * + * The search is bounded and ordered: an explicit variable, ComfyUI Desktop's + * own record of where it installed, what comfy-cli reports about the workspaces + * it knows (its `env --json` names each Desktop install's `code_dir` and + * `data_dir`), the portable folder a person unpacks, then the places a checkout + * usually sits. It never scans a drive. + * + * @param options - `{ env, platform, cli }`; `cli` is a `cli.envFacts()` result. + * @returns `{ found, bases, app, version, python, models, modelRoots, customNodes, sources, notes }`. + */ +export function discoverInstall(options = {}) { + const env = options.env ?? process.env + const platform = options.platform ?? process.platform + const cli = options.cli ?? null + const home = env.USERPROFILE ?? env.HOME ?? homedir() + const notes = [] + const bases = [] + const seen = new Set() + const addBase = (dir, source) => { + if (typeof dir !== 'string' || dir.trim() === '') return + const resolved = path.resolve(dir.trim()) + const key = resolved.toLowerCase() + if (seen.has(key)) return + seen.add(key) + if (!isDir(resolved)) return + bases.push({ dir: resolved, source }) + } + const appCandidatesExtra = [] + + addBase(String(env[DIR_ENV] ?? ''), DIR_ENV) + if (cli !== null && typeof cli === 'object') { + // comfy-cli's own view: a Desktop install names where the code is and where + // the models are, which is exactly the pair this function needs. + for (const install of Array.isArray(cli.installs) ? cli.installs : []) { + if (install === null || typeof install !== 'object') continue + if (install.exists === false) continue + addBase(install.dataDir, 'comfy-cli Desktop install' + (install.name === '' ? '' : ' "' + install.name + '"')) + if (typeof install.codeDir === 'string' && install.codeDir !== '') appCandidatesExtra.push(install.codeDir) + } + if (cli.workspace !== '' && cli.workspaceExists === true) addBase(cli.workspace, 'comfy-cli workspace') + } + const configFile = desktopConfigFile(env, platform) + let desktopBase = '' + if (existsSync(configFile)) { + try { + const config = JSON.parse(readFileSync(configFile, 'utf8')) + if (typeof config.basePath === 'string' && config.basePath !== '') { + desktopBase = config.basePath + if (isDir(config.basePath)) addBase(config.basePath, 'ComfyUI Desktop config') + else notes.push('ComfyUI Desktop records the base path ' + config.basePath + ', and that folder is NOT there - the app cannot start until it is. Reinstall the desktop build (or point it at a base path) and this row will find the models again.') + } + if (typeof config.installState === 'string' && config.installState !== 'installed') { + notes.push('ComfyUI Desktop records installState "' + config.installState + '" - the app may not be fully installed.') + } + } catch (error) { + notes.push('ComfyUI Desktop config at ' + configFile + ' is not readable JSON, so its base path was not used.') + } + } else { + notes.push('no ComfyUI Desktop config at ' + configFile) + } + for (const candidate of [path.join(home, 'ComfyUI'), path.join(home, 'comfyui'), path.join(home, 'ComfyUI_windows_portable', 'ComfyUI'), path.join(home, 'Desktop', 'ComfyUI'), path.join(home, 'Documents', 'ComfyUI'), '/opt/ComfyUI', 'C:\\ComfyUI']) { + addBase(candidate, 'a standard location') + } + + let app = '' + const appCandidates = [] + for (const dir of desktopAppDirs(env, platform)) appCandidates.push(path.join(dir, 'resources', 'ComfyUI'), dir) + for (const candidate of appCandidatesExtra) appCandidates.push(candidate) + for (const base of bases) appCandidates.push(base.dir) + for (const candidate of appCandidates) { + if (!isDir(candidate)) continue + if (looksLikeApp(candidate)) { + app = candidate + break + } + } + + const base = bases.find((entry) => looksLikeBase(entry.dir)) ?? null + const version = app === '' ? '' : versionFromFile(path.join(app, 'comfyui_version.py')) + const python = base === null ? '' : pythonIn(base.dir, platform) + const customNodes = [] + for (const dir of [base === null ? null : path.join(base.dir, 'custom_nodes'), app === '' ? null : path.join(app, 'custom_nodes')]) { + if (dir === null || !isDir(dir)) continue + try { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== '__pycache__') customNodes.push(entry.name) + } + } catch (error) { + notes.push('could not list ' + dir + ': ' + error.message) + } + } + const models = {} + if (base !== null) { + const modelsDir = path.join(base.dir, 'models') + if (isDir(modelsDir)) { + try { + for (const entry of readdirSync(modelsDir, { withFileTypes: true })) if (entry.isDirectory()) models[entry.name] = modelFiles(base.dir, entry.name).length + } catch (error) { + notes.push('could not list ' + modelsDir + ': ' + error.message) + } + } + } + // Model roots comfy-cli knows about (a Desktop install can keep models in a + // shared folder beside the app): reported, and used as extra places to look. + const modelRoots = [] + for (const root of [...(cli !== null && Array.isArray(cli.modelRoots) ? cli.modelRoots : []), ...(base === null ? [] : [path.join(base.dir, 'models')])]) { + if (typeof root === 'string' && root !== '' && isDir(root) && !modelRoots.includes(root)) modelRoots.push(root) + } + if (app !== '' && base === null) notes.push('the source tree at ' + app + ' was found, but no base path with models/ and custom_nodes/ was; a model filename cannot be checked against the disk here - start ComfyUI and its own /object_info lists become the truth.') + + return { + found: base !== null || app !== '', + base: base === null ? '' : base.dir, + baseSource: base === null ? '' : base.source, + app, + version, + python, + models, + modelRoots, + customNodes, + desktopBase, + configFile, + notes, + } +} + +/** The abort signal for one request: our deadline, plus the caller's when given. */ +function signalFor(timeoutMs, callerSignal) { + const deadline = AbortSignal.timeout(Math.max(1, Math.round(timeoutMs))) + if (callerSignal === undefined || callerSignal === null) return deadline + if (typeof AbortSignal.any === 'function') return AbortSignal.any([deadline, callerSignal]) + return deadline +} + +/** The deepest `code` a fetch failure carries (ECONNREFUSED lives in `cause`). */ +function causeCode(error) { + let current = error + for (let depth = 0; depth < 4 && current; depth += 1) { + if (typeof current.code === 'string' && current.code !== '') return current.code + current = current.cause + } + return '' +} + +/** Read a response body against a byte ceiling. */ +async function readBounded(response, maxBytes = MAX_BODY_BYTES) { + const declared = Number(response.headers.get('content-length')) + if (Number.isFinite(declared) && declared > maxBytes) { + throw new ComfyError('BODY_TOO_LARGE', 'The server answered with ' + declared + ' bytes, over the ' + maxBytes + '-byte ceiling this row reads.') + } + if (response.body === null || typeof response.body?.getReader !== 'function') { + const text = await response.text() + return text.length > maxBytes ? text.slice(0, maxBytes) : text + } + const reader = response.body.getReader() + const decoder = new TextDecoder() + let text = '' + let bytes = 0 + try { + for (;;) { + const { value, done } = await reader.read() + if (done) break + bytes += value.byteLength + if (bytes > maxBytes) throw new ComfyError('BODY_TOO_LARGE', 'The server answered with more than the ' + maxBytes + '-byte ceiling this row reads.') + text += decoder.decode(value, { stream: true }) + } + text += decoder.decode() + } finally { + reader.cancel().catch(() => {}) + } + return text +} + +/** + * One JSON request to a ComfyUI server. + * + * A refusal keeps the server's own words in `extra.body`: `/prompt` answers a + * rejected graph with `node_errors`, which is the most useful text in the whole + * API, and replacing it with "HTTP 400" would throw it away. + * + * @param deps - `{ fetch }`. + * @param origin - e.g. `http://127.0.0.1:8188`. + * @param route - e.g. `/prompt`. + * @param options - `{ method, body, timeoutMs, signal }`. + * @returns `{ status, data, text }`. + */ +export async function requestJson(deps, origin, route, options = {}) { + const fetchImpl = deps.fetch ?? globalThis.fetch + const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 30000 + const init = { method: options.method ?? 'GET', headers: { accept: 'application/json', 'user-agent': 'dsh-comfyui' }, signal: signalFor(timeoutMs, options.signal) } + if (options.body !== undefined) { + init.body = JSON.stringify(options.body) + init.headers['content-type'] = 'application/json' + } + let response + try { + response = await fetchImpl(origin + route, init) + } catch (error) { + const name = error && error.name ? String(error.name) : '' + if (name === 'TimeoutError' || name === 'AbortError') { + throw new ComfyError('TIMEOUT', 'No answer from ' + origin + route + ' within ' + Math.round(timeoutMs / 1000) + ' s. A big install takes a while to answer /object_info the first time; a run takes as long as its model.', { origin, route }) + } + const detail = causeCode(error) || (error && error.message ? String(error.message) : 'fetch failed') + throw new ComfyError('SERVER_DOWN', 'Nothing is answering at ' + origin + ' (' + detail + '). ComfyUI is not running there: start the app (or `python main.py`), then call `comfy_status` - it names the ports this row tries.', { origin }) + } + const text = await readBounded(response) + let data = {} + if (text.trim() !== '') { + try { + data = JSON.parse(text) + } catch (error) { + if (response.ok) throw new ComfyError('BAD_JSON', 'The server answered ' + route + ' with something that is not JSON: ' + text.trim().slice(0, 200), { origin, route }) + data = { error: text.trim().slice(0, 600) } + } + } + if (!response.ok) { + throw new ComfyError('HTTP_ERROR', 'The server answered HTTP ' + response.status + ' for ' + route + '.', { origin, route, status: response.status, body: data }) + } + return { status: response.status, data, text } +} + +/** + * One server's identity, or null when nothing answers there. + * + * `/system_stats` is the proof: it is answered by the ComfyUI server itself + * (not by its frontend, not by a proxy that happens to hold the port) and it + * carries the version, the device and the VRAM this row reports. + * + * @returns `{ origin, version, device, vramTotal, ramTotal, pythonVersion, pytorchVersion, os, argv }` or null. + */ +export async function probeServer(deps, origin, options = {}) { + try { + const { data } = await requestJson(deps, origin, '/system_stats', { timeoutMs: options.timeoutMs ?? PROBE_TIMEOUT_MS, signal: options.signal }) + const system = data !== null && typeof data.system === 'object' && data.system !== null ? data.system : {} + const devices = Array.isArray(data.devices) ? data.devices : [] + const device = devices[0] !== null && typeof devices[0] === 'object' ? devices[0] : {} + return { + origin, + version: typeof system.comfyui_version === 'string' ? system.comfyui_version : '', + device: typeof device.name === 'string' ? device.name : '', + deviceType: typeof device.type === 'string' ? device.type : '', + vramTotal: typeof device.vram_total === 'number' ? device.vram_total : null, + vramFree: typeof device.vram_free === 'number' ? device.vram_free : null, + ramTotal: typeof system.ram_total === 'number' ? system.ram_total : null, + pythonVersion: typeof system.python_version === 'string' ? system.python_version.split(' ')[0] : '', + pytorchVersion: typeof system.pytorch_version === 'string' ? system.pytorch_version : '', + os: typeof system.os === 'string' ? system.os : '', + devices: devices.length, + } + } catch (error) { + return null + } +} + +/** + * The first origin that answers, with what every probe said. + * + * Sequential, not parallel, and for a reason: the Desktop ports are tried in + * order and the first hit is the app, while a parallel fan-out would race the + * same server twice and make the reported port depend on network jitter. + * + * @returns `{ server, probed }` - `server` is null when nothing answered. + */ +export async function findServer(deps, options = {}) { + const resolved = options.servers ?? resolveServers(deps.env ?? process.env) + if (!resolved.allowed) return { server: null, probed: [], servers: resolved } + const probed = [] + for (const origin of resolved.origins) { + const server = await probeServer(deps, origin, { timeoutMs: options.timeoutMs ?? PROBE_TIMEOUT_MS, signal: options.signal }) + probed.push({ origin, up: server !== null }) + if (server !== null) return { server, probed, servers: resolved } + } + return { server: null, probed, servers: resolved } +} + +/** `/object_info`, parsed. The caller decides where to cache it. */ +export async function fetchObjectInfo(deps, origin, options = {}) { + const { data } = await requestJson(deps, origin, '/object_info', { timeoutMs: options.timeoutMs ?? SCHEMA_TIMEOUT_MS, signal: options.signal }) + if (data === null || typeof data !== 'object' || Array.isArray(data)) { + throw new ComfyError('BAD_OBJECT_INFO', 'The server answered /object_info with something that is not an object of node classes.', { origin }) + } + return data +} + +/** Write one catalog to the cache, and return the file it wrote. */ +export function writeCache(env, origin, record) { + const file = cacheFileFor(env, origin) + mkdirSync(path.dirname(file), { recursive: true }) + writeFileSync(file, JSON.stringify(record, null, 2), 'utf8') + return file +} + +/** The cached catalog for one origin, or null. */ +export function readCache(env, origin) { + const file = cacheFileFor(env, origin) + if (!existsSync(file)) return null + try { + const record = JSON.parse(readFileSync(file, 'utf8')) + if (record === null || typeof record !== 'object' || record.objectInfo === null || typeof record.objectInfo !== 'object') return null + return record + } catch (error) { + return null + } +} + +/** Every catalog this machine has read, newest first. */ +export function listCache(env) { + const root = cacheRoot(env) + if (!existsSync(root)) return [] + const found = [] + try { + for (const entry of readdirSync(root, { withFileTypes: true })) { + if (!entry.isFile() || !entry.name.endsWith('.json')) continue + const file = path.join(root, entry.name) + try { + const record = JSON.parse(readFileSync(file, 'utf8')) + found.push({ + file, + origin: typeof record.origin === 'string' ? record.origin : '', + version: typeof record.version === 'string' ? record.version : '', + fetchedAt: typeof record.fetchedAt === 'string' ? record.fetchedAt : '', + classes: record.objectInfo !== null && typeof record.objectInfo === 'object' ? Object.keys(record.objectInfo).length : 0, + }) + } catch (error) { + found.push({ file, origin: '', version: '', fetchedAt: '', classes: 0 }) + } + } + } catch (error) { + return [] + } + return found.sort((left, right) => String(right.fetchedAt).localeCompare(String(left.fetchedAt))) +} + +/** Queue one prompt. A rejected graph comes back as a ComfyError with the body. */ +export async function queuePrompt(deps, origin, prompt, options = {}) { + const body = { prompt, client_id: options.clientId ?? 'dsh-comfyui' } + if (options.number !== undefined) body.number = options.number + const { data } = await requestJson(deps, origin, '/prompt', { method: 'POST', body, timeoutMs: options.timeoutMs ?? 30000, signal: options.signal }) + if (typeof data.prompt_id !== 'string' || data.prompt_id === '') { + throw new ComfyError('PROMPT_REFUSED', 'The server accepted the request but did not return a prompt_id, so there is nothing to wait for.', { origin, body: data }) + } + return data +} + +/** One prompt's history entry, or null while it is still queued or running. */ +export async function historyOf(deps, origin, promptId, options = {}) { + const { data } = await requestJson(deps, origin, '/history/' + encodeURIComponent(promptId), { timeoutMs: options.timeoutMs ?? 15000, signal: options.signal }) + if (data === null || typeof data !== 'object') return null + const entry = data[promptId] + return entry !== undefined && entry !== null && typeof entry === 'object' ? entry : null +} + +/** The queue, for telling "still waiting" from "dropped". */ +export async function queueOf(deps, origin, options = {}) { + const { data } = await requestJson(deps, origin, '/queue', { timeoutMs: options.timeoutMs ?? 15000, signal: options.signal }) + const running = Array.isArray(data.queue_running) ? data.queue_running : [] + const pending = Array.isArray(data.queue_pending) ? data.queue_pending : [] + return { running, pending } +} + +/** + * Wait for one prompt to finish. + * + * `/history/{id}` gaining an entry is the only completion signal the HTTP API + * has - the WebSocket is how the frontend learns it first, and this row does + * not open a socket. A prompt that leaves the queue without a history entry was + * dropped (the server restarted, or the item was deleted), which is reported + * rather than waited out. + * + * @returns `{ entry, waitedMs, timedOut, dropped }`. + */ +export async function waitForHistory(deps, origin, promptId, options = {}) { + const started = typeof deps.now === 'function' ? deps.now() : Date.now() + const timeoutMs = options.timeoutMs ?? 600000 + const intervalMs = options.intervalMs ?? 500 + for (;;) { + const entry = await historyOf(deps, origin, promptId, { signal: options.signal }) + if (entry !== null) { + const now = typeof deps.now === 'function' ? deps.now() : Date.now() + return { entry, waitedMs: now - started, timedOut: false, dropped: false } + } + const now = typeof deps.now === 'function' ? deps.now() : Date.now() + if (now - started >= timeoutMs) return { entry: null, waitedMs: now - started, timedOut: true, dropped: false } + if (typeof options.onTick === 'function') await options.onTick({ waitedMs: now - started }) + // After the first minute, asking the queue every tick is a lot of requests + // for an answer that cannot change quickly - and it is how a prompt that was + // DROPPED (server restart, deleted item) is told from one still waiting. + if (now - started > 60000) { + const queue = await queueOf(deps, origin, { signal: options.signal }).catch(() => null) + if (queue !== null) { + const present = [...queue.running, ...queue.pending].some((item) => Array.isArray(item) && String(item[1]) === promptId) + if (!present) { + const late = await historyOf(deps, origin, promptId, { signal: options.signal }) + if (late === null) return { entry: null, waitedMs: now - started, timedOut: false, dropped: true } + } + } + } + await (deps.sleep ? deps.sleep(intervalMs) : new Promise((resolve) => setTimeout(resolve, intervalMs))) + } +} + +/** Bytes as a person reads them. */ +export function formatBytes(bytes) { + if (typeof bytes !== 'number' || !Number.isFinite(bytes) || bytes <= 0) return '0 B' + const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'] + let value = bytes + let unit = 0 + while (value >= 1024 && unit < units.length - 1) { + value /= 1024 + unit += 1 + } + return (value >= 100 || unit === 0 ? Math.round(value) : value.toFixed(1)) + ' ' + units[unit] +} + +/** Milliseconds as a person reads them. */ +export function formatMilliseconds(ms) { + if (typeof ms !== 'number' || !Number.isFinite(ms)) return 'n/a' + if (ms < 1000) return Math.round(ms) + ' ms' + if (ms < 60000) return (ms / 1000).toFixed(2) + ' s' + const minutes = Math.floor(ms / 60000) + const seconds = Math.round((ms % 60000) / 1000) + return minutes + ' min ' + seconds + ' s' +} diff --git a/packages/dsh-comfyui/lib/compile.js b/packages/dsh-comfyui/lib/compile.js new file mode 100644 index 0000000..377fbd7 --- /dev/null +++ b/packages/dsh-comfyui/lib/compile.js @@ -0,0 +1,430 @@ +/** + * dsh-comfyui — the compiler: a project spec becomes the two files ComfyUI + * actually consumes. + * + * prompt.json the API prompt `/prompt` accepts: `{ "": { class_type, + * inputs, _meta } }`, where a wire is `[ "", slot ]`. + * workflow.json the canvas the APP opens: nodes with positions, an `inputs` + * array per node, and `links`, which is what a person drags + * around and what the frontend's "Save" would have written. + * + * The two are not interchangeable and are produced together because each is + * unreadable to the other consumer: `/prompt` wants ids and slot numbers; the + * canvas wants geometry and widget arrays. + * + * THE HARD PART, AND WHY THE CATALOG IS REQUIRED: `widgets_values` is an + * UNNAMED array. Its meaning is the class's input order, and there is one trap + * with no syntactic marker at all - a class whose INT input declares + * `control_after_generate: true` gets an EXTRA string value right after that + * input ("fixed" / "increment" / "decrement" / "randomize"). Measured on + * ComfyUI 0.21.1: `KSampler.seed` has it, so its array is + * `[seed, "fixed", steps, cfg, sampler_name, scheduler, denoise]`, and a + * compiler that omits the extra value silently shifts every widget after the + * seed - the graph opens, the values are wrong, and nothing reports it. That is + * the defect this module exists to make impossible. + * + * Positions are computed when the spec does not give them (columns by depth, so + * a compiled graph reads left-to-right instead of stacking at the origin), and + * every emitted file records WHICH catalog built it, so a graph compiled + * against the built-in table is never presented as one checked against a + * server. + */ + +import { ComfyError } from './errors.js' +import { linkInputs, nodeIn, SOURCES, widgetInputs } from './nodes.js' +import { resolveWire } from './spec.js' + +/** The workflow format version this package writes (the 0.4 object-link form). */ +export const WORKFLOW_VERSION = 0.4 + +/** The default `control_after_generate` value: a build must be reproducible. */ +export const DEFAULT_CONTROL_AFTER_GENERATE = 'fixed' + +/** The four values ComfyUI's frontend offers after a control widget. */ +export const CONTROL_AFTER_GENERATE = ['fixed', 'increment', 'decrement', 'randomize'] + +/** A canvas column's width and a row's height, in pixels. */ +const COLUMN_WIDTH = 400 +const ROW_HEIGHT = 300 + +/** One finding, shaped like the rest of the package. */ +function finding(severity, type, message, where = {}) { + return { severity, type, message, ...where } +} + +/** + * Resolve `@bindings` and coerce every widget value to the type its input + * declares. + * + * A binding is the project's promise that "whichever checkpoint this machine + * has" is a decision made at build time, not a filename frozen into a document. + * An unresolved binding is an ERROR, never a silent default: a graph built with + * a checkpoint nobody chose is a graph whose first run fails with + * `value_not_in_list`, one step removed from the cause. + * + * @returns `{ values, findings }` where `values` is `Map`. + */ +export function resolveWidgetValues(project, catalog) { + const values = new Map() + const findings = [] + for (const node of project.nodes) { + const spec = nodeIn(catalog, node.class) + const resolved = {} + for (const [inputName, rawValue] of Object.entries(node.widgets)) { + const inputSpec = spec === null ? null : spec.inputs.find((input) => input.name === inputName) ?? null + let value = rawValue + if (typeof value === 'string' && value.startsWith('@')) { + const binding = value.slice(1) + if (!(binding in project.bindings)) { + findings.push( + finding( + 'error', + 'BINDING_UNRESOLVED', + 'node "' + node.key + '" input "' + inputName + '" asks for the binding "@' + binding + '", which this project does not declare. Declared bindings: ' + (Object.keys(project.bindings).join(', ') || '(none)') + '. Set it in project.json\'s `bindings`, or pass it to `comfy_project` action=new.', + { node: node.key, input: inputName, binding }, + ), + ) + continue + } + value = project.bindings[binding] + } + const coerced = coerce(value, inputSpec) + if (coerced.error !== '') { + findings.push(finding('error', coerced.type, 'node "' + node.key + '" input "' + inputName + '": ' + coerced.error, { node: node.key, input: inputName })) + continue + } + resolved[inputName] = coerced.value + } + values.set(node.key, resolved) + } + return { values, findings } +} + +/** + * One widget value, in the type its input declares. + * + * A COMBO is matched against the server's own option list, and a + * case-insensitive match is normalized to the server's spelling - so a spec + * that says "SGM Uniform" builds against a server that spells it + * "sgm_uniform", instead of failing on a detail nobody meant to type. + */ +export function coerce(value, inputSpec) { + if (inputSpec === null) return { value, error: '', type: '' } + const type = inputSpec.type + if (type === 'INT') { + const number = typeof value === 'number' ? value : Number(String(value).trim()) + if (!Number.isFinite(number) || !Number.isInteger(number)) { + return { value, error: 'expected an integer, got ' + JSON.stringify(value) + '.', type: 'invalid_input_type' } + } + if (inputSpec.options !== undefined && typeof inputSpec.options.min === 'number' && number < inputSpec.options.min) { + return { value: number, error: 'value ' + number + ' is smaller than the minimum ' + inputSpec.options.min + '.', type: 'value_smaller_than_min' } + } + if (inputSpec.options !== undefined && typeof inputSpec.options.max === 'number' && number > inputSpec.options.max) { + return { value: number, error: 'value ' + number + ' is bigger than the maximum ' + inputSpec.options.max + '.', type: 'value_bigger_than_max' } + } + return { value: number, error: '', type: '' } + } + if (type === 'FLOAT') { + const number = typeof value === 'number' ? value : Number(String(value).trim()) + if (!Number.isFinite(number)) return { value, error: 'expected a number, got ' + JSON.stringify(value) + '.', type: 'invalid_input_type' } + if (inputSpec.options !== undefined && typeof inputSpec.options.min === 'number' && number < inputSpec.options.min) { + return { value: number, error: 'value ' + number + ' is smaller than the minimum ' + inputSpec.options.min + '.', type: 'value_smaller_than_min' } + } + if (inputSpec.options !== undefined && typeof inputSpec.options.max === 'number' && number > inputSpec.options.max) { + return { value: number, error: 'value ' + number + ' is bigger than the maximum ' + inputSpec.options.max + '.', type: 'value_bigger_than_max' } + } + return { value: number, error: '', type: '' } + } + if (type === 'BOOLEAN') return { value: value === true || value === 'true' || value === 1, error: '', type: '' } + if (type === 'STRING') return { value: String(value), error: '', type: '' } + if (type === 'COMBO') { + if (inputSpec.enum !== null && inputSpec.enum.length > 0) { + const text = String(value) + if (inputSpec.enum.includes(text)) return { value: text, error: '', type: '' } + const insensitive = inputSpec.enum.find((option) => option.toLowerCase() === text.toLowerCase()) + if (insensitive !== undefined) return { value: insensitive, error: '', type: '' } + const shown = inputSpec.enum.slice(0, 12) + return { + value, + error: + 'value ' + + JSON.stringify(text) + + ' is not in this server\'s list for that input. Options: ' + + shown.join(', ') + + (inputSpec.enum.length > shown.length ? ', … (' + inputSpec.enum.length + ' total)' : '') + + '.', + type: 'value_not_in_list', + } + } + return { value: String(value), error: '', type: '' } + } + // A link type used as a widget value: the class declared it as a widget + // through a shape this compiler does not model, so pass it through untouched + // rather than guessing a conversion. + return { value, error: '', type: '' } +} + +/** + * Compile a validated project. + * + * @param project - a `readSpec` project. + * @param catalog - the catalog in force. + * @param options - `{ controlAfterGenerate }` default for seed widgets. + * @returns `{ prompt, workflow, ids, order, widgetOrder, findings }`; any + * `findings` entry with severity `error` means nothing should be run. + */ +export function compileProject(project, catalog, options = {}) { + const findings = [] + const { values, findings: bindingFindings } = resolveWidgetValues(project, catalog) + findings.push(...bindingFindings) + + // Ids: declaration order, 1-based, because that is what a hand-written + // ComfyUI workflow looks like and what a reader expects to see. + const ids = new Map() + for (const [index, node] of project.nodes.entries()) ids.set(node.key, index + 1) + + const prompt = {} + for (const node of project.nodes) { + const spec = nodeIn(catalog, node.class) + const inputs = {} + for (const [inputName, value] of Object.entries(values.get(node.key) ?? {})) inputs[inputName] = value + for (const [inputName, target] of Object.entries(node.wires)) { + const resolved = resolveWire(target, project.byKey, catalog) + if (resolved.error !== '') { + findings.push(finding('error', resolved.type, 'node "' + node.key + '" input "' + inputName + '": ' + resolved.error, { node: node.key, input: inputName })) + continue + } + inputs[inputName] = [String(ids.get(resolved.key)), resolved.slot] + } + const title = node.title !== '' ? node.title : spec !== null ? spec.displayName : node.class + prompt[String(ids.get(node.key))] = { class_type: node.class, inputs, _meta: { title } } + } + + const workflow = buildWorkflow(project, catalog, ids, values, options, findings) + const widgetOrder = catalogueSourceOf(project, catalog) + return { prompt, workflow, ids, widgetOrder, findings } +} + +/** Which catalog decided the widget layout - the fact a build record carries. */ +function catalogueSourceOf(project, catalog) { + if (catalog.complete) return catalog.source + const everyKnown = project.nodes.every((node) => nodeIn(catalog, node.class) !== null) + return everyKnown ? catalog.source : catalog.source + '-partial' +} + +/** + * The canvas. + * + * `inputs` carries the classic frontend form on purpose: an entry appears for a + * link input, and for a widget input ONLY when a wire feeds it (with + * `widget: { name }` marking the conversion). That is what every ComfyUI before + * the 0.4 canvas wrote, and the current frontend migrates it on load - so the + * file opens on old installs and new ones, which the current object-only form + * does not. + */ +function buildWorkflow(project, catalog, ids, values, options, findings) { + const order = topologicalOrder(project) + const orderIndex = new Map(order.map((key, index) => [key, index])) + const positions = layout(project, order) + const links = [] + const linkIdsByTarget = new Map() + let linkId = 0 + + for (const node of project.nodes) { + for (const [inputName, target] of Object.entries(node.wires)) { + const resolved = resolveWire(target, project.byKey, catalog) + if (resolved.error !== '') continue + const targetNode = nodeIn(catalog, project.byKey.get(resolved.key).class) + linkId += 1 + const type = targetNode !== null && targetNode.outputs[resolved.slot] !== undefined ? targetNode.outputs[resolved.slot].type : '*' + links.push({ id: linkId, origin_id: ids.get(resolved.key), origin_slot: resolved.slot, target_id: ids.get(node.key), target_slot: -1, type }) + const list = linkIdsByTarget.get(node.key) ?? [] + list.push({ input: inputName, id: linkId }) + linkIdsByTarget.set(node.key, list) + } + } + + const nodes = [] + for (const node of project.nodes) { + const spec = nodeIn(catalog, node.class) + const wired = new Map((linkIdsByTarget.get(node.key) ?? []).map((entry) => [entry.input, entry.id])) + const inputs = [] + if (spec !== null) { + for (const input of spec.inputs) { + if (input.kind === 'hidden') continue + const link = wired.get(input.name) + if (input.kind === 'link') { + if (link === undefined) continue + inputs.push({ name: input.name, type: input.type, link }) + continue + } + if (link !== undefined) inputs.push({ name: input.name, type: input.type, widget: { name: input.name }, link }) + } + } + // The target_slot of every link into this node is its position in `inputs`. + for (const entry of linkIdsByTarget.get(node.key) ?? []) { + const at = inputs.findIndex((input) => input.name === entry.input) + const link = links.find((candidate) => candidate.id === entry.id) + if (link !== undefined) link.target_slot = at === -1 ? inputs.length : at + } + const outputs = (spec === null ? [] : spec.outputs).map((output, slot) => ({ + name: output.name, + type: output.type, + links: links.filter((link) => link.origin_id === ids.get(node.key) && link.origin_slot === slot).map((link) => link.id), + slot_index: slot, + })) + for (const output of outputs) if (output.links.length === 0) output.links = null + const widgets = spec === null ? [] : widgetInputs(spec) + const widgetsValues = [] + const resolved = values.get(node.key) ?? {} + for (const input of widgets) { + if (input.name in resolved) widgetsValues.push(resolved[input.name]) + else if (input.options !== undefined && input.options.default !== undefined) widgetsValues.push(input.options.default) + else if (input.enum !== null && input.enum.length > 0) widgetsValues.push(input.enum[0]) + else widgetsValues.push('') + if (input.controlAfterGenerate) { + const chosen = node.controlAfterGenerate[input.name] ?? options.controlAfterGenerate ?? DEFAULT_CONTROL_AFTER_GENERATE + if (!CONTROL_AFTER_GENERATE.includes(chosen)) { + findings.push( + finding( + 'warning', + 'bad_control_after_generate', + 'node "' + node.key + '" input "' + input.name + '" asks for control_after_generate "' + String(chosen) + '", which is not one of ' + CONTROL_AFTER_GENERATE.join(', ') + '; "fixed" was used.', + { node: node.key, input: input.name }, + ), + ) + widgetsValues.push(DEFAULT_CONTROL_AFTER_GENERATE) + } else { + widgetsValues.push(chosen) + } + } + } + const title = node.title !== '' ? node.title : spec !== null ? spec.displayName : node.class + nodes.push({ + id: ids.get(node.key), + type: node.class, + pos: positions.get(node.key) ?? [0, 0], + size: node.size ?? estimateSize(spec), + flags: {}, + order: orderIndex.get(node.key) ?? 0, + mode: node.mode, + inputs, + outputs, + title, + properties: { 'Node name for S&R': node.class }, + widgets_values: widgetsValues, + }) + } + + return { + revision: 0, + last_node_id: project.nodes.length, + last_link_id: linkId, + nodes, + links, + groups: [], + config: {}, + extra: { ds: { scale: 1, offset: [0, 0] } }, + version: WORKFLOW_VERSION, + } +} + +/** A node's box on the canvas, from how much text it has to show. */ +function estimateSize(spec) { + if (spec === null) return [320, 120] + const widgets = widgetInputs(spec).length + const slots = Math.max(linkInputs(spec).length, spec.outputs.length) + const height = Math.max(90, 46 + widgets * 26 + Math.max(0, slots - widgets) * 22) + return [320, height] +} + +/** + * The execution order the canvas records: a node's `order` is its index in a + * topological pass, which is what the frontend writes after it sorts the graph. + */ +function topologicalOrder(project) { + const pending = new Map(project.nodes.map((node) => [node.key, new Set(Object.values(node.wires).map((target) => String(target).split('.')[0]))])) + const done = [] + const seen = new Set() + while (done.length < project.nodes.length) { + let progressed = false + for (const node of project.nodes) { + if (seen.has(node.key)) continue + const waiting = [...(pending.get(node.key) ?? [])].filter((key) => !seen.has(key) && project.byKey.has(key)) + if (waiting.length > 0) continue + seen.add(node.key) + done.push(node.key) + progressed = true + } + if (!progressed) { + // A cycle: everything left is emitted in declaration order, which is what + // the validator has already reported as an error. + for (const node of project.nodes) if (!seen.has(node.key)) { + seen.add(node.key) + done.push(node.key) + } + } + } + return done +} + +/** + * Put the nodes on the canvas: one column per dependency depth, one row per + * node in that column. + * + * Without this every node lands on (0,0) and the person opens a graph they + * cannot see - the difference between a workflow that is CORRECT and one that + * is usable. + */ +function layout(project, order) { + const depth = new Map() + for (const key of order) { + const node = project.byKey.get(key) + if (node === undefined) continue + if (node.pos !== null) { + depth.set(key, 0) + continue + } + let deepest = -1 + for (const target of Object.values(node.wires)) { + const source = String(target).split('.')[0] + const value = depth.get(source) + if (typeof value === 'number' && value > deepest) deepest = value + } + depth.set(key, deepest + 1) + } + const rowsIn = new Map() + const positions = new Map() + for (const key of order) { + const node = project.byKey.get(key) + if (node === undefined) continue + if (node.pos !== null) { + positions.set(key, node.pos) + continue + } + const column = depth.get(key) ?? 0 + const row = rowsIn.get(column) ?? 0 + rowsIn.set(column, row + 1) + positions.set(key, [40 + column * COLUMN_WIDTH, 40 + row * ROW_HEIGHT]) + } + return positions +} + +/** The classes a project uses that the catalog does not know. */ +export function unknownClasses(project, catalog) { + return project.nodes.filter((node) => nodeIn(catalog, node.class) === null).map((node) => node.class) +} + +/** The catalog's own name for where it came from, for a build record. */ +export function describeCatalog(catalog) { + if (catalog.source === SOURCES.core) return 'built-in core table (' + catalog.nodes.size + ' nodes)' + if (catalog.source === SOURCES.cache) return 'cached /object_info' + (catalog.version === '' ? '' : ' from ComfyUI ' + catalog.version) + (catalog.fetchedAt === '' ? '' : ', ' + catalog.fetchedAt) + return '/object_info from ' + (catalog.origin === '' ? 'the server' : catalog.origin) + (catalog.version === '' ? '' : ' (ComfyUI ' + catalog.version + ')') +} + +/** A compiled project as a ComfyError when there is nothing to compile. */ +export function assertCompiled(result) { + const errors = result.findings.filter((entry) => entry.severity === 'error') + if (errors.length === 0) return result + throw new ComfyError('PROJECT_INVALID', errors.length + ' error(s) stop this project from compiling: ' + errors.map((entry) => entry.message).join(' '), { findings: errors }) +} diff --git a/packages/dsh-comfyui/lib/errors.js b/packages/dsh-comfyui/lib/errors.js new file mode 100644 index 0000000..c485388 --- /dev/null +++ b/packages/dsh-comfyui/lib/errors.js @@ -0,0 +1,59 @@ +/** + * dsh-comfyui — the error vocabulary. + * + * Every refusal names the thing that would go WRONG and the next move, because + * the caller is an agent that reads one sentence and acts: a project that does + * not build, a graph that would be rejected by `/prompt`, or a server that is + * not there are different problems with different fixes, and a single generic + * "failed" collapses them into a guess. + * + * The codes are the branch points the package check drives, and the ones a + * tool view exposes as `code` so a caller can decide without reading prose. + */ + +/** One typed refusal. `extra` travels to the view untouched. */ +export class ComfyError extends Error { + /** + * @param code - a stable code, e.g. 'SERVER_DOWN', 'PROJECT_INVALID'. + * @param message - the sentence the caller acts on. + * @param extra - facts the view carries (path, node, field, ...). + */ + constructor(code, message, extra = {}) { + super(message) + this.name = 'ComfyError' + this.code = code + this.extra = extra + } +} + +/** The sentence of any thrown value, without inventing one. */ +export function messageOf(error) { + if (error === null || error === undefined) return 'unknown failure' + if (typeof error === 'string') return error + if (typeof error.message === 'string' && error.message !== '') return error.message + return String(error) +} + +/** The code of any thrown value, or 'FAILED'. */ +export function codeOf(error) { + return error && typeof error.code === 'string' && error.code !== '' ? error.code : 'FAILED' +} + +/** + * A validation finding, in the shape ComfyUI's own validator uses. + * + * `type` is deliberately the SAME string `/prompt` returns (`required_input_missing`, + * `return_type_mismatch`, `value_not_in_list`, `dependency_cycle`, ...): a + * project that fails here would fail there, and a reader should not have to + * translate between two vocabularies for the same defect. `where` is the extra + * this row adds - the node KEY the spec uses and the input name - because + * "node 7" is not searchable in the file the person is editing. + */ +export function finding(severity, type, message, where = {}) { + return { severity, type, message, ...where } +} + +/** All the errors of a finding list, for a one-line summary. */ +export function countBy(findings, severity) { + return findings.filter((entry) => entry.severity === severity).length +} diff --git a/packages/dsh-comfyui/lib/examples.js b/packages/dsh-comfyui/lib/examples.js new file mode 100644 index 0000000..84bcb49 --- /dev/null +++ b/packages/dsh-comfyui/lib/examples.js @@ -0,0 +1,85 @@ +/** + * dsh-comfyui — the shipped example library. + * + * An example is a SPEC, not a frozen graph, and it lives as a folder with a + * `project.json` so the same file can be read by a person, edited in place, and + * compiled by `comfy_test`. Nothing here decides what the examples mean: the + * directory listing is the catalog, so a new example is one folder and a + * manifest entry that cannot drift, because there is no separate index to + * forget. + * + * The library is deliberately ordered from "no model needed" to "needs a + * checkpoint", because the first question on a new machine is whether anything + * runs at all - and a 2 GB download must never be what stands between a person + * and their first green tick. + */ + +import { existsSync, readFileSync, readdirSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +/** Where the example folders live, beside this module. */ +export const EXAMPLES_DIR = fileURLToPath(new URL('../examples/', import.meta.url)) + +/** Read one JSON file, or throw with the path in the sentence. */ +function readJson(file) { + return JSON.parse(readFileSync(file, 'utf8')) +} + +/** + * The example library, sorted the way it should be tried. + * + * @param dir - the examples folder (injectable for the check). + * @returns `[{ slug, title, description, tags, requires, nodes, file }]`. + */ +export function listExamples(dir = EXAMPLES_DIR) { + if (!existsSync(dir)) return [] + const found = [] + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (!entry.isDirectory()) continue + const file = path.join(dir, entry.name, 'project.json') + if (!existsSync(file)) continue + let spec + try { + spec = readJson(file) + } catch (error) { + found.push({ slug: entry.name, title: entry.name, description: '', tags: [], requires: {}, nodes: 0, file, error: error.message }) + continue + } + found.push({ + slug: entry.name, + title: typeof spec.title === 'string' && spec.title !== '' ? spec.title : entry.name, + description: typeof spec.description === 'string' ? spec.description : '', + tags: Array.isArray(spec.tags) ? spec.tags.map(String) : [], + requires: spec.requires !== null && typeof spec.requires === 'object' ? spec.requires : {}, + nodes: Array.isArray(spec.nodes) ? spec.nodes.length : 0, + file, + }) + } + const weight = (entry) => (entry.tags.includes('no-models') ? 0 : entry.tags.includes('needs-input') ? 2 : 1) + return found.sort((left, right) => weight(left) - weight(right) || left.slug.localeCompare(right.slug)) +} + +/** One example's spec, or null. */ +export function readExample(slug, dir = EXAMPLES_DIR) { + const file = path.join(dir, String(slug), 'project.json') + if (!existsSync(file)) return null + return readJson(file) +} + +/** Whether a slug names a shipped example. */ +export function hasExample(slug, dir = EXAMPLES_DIR) { + return existsSync(path.join(dir, String(slug), 'project.json')) +} + +/** What one example needs, as one line for a table. */ +export function requirementLine(example) { + const models = example.requires !== null && typeof example.requires === 'object' && example.requires.models !== null && typeof example.requires.models === 'object' ? example.requires.models : {} + const files = Object.entries(models).flatMap(([folder, list]) => (Array.isArray(list) ? list.map((name) => folder + '/' + name) : [])) + const inputs = example.requires !== null && typeof example.requires === 'object' && Array.isArray(example.requires.inputFiles) ? example.requires.inputFiles : [] + const parts = [] + if (files.length === 0) parts.push('no model') + else parts.push(files.join(', ')) + if (inputs.length > 0) parts.push('input: ' + inputs.join(', ')) + return parts.join(' · ') +} diff --git a/packages/dsh-comfyui/lib/files.js b/packages/dsh-comfyui/lib/files.js new file mode 100644 index 0000000..8c525ba --- /dev/null +++ b/packages/dsh-comfyui/lib/files.js @@ -0,0 +1,241 @@ +/** + * dsh-comfyui — "does this machine actually HAVE the files this graph names?" + * + * THE QUESTION NOBODY ELSE ANSWERS. With a server running, `/object_info` + * answers it: a combo's options ARE the filenames in that folder, so a missing + * checkpoint comes back as `value_not_in_list` from ComfyUI's own validator. With + * no server, nothing did - a project compiled, validated, and reported a clean + * `v1-structural` while naming a 2 GB checkpoint that is not on the disk. + * + * So this module reads the INSTALL instead of the server: the base path + * `comfy_status` found, `models//`, `input/`, and any extra model root + * comfy-cli reports. It checks an API PROMPT - the compiled one, with its + * `@bindings` already resolved - because a spec's raw `"@checkpoint"` is not a + * filename and checking it would report a missing file called "@checkpoint". + * + * It runs ONLY for a file input whose option list the catalog did not know (a + * complete catalog means the server already answered, and a second opinion from + * the filesystem could disagree with a folder path the server resolves + * differently). + * + * The finding keeps ComfyUI's own type, `value_not_in_list`, because that is the + * sentence `/prompt` would return for the same file - and it carries the two + * things a person needs: how many files ARE in that folder, and the nearest name + * to the one the graph wants. `v1-structural` on a machine whose models happen to + * be there is a real claim; without this check it was a claim nobody had made. + */ + +import { existsSync, readdirSync } from 'node:fs' +import path from 'node:path' + +import { FILE_INPUTS } from './nodes.js' + +/** The folders a file input can come from, as the ComfyUI base path names them. */ +export function folderOf(inputName) { + return FILE_INPUTS[inputName] ?? null +} + +/** Every file in one folder, relative and slash-separated, bounded in depth. */ +export function filesIn(dir, options = {}) { + const files = [] + const depthLimit = Number.isInteger(options.depth) ? options.depth : 2 + const extensions = options.extensions ?? null + if (!existsSync(dir)) return files + const walk = (current, prefix, depth) => { + let entries + try { + entries = readdirSync(current, { withFileTypes: true }) + } catch (error) { + return + } + for (const entry of entries) { + if (entry.name.startsWith('.')) continue + const relative = prefix === '' ? entry.name : prefix + '/' + entry.name + if (entry.isDirectory()) { + if (depth < depthLimit) walk(path.join(current, entry.name), relative, depth + 1) + continue + } + if (extensions !== null && !extensions.test(entry.name)) continue + files.push(relative) + } + } + walk(dir, '', 0) + return files.sort() +} + +/** The extensions ComfyUI's own loaders accept, so a stray .txt is not a candidate. */ +const MODEL_EXTENSIONS = /\.(safetensors|ckpt|pt|pth|bin|gguf|sft|onnx)$/i + +/** The extensions an `input/` file may have. */ +const INPUT_EXTENSIONS = /\.(png|jpe?g|webp|gif|bmp|tiff?|avif|mp4|webm|mov|mkv|wav|mp3|flac|ogg|m4a|aiff?)$/i + +/** + * The nearest names to one that was asked for, so a typo is visible. + * + * Not a Levenshtein table: a person's mistake is almost always a wrong folder, a + * different version string, or a dropped path prefix, and those show up as a + * shared stem. Three candidates, no more - the finding is a pointer, not a list. + */ +export function nearestNames(wanted, candidates, limit = 3) { + const target = String(wanted).toLowerCase() + const stem = target.replace(/\.[^.]+$/, '') + const scored = [] + for (const candidate of candidates) { + const lower = candidate.toLowerCase() + const otherStem = lower.replace(/\.[^.]+$/, '') + let score = 0 + if (lower === target) score = 100 + else if (otherStem === stem) score = 90 + else if (otherStem.startsWith(stem) || stem.startsWith(otherStem)) score = 70 + else if (otherStem.includes(stem) || stem.includes(otherStem)) score = 50 + else if (lower.includes(target)) score = 30 + if (score > 0) scored.push({ candidate, score }) + } + scored.sort((left, right) => right.score - left.score || left.candidate.localeCompare(right.candidate)) + const picked = scored.slice(0, limit).map((entry) => entry.candidate) + if (picked.length > 0) return picked + return candidates.slice(0, limit) +} + +/** + * A checker bound to one install: `check(folder, name, where)` records a finding + * or nothing, and remembers what it looked at. + */ +function makeChecker(install) { + const findings = [] + const checked = [] + const roots = [] + const base = install.base + // A Desktop install can keep its models in a shared folder beside the app + // (comfy-cli reports those as `model_roots`): they are searched too, so a file + // that IS on the machine is never reported missing. + const extraRoots = Array.isArray(install.modelRoots) ? install.modelRoots.filter((root) => typeof root === 'string' && root !== '') : [] + const seen = new Set() + const check = (folder, declared, where) => { + if (typeof declared !== 'string' || declared === '') return + const key = folder + '/' + declared + if (seen.has(key)) return + seen.add(key) + const primary = folder === 'input' ? path.join(base, 'input') : path.join(base, 'models', folder) + const extras = folder === 'input' ? [] : extraRoots.map((root) => path.join(root, folder)).filter((dir) => dir !== primary) + const dirs = [primary, ...extras].filter((dir) => existsSync(dir)) + const extensions = folder === 'input' ? INPUT_EXTENSIONS : MODEL_EXTENSIONS + if (dirs.length === 0) { + findings.push({ + severity: 'warning', + type: 'model_folder_absent', + message: 'the graph needs "' + declared + '" from ' + (folder === 'input' ? 'input/' : 'models/' + folder + '/') + ', and that folder does not exist under ' + base + '. Nothing can be checked about the file until it does.', + ...where, + }) + return + } + for (const dir of dirs) if (!roots.includes(dir)) roots.push(dir) + checked.push({ folder, declared }) + for (const dir of dirs) if (existsSync(path.join(dir, declared))) return + const candidates = [] + for (const dir of dirs) candidates.push(...filesIn(dir, { extensions, depth: 2 })) + const nearest = nearestNames(declared, candidates) + const count = candidates.length + findings.push({ + severity: 'error', + type: 'value_not_in_list', + message: + (folder === 'input' ? 'input/' + declared : 'models/' + folder + '/' + declared) + + ' does not exist on this machine (' + + (count === 0 ? 'that folder is empty' : count + ' file(s) there') + + (nearest.length === 0 ? '' : '; nearest: ' + nearest.join(', ')) + + '). ComfyUI refuses a prompt naming a file it does not have with value_not_in_list, so this graph cannot run yet. Put the file in that folder, or point the binding at one of the names above.', + path: path.join(primary, declared), + searched: dirs, + ...where, + }) + } + return { check, findings, checked, roots } +} + +/** The answer when there is no install to check against. */ +function noInstall() { + return { findings: [], checked: [], missing: 0, roots: [], skipped: 'no ComfyUI base path with models/ and input/ was found, so no file could be checked' } +} + +/** + * Check an API prompt's file-named inputs, and anything the spec declares. + * + * @param options - `{ prompt, catalog, install, requires }`. + * @returns `{ findings, checked, missing, roots, skipped }`. + */ +export function checkPromptFiles(options) { + const install = options.install ?? null + const catalog = options.catalog ?? null + const prompt = options.prompt !== null && typeof options.prompt === 'object' ? options.prompt : {} + const requires = options.requires !== null && typeof options.requires === 'object' ? options.requires : null + if (install === null || typeof install.base !== 'string' || install.base === '') return noInstall() + const checker = makeChecker(install) + + for (const [nodeId, node] of Object.entries(prompt)) { + if (node === null || typeof node !== 'object' || typeof node.class_type !== 'string') continue + const inputs = node.inputs !== null && typeof node.inputs === 'object' ? node.inputs : {} + for (const [inputName, value] of Object.entries(inputs)) { + if (Array.isArray(value) || value === null || typeof value === 'object') continue + const folder = folderForNode(catalog, node.class_type, inputName) + if (folder === null || folder.fromCatalog === true) continue + if (typeof value !== 'string') continue + checker.check(folder.folder, value, { node: nodeId, input: inputName }) + } + } + + // What the spec DECLARES it needs, even when no node in it names the file. + if (requires !== null) { + for (const [folder, list] of Object.entries(requires.models ?? {})) { + if (!Array.isArray(list)) continue + for (const name of list) checker.check(folder, name, { declared: true }) + } + for (const name of Array.isArray(requires.inputFiles) ? requires.inputFiles : []) checker.check('input', name, { declared: true }) + } + + return { findings: checker.findings, checked: checker.checked, missing: checker.findings.filter((entry) => entry.severity === 'error').length, roots: checker.roots, skipped: '' } +} + +/** Which folder one input reads from, and whether the catalog already answered it. */ +function folderForNode(catalog, classType, inputName) { + const spec = catalog === null ? null : catalog.nodes.get(classType) ?? null + const inputSpec = spec === null ? null : spec.inputs.find((input) => input.name === inputName) ?? null + if (inputSpec !== null && inputSpec.enum !== null) return { folder: '', fromCatalog: true } + const folder = inputSpec !== null && inputSpec.fileFolder !== null ? inputSpec.fileFolder : folderOf(inputName) + if (folder === null) return null + return { folder, fromCatalog: false } +} + +/** + * The install's own inventory, for `comfy_status`: what each folder holds, with + * the first few names, so a reader can see a checkpoint is there without asking + * for it. + */ +export function inventory(install, options = {}) { + if (install === null || typeof install.base !== 'string' || install.base === '') return { folders: {}, files: 0, roots: [] } + const perFolder = Number.isInteger(options.perFolder) ? options.perFolder : 4 + const folders = {} + let files = 0 + const modelsDir = path.join(install.base, 'models') + if (existsSync(modelsDir)) { + let entries = [] + try { + entries = readdirSync(modelsDir, { withFileTypes: true }) + } catch (error) { + entries = [] + } + for (const entry of entries) { + if (!entry.isDirectory() || entry.name.startsWith('.')) continue + const names = filesIn(path.join(modelsDir, entry.name), { extensions: MODEL_EXTENSIONS, depth: 2 }) + folders[entry.name] = { count: names.length, first: names.slice(0, perFolder) } + files += names.length + } + } + const inputDir = path.join(install.base, 'input') + if (existsSync(inputDir)) { + const names = filesIn(inputDir, { extensions: INPUT_EXTENSIONS, depth: 1 }) + folders.input = { count: names.length, first: names.slice(0, perFolder) } + } + const roots = [modelsDir, inputDir].filter((dir) => existsSync(dir)) + return { folders, files, roots } +} diff --git a/packages/dsh-comfyui/lib/graph.js b/packages/dsh-comfyui/lib/graph.js new file mode 100644 index 0000000..c63930b --- /dev/null +++ b/packages/dsh-comfyui/lib/graph.js @@ -0,0 +1,520 @@ +/** + * dsh-comfyui — the validator and the reader for files this package did not + * write. + * + * TWO JOBS, ONE VOCABULARY. + * + * `validatePrompt` applies the checks ComfyUI's own `execution.validate_prompt` + * and `execution.validate_inputs` apply, offline, before anything is queued: + * a class that does not exist, a required input nobody set, a link that points + * at a node or slot that is not there, a wire whose type does not match, a + * widget value outside the server's list or its min/max, a dependency cycle, a + * graph with no output node. Each finding carries ComfyUI's OWN `type` string + * (`required_input_missing`, `return_type_mismatch`, `value_not_in_list`, + * `dependency_cycle`, `prompt_no_outputs`, ...) because a defect found here + * would be the same defect found there, and translating between two + * vocabularies for one problem is how an agent learns the wrong lesson. + * + * `workflowToPrompt` reads a UI workflow - the file the app's "Save" writes and + * a person drags into the canvas - and derives the API prompt from it. It needs + * the FULL catalog, and says so when it does not have one: `widgets_values` is + * an unnamed array, so without the class's input order the numbers cannot be + * attributed to names. A guess here would produce a prompt that runs and means + * something else. + * + * Measured on ComfyUI 0.21.1: a UI workflow stores links as OBJECTS + * (`{id, origin_id, origin_slot, target_id, target_slot, type}`), while every + * install before the 0.4 canvas stored ARRAYS (`[id, origin, slot, target, + * slot, type]`). Both are read; only the object form is written. + */ + +import { ComfyError } from './errors.js' +import { coerce } from './compile.js' +import { nodeIn } from './nodes.js' +import { typesCompatible } from './spec.js' + +/** Node modes the frontend uses: 0 always, 2 never, 4 bypass. */ +export const MODE_ALWAYS = 0 +export const MODE_NEVER = 2 +export const MODE_BYPASS = 4 + +/** The classes the FRONTEND draws that never reach an API prompt. */ +const VIRTUAL_CLASSES = new Set(['Reroute', 'PrimitiveNode', 'Note', 'MarkdownNote', 'GroupNode']) + +/** One finding, shaped like the rest of the package. */ +function finding(severity, type, message, where = {}) { + return { severity, type, message, ...where } +} + +/** + * Validate an API prompt against the catalog. + * + * @param prompt - `{ "": { class_type, inputs } }`. + * @param catalog - the catalog in force. + * @returns `{ findings, nodeErrors }` - `nodeErrors` is keyed by node id, the + * way `/prompt`'s `node_errors` is, so the two can be compared. + */ +export function validatePrompt(prompt, catalog) { + const findings = [] + if (prompt === null || typeof prompt !== 'object' || Array.isArray(prompt)) { + return { findings: [finding('error', 'prompt_invalid', 'An API prompt is an object keyed by node id, each value { class_type, inputs }; that is not what this is.')], nodeErrors: {} } + } + const ids = Object.keys(prompt) + if (ids.length === 0) { + return { findings: [finding('error', 'prompt_empty', 'The prompt has no nodes, so there is nothing to run.')], nodeErrors: {} } + } + const nodeErrors = {} + const add = (id, entry) => { + const list = nodeErrors[id] ?? [] + list.push(entry) + nodeErrors[id] = list + findings.push(entry) + } + + for (const id of ids) { + const node = prompt[id] + if (node === null || typeof node !== 'object') { + add(id, finding('error', 'bad_node', 'node ' + id + ' is not an object.', { node: id })) + continue + } + const classType = typeof node.class_type === 'string' ? node.class_type : '' + if (classType === '') { + add(id, finding('error', 'missing_node_type', 'node ' + id + ' has no `class_type`.', { node: id })) + continue + } + const spec = nodeIn(catalog, classType) + if (spec === null) { + const entry = catalog.complete + ? finding('error', 'missing_node_type', 'node ' + id + ' is class "' + classType + '", which this server does not have (a custom node missing from custom_nodes/ is the usual cause).', { node: id, class: classType }) + : finding('warning', 'class_unverified', 'node ' + id + ' is class "' + classType + '", which the built-in core table does not cover; nothing here can confirm it exists.', { node: id, class: classType }) + add(id, entry) + continue + } + const inputs = node.inputs !== null && typeof node.inputs === 'object' ? node.inputs : {} + for (const input of spec.inputs) { + if (input.kind === 'hidden' || input.optional) continue + if (!(input.name in inputs)) { + add(id, finding('error', 'required_input_missing', 'node ' + id + ' (' + classType + ') has no value for required input "' + input.name + '".', { node: id, input: input.name, class: classType })) + } + } + for (const [name, value] of Object.entries(inputs)) { + const inputSpec = spec.inputs.find((input) => input.name === name) + if (inputSpec === undefined) { + add(id, finding('warning', 'unknown_input', 'node ' + id + ' (' + classType + ') has an input "' + name + '" that the class does not declare, so the server ignores it. Its inputs: ' + spec.inputs.filter((input) => input.kind !== 'hidden').map((input) => input.name).join(', ') + '.', { node: id, input: name })) + continue + } + if (Array.isArray(value)) { + // A wire: [ "", slot ]. + if (value.length !== 2 || !Number.isInteger(value[1])) { + add(id, finding('error', 'bad_linked_input', 'node ' + id + ' input "' + name + '" is a wire but is not a [node id, slot] pair: ' + JSON.stringify(value) + '.', { node: id, input: name })) + continue + } + const sourceId = String(value[0]) + const source = prompt[sourceId] + if (source === undefined) { + add(id, finding('error', 'bad_linked_input', 'node ' + id + ' input "' + name + '" wires from node ' + sourceId + ', which is not in this prompt.', { node: id, input: name })) + continue + } + const sourceSpec = nodeIn(catalog, typeof source.class_type === 'string' ? source.class_type : '') + if (sourceSpec === null) continue + const slot = value[1] + if (slot < 0 || slot >= sourceSpec.outputs.length) { + add(id, finding('error', 'bad_linked_input', 'node ' + id + ' input "' + name + '" wires from node ' + sourceId + ' (' + source.class_type + ') slot ' + slot + ', which does not exist; that class has ' + sourceSpec.outputs.length + ' output(s).', { node: id, input: name })) + continue + } + const received = sourceSpec.outputs[slot].type + if (!compatible(received, inputSpec.type)) { + add(id, finding('error', 'return_type_mismatch', 'node ' + id + ' input "' + name + '" is ' + inputSpec.type + ', but node ' + sourceId + ' (' + source.class_type + ') output ' + slot + ' is ' + received + '. ComfyUI refuses this wire.', { node: id, input: name, received: received, expected: inputSpec.type })) + } + continue + } + if (inputSpec.kind === 'link') { + add(id, finding('error', 'invalid_input_type', 'node ' + id + ' input "' + name + '" needs a wire (' + inputSpec.type + ') but was given the value ' + JSON.stringify(value) + '.', { node: id, input: name })) + continue + } + const result = coerce(value, inputSpec) + if (result.error !== '') add(id, finding('error', result.type, 'node ' + id + ' (' + classType + ') input "' + name + '": ' + result.error, { node: id, input: name })) + } + } + + const cycle = cycleInPrompt(prompt, catalog) + if (cycle.length > 0) findings.push(finding('error', 'dependency_cycle', 'the prompt has a dependency cycle: ' + cycle.join(' -> ') + '.', { nodes: cycle })) + + const outputs = ids.filter((id) => { + const spec = nodeIn(catalog, prompt[id] && typeof prompt[id].class_type === 'string' ? prompt[id].class_type : '') + return spec !== null && spec.outputNode + }) + if (outputs.length === 0) { + const unknown = ids.filter((id) => nodeIn(catalog, prompt[id] && typeof prompt[id].class_type === 'string' ? prompt[id].class_type : '') === null).length + if (unknown > 0) findings.push(finding('warning', 'output_unverified', 'no node in this prompt is a KNOWN output node, and ' + unknown + ' class(es) could not be checked against a catalog.')) + else findings.push(finding('error', 'prompt_no_outputs', 'no node in this prompt is an output node, so ComfyUI answers `prompt_no_outputs` and runs nothing. A graph executes to its output nodes, not to every node.', { })) + } + + const reached = reachableFromOutputs(prompt, outputs) + const orphans = ids.filter((id) => !reached.has(id)) + if (orphans.length > 0) { + findings.push(finding('warning', 'unreachable_node', 'node(s) ' + orphans.join(', ') + ' do not feed any output, so they never execute (the queue runs what an output needs, nothing more).', { nodes: orphans })) + } + return { findings, nodeErrors } +} + +/** + * Whether an output type may feed an input - ComfyUI's `validate_node_input` + * rule, reached through `spec.typesCompatible` so the compiler and the + * validator cannot disagree about a wire. + */ +function compatible(received, wanted) { + return typesCompatible(received, wanted) +} + +/** The first cycle among prompt ids, as a readable path, or []. */ +function cycleInPrompt(prompt, catalog) { + const state = new Map() + const stack = [] + let found = null + const walk = (id) => { + if (found !== null) return + const mark = state.get(id) ?? 0 + if (mark === 1) { + found = stack.slice(stack.indexOf(id)).concat([id]) + return + } + if (mark === 2) return + state.set(id, 1) + stack.push(id) + const node = prompt[id] + if (node !== null && typeof node === 'object' && node.inputs !== null && typeof node.inputs === 'object') { + for (const value of Object.values(node.inputs)) { + if (Array.isArray(value) && value.length === 2 && typeof prompt[String(value[0])] === 'object') walk(String(value[0])) + } + } + stack.pop() + state.set(id, 2) + } + for (const id of Object.keys(prompt)) walk(id) + if (found === null) return [] + return found.map((id) => { + const node = prompt[id] + const classType = node && typeof node.class_type === 'string' ? node.class_type : '?' + return id + ' (' + classType + ')' + }) +} + +/** Everything an output node depends on, itself included. */ +function reachableFromOutputs(prompt, outputs) { + const seen = new Set() + const stack = [...outputs] + while (stack.length > 0) { + const id = stack.pop() + if (seen.has(id)) continue + seen.add(id) + const node = prompt[id] + if (node === null || typeof node !== 'object' || node.inputs === null || typeof node.inputs !== 'object') continue + for (const value of Object.values(node.inputs)) { + if (Array.isArray(value) && value.length === 2) stack.push(String(value[0])) + } + } + return seen +} + +/** + * A UI workflow's node/link lists, normalized. + * + * @returns `{ nodes, links, findings }`; `links` always in the object form. + * @throws ComfyError when the file is not a workflow (a subgraph-only export is + * the case worth naming, because it LOOKS like one). + */ +export function parseWorkflow(raw) { + if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) { + throw new ComfyError('WORKFLOW_INVALID', 'A UI workflow is a JSON object with `nodes` and `links`; that is not one.') + } + const nodes = Array.isArray(raw.nodes) ? raw.nodes : [] + const links = Array.isArray(raw.links) ? raw.links : [] + if (nodes.length === 0) { + const subgraphs = raw.definitions !== null && typeof raw.definitions === 'object' && Array.isArray(raw.definitions.subgraphs) ? raw.definitions.subgraphs : [] + if (subgraphs.length > 0) { + throw new ComfyError( + 'SUBGRAPH_ONLY', + 'This file has no top-level nodes: its graph lives inside a subgraph definition (' + subgraphs.map((entry) => JSON.stringify(entry.name ?? entry.id ?? '')).join(', ') + '). A subgraph is a frontend construct with virtual input/output nodes this package does not lower. Open it in ComfyUI, ungroup it (or right-click the subgraph and pick "Unpack"), then save again - or export the API form with "Export (API)".', + ) + } + throw new ComfyError('WORKFLOW_EMPTY', 'This workflow has no nodes, so there is nothing to read.') + } + const findings = [] + const normalized = [] + const seen = new Set() + for (const [index, node] of nodes.entries()) { + if (node === null || typeof node !== 'object') { + findings.push(finding('warning', 'bad_node', 'nodes[' + index + '] is not an object and was skipped.')) + continue + } + const id = Number(node.id) + if (!Number.isInteger(id)) { + findings.push(finding('warning', 'bad_node', 'nodes[' + index + '] has no integer id and was skipped.')) + continue + } + if (seen.has(id)) { + findings.push(finding('warning', 'duplicate_id', 'two nodes share id ' + id + '; the later one was skipped.')) + continue + } + seen.add(id) + normalized.push({ + id, + type: typeof node.type === 'string' ? node.type : '', + mode: Number.isInteger(node.mode) ? node.mode : MODE_ALWAYS, + title: typeof node.title === 'string' ? node.title : '', + inputs: Array.isArray(node.inputs) ? node.inputs : [], + outputs: Array.isArray(node.outputs) ? node.outputs : [], + widgetsValues: Array.isArray(node.widgets_values) ? node.widgets_values : [], + widgetsValuesIsObject: node.widgets_values !== null && typeof node.widgets_values === 'object' && !Array.isArray(node.widgets_values), + properties: node.properties !== null && typeof node.properties === 'object' ? node.properties : {}, + }) + } + return { nodes: normalized, links: links.map(normalizeLink).filter(Boolean), findings } +} + +/** One link, from either stored shape. */ +function normalizeLink(entry) { + if (Array.isArray(entry) && entry.length >= 5) { + return { id: Number(entry[0]), origin_id: Number(entry[1]), origin_slot: Number(entry[2]), target_id: Number(entry[3]), target_slot: Number(entry[4]), type: String(entry[5] ?? '') } + } + if (entry === null || typeof entry !== 'object') return null + return { + id: Number(entry.id), + origin_id: Number(entry.origin_id), + origin_slot: Number(entry.origin_slot), + target_id: Number(entry.target_id), + target_slot: Number(entry.target_slot), + type: typeof entry.type === 'string' ? entry.type : '', + } +} + +/** + * A UI workflow as an API prompt. + * + * The three frontend-only constructs are handled rather than tripped over: + * `Reroute` is followed through (it is a bend in a wire, not a node), + * `PrimitiveNode` supplies a literal to the widget it feeds, and a MUTED node + * (mode 2) is dropped. A BYPASSED node (mode 4) is refused by name, because + * bypass rewires the graph and silently dropping the node would run a + * different graph than the one on screen. + * + * @param workflow - a `parseWorkflow` result. + * @param catalog - a COMPLETE catalog. + * @returns `{ prompt, findings }` - feed `prompt` to `validatePrompt`. + * @throws ComfyError('SCHEMA_REQUIRED') without a complete catalog. + */ +export function workflowToPrompt(workflow, catalog) { + if (catalog === null || catalog.complete !== true) { + throw new ComfyError( + 'SCHEMA_REQUIRED', + 'Reading a UI workflow needs the FULL node catalog, and only a server (or its cache) has one: `widgets_values` is an unnamed array, so the class\'s input order is what turns it into names. Start ComfyUI, call `comfy_status` to find its address, then call this again. A prompt.json needs none of this - validate that instead.', + ) + } + const findings = [...workflow.findings] + const byId = new Map(workflow.nodes.map((node) => [node.id, node])) + const linksByTarget = new Map() + const linksById = new Map() + for (const link of workflow.links) { + linksById.set(link.id, link) + const list = linksByTarget.get(link.target_id) ?? [] + list.push(link) + linksByTarget.set(link.target_id, list) + } + + /** The node at the far end of a wire, following reroutes. */ + const originOf = (link) => { + let current = link + let guard = 0 + while (current !== undefined && guard < 64) { + guard += 1 + const node = byId.get(current.origin_id) + if (node === undefined) return null + if (node.type === 'Reroute') { + const incoming = (linksByTarget.get(node.id) ?? [])[0] + if (incoming === undefined) return null + current = incoming + continue + } + return { node, slot: current.origin_slot } + } + return null + } + + const prompt = {} + for (const node of workflow.nodes) { + if (VIRTUAL_CLASSES.has(node.type)) continue + if (node.mode === MODE_NEVER) { + findings.push(finding('warning', 'muted_node', 'node ' + node.id + ' (' + node.type + ') is muted, so it is not part of the prompt.')) + continue + } + if (node.mode === MODE_BYPASS) { + throw new ComfyError( + 'BYPASSED_NODE', + 'node ' + node.id + ' (' + node.type + ') is BYPASSED. Bypass rewires the graph through the node\'s matching input and output, and dropping the node instead would run a different graph than the one on screen. Un-bypass it in ComfyUI (Ctrl+B) and save again.', + ) + } + const spec = nodeIn(catalog, node.type) + if (spec === null) { + findings.push(finding('error', 'missing_node_type', 'node ' + node.id + ' is class "' + node.type + '", which this server does not have.', { node: String(node.id), class: node.type })) + continue + } + const inputs = {} + const links = linksByTarget.get(node.id) ?? [] + for (const link of links) { + const target = node.inputs[link.target_slot] + const name = target !== undefined && typeof target.name === 'string' ? target.name : '' + if (name === '') { + findings.push(finding('warning', 'bad_linked_input', 'node ' + node.id + ' has a link into slot ' + link.target_slot + ', which is not one of its inputs.')) + continue + } + const origin = originOf(link) + if (origin === null) { + findings.push(finding('error', 'bad_linked_input', 'node ' + node.id + ' input "' + name + '" wires from node ' + link.origin_id + ', which is not in this file.', { node: String(node.id), input: name })) + continue + } + if (origin.node.type === 'PrimitiveNode') { + // A primitive is a literal typed into a widget: no node, no wire. + const value = origin.node.widgetsValues.length > 0 ? origin.node.widgetsValues[0] : undefined + inputs[name] = value + continue + } + inputs[name] = [String(origin.node.id), origin.slot] + } + if (node.widgetsValuesIsObject) { + findings.push(finding('warning', 'widgets_values_object', 'node ' + node.id + ' (' + node.type + ') stores `widgets_values` as an object rather than an array. Only the wired inputs are read; set its widgets in ComfyUI and save again for a complete prompt.')) + } else { + const decoded = decodeWidgetValues(spec, node.widgetsValues, findings, node) + for (const [name, value] of Object.entries(decoded)) if (!(name in inputs)) inputs[name] = value + } + prompt[String(node.id)] = { + class_type: node.type, + inputs, + _meta: { title: node.title !== '' ? node.title : spec.displayName }, + } + } + return { prompt, findings } +} + +/** + * `widgets_values` as names. + * + * The order is the class's widget inputs, in declaration order, and the LENGTH + * is not the number of widgets: a widget input that declares + * `control_after_generate` carries a second value right after itself. The + * decode is positional, so a length mismatch is reported rather than guessed + * at - a shifted array is exactly the defect this feature would otherwise + * introduce. + */ +export function decodeWidgetValues(spec, values, findings = [], node = null) { + const widgets = spec.inputs.filter((input) => input.kind === 'widget') + const decoded = {} + let cursor = 0 + for (const input of widgets) { + if (cursor >= values.length) break + decoded[input.name] = values[cursor] + cursor += 1 + if (input.controlAfterGenerate && typeof values[cursor] === 'string' && ['fixed', 'increment', 'decrement', 'randomize'].includes(values[cursor])) cursor += 1 + } + if (cursor !== values.length && node !== null) { + findings.push( + finding( + 'warning', + 'widgets_values_length', + 'node ' + node.id + ' (' + spec.class + ') has ' + values.length + ' widget value(s) but its inputs account for ' + cursor + '. The values are matched in order, so anything after the mismatch is attributed by position.', + { node: String(node.id), class: spec.class }, + ), + ) + } + return decoded +} + +/** + * The files a finished prompt produced. + * + * `/history` stores them per node under a key that depends on the node + * (`images` for SaveImage, `audio` for SaveAudio, `video` for SaveVideo), so the + * shape is read generically: any array of `{ filename, subfolder, type }` is an + * artifact, whatever it is called. + */ +export function outputsOf(historyEntry) { + const outputs = historyEntry !== null && typeof historyEntry === 'object' && historyEntry.outputs !== null && typeof historyEntry.outputs === 'object' ? historyEntry.outputs : {} + const files = [] + for (const [nodeId, value] of Object.entries(outputs)) { + if (value === null || typeof value !== 'object') continue + for (const [key, list] of Object.entries(value)) { + if (!Array.isArray(list)) continue + for (const item of list) { + if (item === null || typeof item !== 'object') continue + if (typeof item.filename !== 'string') continue + files.push({ + node: nodeId, + key, + filename: item.filename, + subfolder: typeof item.subfolder === 'string' ? item.subfolder : '', + type: typeof item.type === 'string' ? item.type : 'output', + url: '/view?filename=' + encodeURIComponent(item.filename) + '&subfolder=' + encodeURIComponent(typeof item.subfolder === 'string' ? item.subfolder : '') + '&type=' + encodeURIComponent(typeof item.type === 'string' ? item.type : 'output'), + }) + } + } + } + return files +} + +/** The execution errors a `/history` entry recorded, as sentences. */ +export function errorsOf(historyEntry) { + const status = historyEntry !== null && typeof historyEntry === 'object' && historyEntry.status !== null && typeof historyEntry.status === 'object' ? historyEntry.status : {} + const messages = Array.isArray(status.messages) ? status.messages : [] + const found = [] + for (const message of messages) { + if (!Array.isArray(message) || message.length < 2) continue + const [event, data] = message + if (event !== 'execution_error' && event !== 'execution_interrupted') continue + const body = data !== null && typeof data === 'object' ? data : {} + found.push({ + event, + node: body.node_id === undefined ? '' : String(body.node_id), + nodeType: typeof body.node_type === 'string' ? body.node_type : '', + exceptionType: typeof body.exception_type === 'string' ? body.exception_type : '', + message: typeof body.exception_message === 'string' ? body.exception_message : '', + }) + } + return found +} + +/** Whether a `/prompt` response is the refusal `node_errors` describes. */ +export function errorSentenceFromResponse(body) { + if (body === null || typeof body !== 'object') return '' + const error = body.error + if (typeof error === 'string') return error + if (error !== null && typeof error === 'object') { + const message = typeof error.message === 'string' ? error.message : '' + const details = typeof error.details === 'string' ? error.details : '' + return (message + (details !== '' ? ' ' + details : '')).trim() + } + return '' +} + +/** Every `node_errors` entry as findings, for a failed `/prompt`. */ +export function findingsFromNodeErrors(nodeErrors) { + const findings = [] + if (nodeErrors === null || typeof nodeErrors !== 'object') return findings + for (const [nodeId, entry] of Object.entries(nodeErrors)) { + const errors = entry !== null && typeof entry === 'object' && Array.isArray(entry.errors) ? entry.errors : [] + const classType = entry !== null && typeof entry === 'object' && typeof entry.class_type === 'string' ? entry.class_type : '' + for (const error of errors) { + findings.push( + finding('error', typeof error.type === 'string' ? error.type : 'node_error', (typeof error.message === 'string' ? error.message : 'node error') + (typeof error.details === 'string' && error.details !== '' ? ': ' + error.details : ''), { + node: nodeId, + class: classType, + }), + ) + } + } + return findings +} + +/** Whether a class is one the frontend draws but the server never sees. */ +export function isVirtualClass(classType) { + return VIRTUAL_CLASSES.has(classType) +} diff --git a/packages/dsh-comfyui/lib/index.js b/packages/dsh-comfyui/lib/index.js new file mode 100644 index 0000000..c5b355f --- /dev/null +++ b/packages/dsh-comfyui/lib/index.js @@ -0,0 +1,219 @@ +/** + * dsh-comfyui — Node half. + * + * One row, seven tools, four bundled skills, no browser surface and no route. + * "Which node class does this graph name that the server does not have, and + * which widget value is not in its list" is a host question whose answer is a + * graph, a JSON file and prose - so there is nothing for the right bar to draw + * and nothing to serve, the same shape as `dsh-ollama` and `dsh-docker`. + * + * WHY IT EXISTS: ComfyUI is a graph editor, and a graph is a file with two + * dialects that are not interchangeable - the CANVAS the app saves (numeric ids, + * links as array positions, `widgets_values` as an UNNAMED positional array that + * shifts by one when a class declares `control_after_generate`) and the API + * PROMPT `/prompt` accepts (ids as keys, wires as `[id, slot]`). Nothing in the + * harness can turn one into the other, nothing can tell a reader "this class does + * not exist on this server", and nothing can say which of the two things a + * workflow does wrong: fail to open, or fail to run. This row answers those, and + * then runs the graph and reports what came out. + * + * WHAT IT IS NOT: not a UI for ComfyUI (the app is the UI), not a model + * downloader, not a node-package installer (both change a person's machine; the + * skills name the commands and the person decides), and not a second queue - + * `comfy_run` submits to the user's own server and waits for its own prompt. + * + * Zero npm dependencies, no engine bundled, no network egress of its own: the + * server is the user's own ComfyUI on loopback, and `comfy_cli` drives the + * user's own comfy-cli. + */ + +import { readFileSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +import { runProcess } from './cli.js' +import { resolveServers, DEFAULT_PORT, DESKTOP_PORTS, cacheRoot } from './client.js' +import { buildTools } from './tools.js' + +export const name = 'dsh-comfyui' +export const inject = ['tools'] + +/** Kept in step with package.json by the package's own check. */ +export const PLUGIN_VERSION = '0.1.0-alpha.1' + +/** The six skills, as files beside this module. */ +export const SKILL_FILES = [ + { name: 'comfyui-fundamentals', file: '../skills/comfyui-fundamentals/SKILL.md' }, + { name: 'comfyui-workflow-json', file: '../skills/comfyui-workflow-json/SKILL.md' }, + { name: 'comfyui-api', file: '../skills/comfyui-api/SKILL.md' }, + { name: 'comfyui-cli', file: '../skills/comfyui-cli/SKILL.md' }, + { name: 'comfyui-node-class', file: '../skills/comfyui-node-class/SKILL.md' }, + { name: 'comfyui-projects', file: '../skills/comfyui-projects/SKILL.md' }, +] + +/** What this row offers, for the README and the package check. */ +export const CAPABILITIES = { + tools: ['comfy_status', 'comfy_nodes', 'comfy_project', 'comfy_validate', 'comfy_run', 'comfy_test', 'comfy_cli'], + endpoints: ['/system_stats', '/object_info', '/object_info/{class}', '/prompt', '/history', '/history/{prompt_id}', '/queue', '/view', '/models', '/models/{folder}', '/upload/image', '/embeddings', '/features', '/api/jobs'], + skills: SKILL_FILES.map((entry) => entry.name), + rungs: ['v1-structural', 'v2-schema', 'v3-queued', 'v4-executed'], + examples: ['smoke-image', 'smoke-video', 'text-to-image', 'image-to-image'], + projectFiles: ['project.json', 'workflow.json', 'prompt.json', 'README.md', 'build.json'], + notBuilt: [ + 'a ComfyUI UI of its own', + 'installing ComfyUI, a custom node pack or a model', + 'starting a server except through comfy-cli (`comfy launch --background`)', + 'the WebSocket feed (this row polls /history)', + 'remote servers unless DSH_COMFYUI_ALLOW_REMOTE=1', + 'lowering a subgraph export (it names the ungroup step instead)', + ], +} + +/** + * The row's shared dependencies, one per boot. + * + * `fetch`, `now`, `sleep` and `runner` are injectable so the package check can + * drive every branch without a server and without a CLI: a fake ComfyUI answers + * the routes, and a fake runner answers `comfy --version`. + * + * @param ctx - the plugin context (inject: tools). + * @param options - `{ env, fetch, now, sleep, runner, platform }`. + */ +export function createDeps(ctx, options = {}) { + return { + ctx, + env: options.env ?? process.env, + fetch: options.fetch ?? globalThis.fetch, + now: options.now ?? (() => performance.now()), + sleep: options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))), + runner: options.runner ?? runProcess, + platform: options.platform ?? process.platform, + log: { + warn: (text) => ctx.logger?.warn?.('[dsh-comfyui] ' + text), + info: (text) => ctx.logger?.info?.('[dsh-comfyui] ' + text), + }, + } +} + +/** + * The one activation line. + * + * It does NOT probe a server: a request per harness start is a request nobody + * asked for, and a machine whose ComfyUI is closed would print the same happy + * line either way. `comfy_status` is the tool that asks. + * + * @param deps - the row's dependencies. + */ +export function activationLine(deps) { + const servers = resolveServers(deps.env) + if (!servers.allowed) return 'inert: ' + servers.reason + const where = servers.explicit ? servers.origins[0] : '127.0.0.1:' + DEFAULT_PORT + ' and the Desktop ports ' + DESKTOP_PORTS.join('/') + return ( + 'active: seven comfy_* tools over ' + + where + + (servers.remote ? ' (allowed by DSH_COMFYUI_ALLOW_REMOTE=1 - not this machine)' : ' (this machine)') + + '; nothing is started - ask `comfy_status` whether a server answers, and `comfy_project` action=new writes a project with or without one' + ) +} + +// --------------------------------------------------------------------------- +// Skills +// --------------------------------------------------------------------------- +/** + * Split one skill document into its frontmatter and its body. + * + * @param text - the file's contents. + * @returns `{ meta, content }`. + */ +export function parseSkillFile(text) { + const normalized = String(text).replace(/\r\n?/g, '\n') + const match = /^---\n([\s\S]*?)\n---\n?/.exec(normalized) + if (!match) return { meta: {}, content: normalized.trim() } + const meta = {} + for (const line of match[1].split('\n')) { + const entry = /^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/.exec(line) + if (!entry) continue + let value = entry[2].trim() + if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) value = value.slice(1, -1) + meta[entry[1]] = value + } + return { meta: meta, content: normalized.slice(match[0].length).trim() } +} + +/** + * Register the bundled skills. The registry is resolved lazily (its absence only + * skips the skills, never the tools) and both installers also copy the folders + * into `$DSH_HOME/skills`, so a host without the registry still gets them from + * the filesystem provider. + * + * @returns the number of skills registered. + */ +export function registerSkills(ctx, log) { + const skills = typeof ctx.get === 'function' ? ctx.get('skills') : undefined + if (skills === null || skills === undefined || typeof skills.register !== 'function') { + log.warn('skill registry unavailable - the six bundled ComfyUI skills were not registered (the installers copy them into $DSH_HOME/skills)') + return 0 + } + let count = 0 + for (const entry of SKILL_FILES) { + try { + const file = fileURLToPath(new URL(entry.file, import.meta.url)) + const { meta, content } = parseSkillFile(readFileSync(file, 'utf8')) + if (content.length === 0) { + log.warn('skill file is empty: ' + entry.file) + continue + } + const skillName = typeof meta.name === 'string' && meta.name.length > 0 ? meta.name : entry.name + ctx.effect( + () => + skills.register({ + name: skillName, + description: typeof meta.description === 'string' ? meta.description : '', + whenToUse: typeof meta.whenToUse === 'string' ? meta.whenToUse : undefined, + content, + provider: 'dsh-comfyui', + source: 'bundled', + path: file, + resourceBase: { kind: 'directory', path: path.dirname(file) }, + }), + 'dsh-comfyui: skill ' + skillName, + ) + count += 1 + } catch (err) { + log.warn('could not register skill ' + entry.name + ': ' + (err && err.message ? err.message : String(err))) + } + } + return count +} + +// --------------------------------------------------------------------------- +// Activation +// --------------------------------------------------------------------------- +/** + * Activate the row. + * + * @param ctx - cordis context (inject: tools). + */ +export function apply(ctx) { + const deps = createDeps(ctx) + deps.log.info(activationLine(deps)) + const skillCount = registerSkills(ctx, deps.log) + deps.log.info('registered ' + skillCount + ' bundled skill(s)') + for (const tool of buildTools(deps)) { + ctx.effect(() => ctx.tools.register(tool), 'dsh-comfyui: tool ' + tool.name) + } +} + +/** Exported for the package's check: the parts of this row worth driving directly. */ +export const __internals = { + buildTools, + createDeps, + registerSkills, + parseSkillFile, + activationLine, + resolveServers, + cacheRoot, + CAPABILITIES, + PLUGIN_VERSION, + SKILL_FILES, +} diff --git a/packages/dsh-comfyui/lib/nodes.js b/packages/dsh-comfyui/lib/nodes.js new file mode 100644 index 0000000..b2df11c --- /dev/null +++ b/packages/dsh-comfyui/lib/nodes.js @@ -0,0 +1,500 @@ +/** + * dsh-comfyui — the node catalog, and the small built-in table that lets a + * project compile on a machine with no server running. + * + * WHAT A CATALOG IS: `/object_info` is the only authority on what a node class + * accepts, what it returns and which of its inputs are WIDGETS (a value typed + * into the node) rather than LINKS (a wire from another node's output). That + * distinction is what turns a readable spec into a workflow the app can open + * and a prompt the server will accept, so it is not a nicety - it is the + * compiler's input. + * + * The response has TWO shapes in one document, and this module flattens both: + * + * - a classic node (`class X: INPUT_TYPES()`), where an input is + * `[type, options]` and `type` is a string, or a LIST of strings (a combo + * whose options are files on this machine); + * - a V3 node (`IO.ComfyNode.define_schema`), whose `/object_info` is + * `GET_NODE_INFO_V1()` - the same `[type, options]` tuple, with combos + * typed `"COMBO"` and their options under `options`. + * + * Measured on ComfyUI 0.21.1 (ComfyUI Desktop 2): `RepeatImageBatch` answers + * through the V3 path, `KSampler` and `LoadImage` through the classic one, and + * `CLIPTextEncode` mixes the two (its `text` input is declared `IO.STRING`). + * A parser that handled only one shape would misread half the catalog. + * + * WHY A TABLE EXISTS AT ALL: a class list is version-specific, so a snapshot + * shipped in a package would be worse than none - but the eighteen core nodes + * the shipped examples use are stable enough to declare, and with them + * `comfy_test` compiles the whole library on a laptop where ComfyUI is not + * running. The table NEVER overrules a server: a live catalog replaces it + * wholesale, and a project built against the table is reported as + * `widgetOrder: "core-table"` so a reader knows what was verified. + */ + +/** The catalog sources, best first. */ +export const SOURCES = { server: 'server', cache: 'cache', core: 'core-table' } + +/** Inputs whose options are files on THIS machine - no snapshot can know them. */ +export const FILE_INPUTS = { + ckpt_name: 'checkpoints', + lora_name: 'loras', + vae_name: 'vae', + unet_name: 'diffusion_models', + clip_name: 'text_encoders', + clip_name1: 'text_encoders', + clip_name2: 'text_encoders', + clip_name3: 'text_encoders', + control_net_name: 'controlnet', + upscale_model_name: 'upscale_models', + style_model_name: 'style_models', + image: 'input', + model: 'diffusion_models', +} + +/** + * The core port table. + * + * eighteen nodes, each entry transcribed from the installed 0.21.1 source + * (`nodes.py`, `comfy_extras/nodes_audio.py`, `nodes_video.py`, `nodes_images.py`) + * and asserted by the package check against a fixture of the real `/object_info` + * shapes. `kind` is what the compiler needs: `widget` values go in + * `widgets_values` AND in the API prompt's `inputs`, `link` values only ever + * carry a wire, and `hidden` values are supplied by the server (`prompt`, + * `extra_pnginfo`) so they must never appear in either. + */ +export const CORE_NODES = { + CheckpointLoaderSimple: { + displayName: 'Load Checkpoint', + category: 'loaders', + outputs: ['MODEL', 'CLIP', 'VAE'], + inputs: [{ name: 'ckpt_name', type: 'COMBO', kind: 'widget', fileFolder: 'checkpoints' }], + }, + LoraLoader: { + displayName: 'Load LoRA', + category: 'loaders', + outputs: ['MODEL', 'CLIP'], + inputs: [ + { name: 'model', type: 'MODEL', kind: 'link' }, + { name: 'clip', type: 'CLIP', kind: 'link' }, + { name: 'lora_name', type: 'COMBO', kind: 'widget', fileFolder: 'loras' }, + { name: 'strength_model', type: 'FLOAT', kind: 'widget', options: { default: 1, min: -100, max: 100, step: 0.01 } }, + { name: 'strength_clip', type: 'FLOAT', kind: 'widget', options: { default: 1, min: -100, max: 100, step: 0.01 } }, + ], + }, + CLIPTextEncode: { + displayName: 'CLIP Text Encode (Prompt)', + category: 'conditioning', + outputs: ['CONDITIONING'], + inputs: [ + { name: 'text', type: 'STRING', kind: 'widget', options: { default: '', multiline: true } }, + { name: 'clip', type: 'CLIP', kind: 'link' }, + ], + }, + EmptyLatentImage: { + displayName: 'Empty Latent Image', + category: 'latent', + outputs: ['LATENT'], + inputs: [ + { name: 'width', type: 'INT', kind: 'widget', options: { default: 512, min: 16, max: 16384, step: 8 } }, + { name: 'height', type: 'INT', kind: 'widget', options: { default: 512, min: 16, max: 16384, step: 8 } }, + { name: 'batch_size', type: 'INT', kind: 'widget', options: { default: 1, min: 1, max: 4096 } }, + ], + }, + KSampler: { + displayName: 'KSampler', + category: 'sampling', + outputs: ['LATENT'], + inputs: [ + { name: 'model', type: 'MODEL', kind: 'link' }, + { name: 'seed', type: 'INT', kind: 'widget', controlAfterGenerate: true, options: { default: 0, min: 0, max: 18446744073709551615 } }, + { name: 'steps', type: 'INT', kind: 'widget', options: { default: 20, min: 1, max: 10000 } }, + { name: 'cfg', type: 'FLOAT', kind: 'widget', options: { default: 8, min: 0, max: 100, step: 0.1 } }, + { name: 'sampler_name', type: 'COMBO', kind: 'widget' }, + { name: 'scheduler', type: 'COMBO', kind: 'widget' }, + { name: 'positive', type: 'CONDITIONING', kind: 'link' }, + { name: 'negative', type: 'CONDITIONING', kind: 'link' }, + { name: 'latent_image', type: 'LATENT', kind: 'link' }, + { name: 'denoise', type: 'FLOAT', kind: 'widget', options: { default: 1, min: 0, max: 1, step: 0.01 } }, + ], + }, + VAEDecode: { + displayName: 'VAE Decode', + category: 'latent', + outputs: ['IMAGE'], + inputs: [ + { name: 'samples', type: 'LATENT', kind: 'link' }, + { name: 'vae', type: 'VAE', kind: 'link' }, + ], + }, + VAEEncode: { + displayName: 'VAE Encode', + category: 'latent', + outputs: ['LATENT'], + inputs: [ + { name: 'pixels', type: 'IMAGE', kind: 'link' }, + { name: 'vae', type: 'VAE', kind: 'link' }, + ], + }, + SaveImage: { + displayName: 'Save Image', + category: 'image', + outputNode: true, + outputs: [], + inputs: [ + { name: 'images', type: 'IMAGE', kind: 'link' }, + { name: 'filename_prefix', type: 'STRING', kind: 'widget', options: { default: 'ComfyUI' } }, + { name: 'prompt', type: 'PROMPT', kind: 'hidden' }, + { name: 'extra_pnginfo', type: 'EXTRA_PNGINFO', kind: 'hidden' }, + ], + }, + PreviewImage: { + displayName: 'Preview Image', + category: 'image', + outputNode: true, + outputs: [], + inputs: [{ name: 'images', type: 'IMAGE', kind: 'link' }], + }, + LoadImage: { + displayName: 'Load Image', + category: 'image', + outputs: ['IMAGE', 'MASK'], + inputs: [{ name: 'image', type: 'COMBO', kind: 'widget', fileFolder: 'input', options: { imageUpload: true } }], + }, + ImageScale: { + displayName: 'Upscale Image', + category: 'image/upscaling', + outputs: ['IMAGE'], + inputs: [ + { name: 'image', type: 'IMAGE', kind: 'link' }, + { name: 'upscale_method', type: 'COMBO', kind: 'widget', enum: ['nearest-exact', 'bilinear', 'area', 'bicubic', 'lanczos'] }, + { name: 'width', type: 'INT', kind: 'widget', options: { default: 512, min: 0, max: 16384, step: 1 } }, + { name: 'height', type: 'INT', kind: 'widget', options: { default: 512, min: 0, max: 16384, step: 1 } }, + { name: 'crop', type: 'COMBO', kind: 'widget', enum: ['disabled', 'center'] }, + ], + }, + EmptyImage: { + displayName: 'Empty Image', + category: 'image', + outputs: ['IMAGE'], + inputs: [ + { name: 'width', type: 'INT', kind: 'widget', options: { default: 512, min: 1, max: 16384, step: 1 } }, + { name: 'height', type: 'INT', kind: 'widget', options: { default: 512, min: 1, max: 16384, step: 1 } }, + { name: 'batch_size', type: 'INT', kind: 'widget', options: { default: 1, min: 1, max: 4096 } }, + { name: 'color', type: 'INT', kind: 'widget', options: { default: 0, min: 0, max: 16777215, step: 1, display: 'color' } }, + ], + }, + RepeatImageBatch: { + displayName: 'Repeat Image Batch', + category: 'image/batch', + outputs: ['IMAGE'], + inputs: [ + { name: 'image', type: 'IMAGE', kind: 'link' }, + { name: 'amount', type: 'INT', kind: 'widget', options: { default: 1, min: 1, max: 4096 } }, + ], + }, + CreateVideo: { + displayName: 'Create Video', + category: 'video', + outputs: ['VIDEO'], + inputs: [ + { name: 'images', type: 'IMAGE', kind: 'link' }, + { name: 'fps', type: 'FLOAT', kind: 'widget', options: { default: 30, min: 1, max: 120, step: 1 } }, + { name: 'audio', type: 'AUDIO', kind: 'link', optional: true }, + ], + }, + SaveVideo: { + displayName: 'Save Video', + category: 'video', + outputNode: true, + outputs: [], + inputs: [ + { name: 'video', type: 'VIDEO', kind: 'link' }, + { name: 'filename_prefix', type: 'STRING', kind: 'widget', options: { default: 'video/ComfyUI' } }, + { name: 'format', type: 'COMBO', kind: 'widget', options: { default: 'auto' } }, + { name: 'codec', type: 'COMBO', kind: 'widget', options: { default: 'auto' } }, + { name: 'prompt', type: 'PROMPT', kind: 'hidden' }, + { name: 'extra_pnginfo', type: 'EXTRA_PNGINFO', kind: 'hidden' }, + ], + }, + EmptyLatentAudio: { + displayName: 'Empty Latent Audio', + category: 'latent/audio', + outputs: ['LATENT'], + inputs: [ + { name: 'seconds', type: 'FLOAT', kind: 'widget', options: { default: 47.6, min: 1, max: 1000, step: 0.1 } }, + { name: 'batch_size', type: 'INT', kind: 'widget', options: { default: 1, min: 1, max: 4096 } }, + ], + }, + VAEDecodeAudio: { + displayName: 'VAE Decode Audio', + category: 'latent/audio', + outputs: ['AUDIO'], + inputs: [ + { name: 'samples', type: 'LATENT', kind: 'link' }, + { name: 'vae', type: 'VAE', kind: 'link' }, + ], + }, + SaveAudio: { + displayName: 'Save Audio (FLAC)', + category: 'audio', + outputNode: true, + outputs: [], + inputs: [ + { name: 'audio', type: 'AUDIO', kind: 'link' }, + { name: 'filename_prefix', type: 'STRING', kind: 'widget', options: { default: 'audio/ComfyUI' } }, + { name: 'prompt', type: 'PROMPT', kind: 'hidden' }, + { name: 'extra_pnginfo', type: 'EXTRA_PNGINFO', kind: 'hidden' }, + ], + }, +} + +/** A widget's value type, from the declared type string. */ +export function widgetKind(type) { + if (type === 'INT' || type === 'FLOAT' || type === 'STRING' || type === 'BOOLEAN') return type + return null +} + +/** Whether a declared type is a link type (no widget of its own). */ +export function isLinkType(type) { + return !(type === 'COMBO' || widgetKind(type) !== null) +} + +/** + * One catalog entry from the core table. + * + * @param classType - the class name. + * @param entry - a `CORE_NODES` value. + * @returns a normalized `NodeSpec`. + */ +export function nodeFromTable(classType, entry) { + return { + class: classType, + displayName: entry.displayName ?? classType, + category: entry.category ?? '', + description: entry.description ?? '', + outputNode: entry.outputNode === true, + deprecated: false, + experimental: false, + pythonModule: 'nodes', + inputs: entry.inputs.map((input) => ({ + name: input.name, + type: input.type, + kind: input.kind, + optional: input.optional === true, + enum: Array.isArray(input.enum) ? input.enum.slice() : null, + options: input.options ?? {}, + controlAfterGenerate: input.controlAfterGenerate === true, + fileFolder: input.fileFolder ?? FILE_INPUTS[input.name] ?? null, + })), + outputs: entry.outputs.map((type) => ({ name: type, type })), + source: SOURCES.core, + } +} + +/** The catalog a machine with no server and no cache can still compile against. */ +export function coreCatalog() { + const nodes = new Map() + for (const [classType, entry] of Object.entries(CORE_NODES)) nodes.set(classType, nodeFromTable(classType, entry)) + return { + source: SOURCES.core, + origin: '', + version: '', + fetchedAt: '', + complete: false, + nodes, + note: 'the built-in core table (' + nodes.size + ' nodes the shipped examples use); a live server replaces it whole', + } +} + +/** + * One `/object_info` entry, flattened. + * + * @param classType - the key the server used. + * @param info - that key's value. + * @returns a `NodeSpec`, or null when the entry is not shaped like one. + */ +export function parseNodeInfo(classType, info) { + if (info === null || typeof info !== 'object') return null + const declared = info.input !== null && typeof info.input === 'object' ? info.input : {} + const order = info.input_order !== null && typeof info.input_order === 'object' ? info.input_order : {} + const inputs = [] + for (const section of ['required', 'optional']) { + const group = declared[section] + if (group === null || typeof group !== 'object') continue + const names = Array.isArray(order[section]) ? order[section] : Object.keys(group) + for (const name of names) { + if (!(name in group)) continue + const input = parseInputEntry(name, group[name], section === 'optional') + if (input !== null) inputs.push(input) + } + } + const hidden = declared.hidden + if (hidden !== null && typeof hidden === 'object') { + for (const name of Object.keys(hidden)) inputs.push({ name, type: 'HIDDEN', kind: 'hidden', optional: true, enum: null, options: {}, controlAfterGenerate: false, fileFolder: null }) + } + const types = Array.isArray(info.output) ? info.output : [] + const names = Array.isArray(info.output_name) && info.output_name.length === types.length ? info.output_name : types + return { + class: classType, + displayName: typeof info.display_name === 'string' && info.display_name !== '' ? info.display_name : classType, + category: typeof info.category === 'string' ? info.category : '', + description: typeof info.description === 'string' ? info.description : '', + outputNode: info.output_node === true, + deprecated: info.deprecated === true, + experimental: info.experimental === true, + pythonModule: typeof info.python_module === 'string' ? info.python_module : '', + inputs, + outputs: types.map((type, index) => ({ name: String(names[index] ?? type), type: String(type) })), + source: SOURCES.server, + } +} + +/** + * One input of an `/object_info` entry: `[type, options]`, in either shape. + * + * A type that is an ARRAY is a combo whose options are that array; the string + * `"COMBO"` is the V3 spelling of the same thing with the options in + * `options.options`. `forceInput` turns a widget into a link-only input, which + * is the difference between a value written into `widgets_values` and a wire. + */ +function parseInputEntry(name, raw, optional) { + let type = raw + let options = {} + if (Array.isArray(raw)) { + type = raw[0] + if (raw[1] !== null && typeof raw[1] === 'object') options = raw[1] + } + let enumValues = null + let declaredType = type + if (Array.isArray(type)) { + enumValues = type.map((value) => String(value)) + declaredType = 'COMBO' + } else if (type === 'COMBO') { + enumValues = Array.isArray(options.options) ? options.options.map((value) => String(value)) : null + } else if (typeof type !== 'string') { + return null + } + const forceInput = options.forceInput === true + // `"COMBO"` is a widget even when this build of the server put no option list + // in the entry (the core table has none offline): a combo with unknown options + // is a dropdown nobody can check, not a wire. + const kind = forceInput ? 'link' : enumValues !== null || declaredType === 'COMBO' || widgetKind(declaredType) !== null ? 'widget' : 'link' + return { + name, + type: declaredType, + kind, + optional: optional === true || options.optional === true, + enum: enumValues, + options, + controlAfterGenerate: options.control_after_generate === true, + fileFolder: FILE_INPUTS[name] ?? null, + } +} + +/** + * A whole `/object_info` response as a catalog. + * + * @param raw - the parsed response body. + * @param meta - `{ origin, version, fetchedAt }`. + */ +export function catalogFromObjectInfo(raw, meta = {}) { + const nodes = new Map() + let skipped = 0 + for (const [classType, info] of Object.entries(raw)) { + const parsed = parseNodeInfo(classType, info) + if (parsed === null) { + skipped += 1 + continue + } + nodes.set(classType, parsed) + } + return { + source: SOURCES.server, + origin: typeof meta.origin === 'string' ? meta.origin : '', + version: typeof meta.version === 'string' ? meta.version : '', + fetchedAt: typeof meta.fetchedAt === 'string' ? meta.fetchedAt : '', + complete: true, + nodes, + note: skipped === 0 ? '' : skipped + ' /object_info entr(ies) were not shaped like a node and were skipped', + } +} + +/** The one node class, from any catalog. */ +export function nodeIn(catalog, classType) { + if (catalog === null || catalog === undefined) return null + return catalog.nodes.get(classType) ?? null +} + +/** Whether a catalog can speak about a class at all. */ +export function knows(catalog, classType) { + return nodeIn(catalog, classType) !== null +} + +/** Every class name, sorted. */ +export function classesIn(catalog) { + return [...catalog.nodes.keys()].sort() +} + +/** The classes grouped by their `category`, sorted, with counts. */ +export function categoriesIn(catalog) { + const groups = new Map() + for (const node of catalog.nodes.values()) { + const key = node.category === '' ? '(uncategorised)' : node.category + const list = groups.get(key) ?? [] + list.push(node.class) + groups.set(key, list) + } + return [...groups.entries()] + .map(([category, classes]) => ({ category, count: classes.length, classes: classes.sort() })) + .sort((left, right) => left.category.localeCompare(right.category)) +} + +/** + * A search over the catalog: class, display name, category and description. + * + * Ranking is "class matches first, then the others", so a query for "KSampler" + * does not put fifty conditioning nodes above the node that is literally named + * that. + */ +export function searchCatalog(catalog, query, limit = 40) { + const needle = String(query).toLowerCase().trim() + if (needle === '') return [] + const scored = [] + for (const node of catalog.nodes.values()) { + let score = 0 + if (node.class.toLowerCase() === needle) score = 100 + else if (node.class.toLowerCase().startsWith(needle)) score = 80 + else if (node.class.toLowerCase().includes(needle)) score = 60 + else if (node.displayName.toLowerCase().includes(needle)) score = 40 + else if (node.category.toLowerCase().includes(needle)) score = 20 + else if (node.description.toLowerCase().includes(needle)) score = 10 + if (score > 0) scored.push({ node, score }) + } + return scored + .sort((left, right) => right.score - left.score || left.node.class.localeCompare(right.node.class)) + .slice(0, limit) + .map((entry) => entry.node) +} + +/** The widget inputs of a node, in the order the frontend lays them out. */ +export function widgetInputs(node) { + return node.inputs.filter((input) => input.kind === 'widget') +} + +/** The link inputs of a node (what a wire may target). */ +export function linkInputs(node) { + return node.inputs.filter((input) => input.kind === 'link') +} + +/** The outputs of a node, as `name -> slot index` plus the slot table. */ +export function outputSlot(node, nameOrIndex) { + if (typeof nameOrIndex === 'number') { + return Number.isInteger(nameOrIndex) && nameOrIndex >= 0 && nameOrIndex < node.outputs.length ? nameOrIndex : -1 + } + const wanted = String(nameOrIndex) + const exact = node.outputs.findIndex((output) => output.name === wanted) + if (exact !== -1) return exact + const insensitive = node.outputs.findIndex((output) => output.name.toLowerCase() === wanted.toLowerCase()) + return insensitive +} diff --git a/packages/dsh-comfyui/lib/projects.js b/packages/dsh-comfyui/lib/projects.js new file mode 100644 index 0000000..613b115 --- /dev/null +++ b/packages/dsh-comfyui/lib/projects.js @@ -0,0 +1,568 @@ +/** + * dsh-comfyui — a project on disk, and the build that turns it into files + * ComfyUI consumes. + * + * A PROJECT IS A FOLDER. `project.json` is the source of truth and is the only + * file a person edits; `workflow.json`, `prompt.json`, `README.md` and + * `build.json` are GENERATED and say so at the top. That split is the whole + * point: a generated canvas is not hand-editable (its `widgets_values` is an + * unnamed positional array), so keeping it as the source would mean every edit + * is a counting exercise - while keeping the spec as the source means the + * canvas can always be regenerated from something readable. + * + * `build.json` is the receipt: which spec bytes were compiled, against WHICH + * catalog, when, with which findings, and which rung of the ladder was reached. + * A question about a workflow somebody was handed is answerable from the + * folder, the same way `dsh-research`'s build record answers it for a document. + * + * TWO DIALECTS, because a person has two ways in: + * - spec-driven: `project.json` holds `nodes`, `bindings`, `requires`, and + * every build rewrites the canvas; + * - workflow-driven: `comfy_project` action=import copied a workflow the app + * saved, `project.json` records `source: "workflow"`, and a build derives + * `prompt.json` from `workflow.json` WITHOUT touching the canvas - the file + * the app wrote stays the file the app reads. + */ + +import { createHash } from 'node:crypto' +import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs' +import path from 'node:path' + +import { ComfyError } from './errors.js' +import { compileProject, describeCatalog } from './compile.js' +import { outputsOf, parseWorkflow, validatePrompt, workflowToPrompt } from './graph.js' +import { checkPromptFiles } from './files.js' +import { readSpec, slugify, summarizeFindings } from './spec.js' + +/** The environment variable that moves where projects live. */ +export const ROOT_ENV = 'DSH_COMFYUI_ROOT' + +/** The ladder, in order. Every answer names the rung it reached, never more. */ +export const RUNGS = ['v1-structural', 'v2-schema', 'v3-queued', 'v4-executed'] + +/** The file names every project folder uses. */ +export const FILES = { spec: 'project.json', workflow: 'workflow.json', prompt: 'prompt.json', readme: 'README.md', build: 'build.json' } + +/** The schema of `build.json`; a reader can tell an old receipt from a new one. */ +export const BUILD_SCHEMA = 1 + +/** Where projects live: the workspace by default, so the agent can edit them. */ +export function projectsRoot(env = process.env, cwd = process.cwd()) { + const fromEnv = env[ROOT_ENV] + if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return path.resolve(cwd || process.cwd(), fromEnv.trim()) + return path.join(cwd || process.cwd(), 'comfyui') +} + +/** One project's folder. */ +export function projectDir(root, slug) { + return path.join(root, slug) +} + +/** The five paths of one project. */ +export function projectPaths(root, slug) { + const dir = projectDir(root, slug) + return { + dir, + spec: path.join(dir, FILES.spec), + workflow: path.join(dir, FILES.workflow), + prompt: path.join(dir, FILES.prompt), + readme: path.join(dir, FILES.readme), + build: path.join(dir, FILES.build), + } +} + +/** A JSON file, or null when it is absent or unreadable. */ +export function readJson(file) { + if (!existsSync(file)) return null + try { + return JSON.parse(readFileSync(file, 'utf8')) + } catch (error) { + throw new ComfyError('BAD_JSON', file + ' is not readable JSON: ' + error.message, { path: file }) + } +} + +/** Write a JSON file through a temporary name, so a reader never sees half of one. */ +export function writeJson(file, value) { + mkdirSync(path.dirname(file), { recursive: true }) + const temporary = file + '.' + process.pid + '.tmp' + writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', 'utf8') + renameSync(temporary, file) + return file +} + +/** Write a text file the same way. */ +export function writeText(file, text) { + mkdirSync(path.dirname(file), { recursive: true }) + const temporary = file + '.' + process.pid + '.tmp' + writeFileSync(temporary, text, 'utf8') + renameSync(temporary, file) + return file +} + +/** The sha256 of a buffer, as the build receipt records it. */ +export function sha256(text) { + return createHash('sha256').update(text, 'utf8').digest('hex') +} + +/** + * Every project in a root, newest build first. + * + * A folder with no `project.json` is not a project and is skipped silently: a + * person's `comfyui/` folder may hold output images too. + */ +export function listProjects(root) { + if (!existsSync(root)) return [] + const found = [] + for (const entry of readdirSync(root, { withFileTypes: true })) { + if (!entry.isDirectory()) continue + const paths = projectPaths(root, entry.name) + if (!existsSync(paths.spec)) continue + let manifest = null + let error = '' + try { + manifest = readJson(paths.spec) + } catch (err) { + error = err.message + } + const build = existsSync(paths.build) ? readJson(paths.build) : null + found.push({ + slug: entry.name, + title: manifest !== null && typeof manifest.title === 'string' && manifest.title !== '' ? manifest.title : entry.name, + source: manifest !== null && typeof manifest.source === 'string' ? manifest.source : 'spec', + nodes: manifest !== null && Array.isArray(manifest.nodes) ? manifest.nodes.length : 0, + built: existsSync(paths.prompt) && existsSync(paths.workflow), + build: build === null + ? null + : { + at: typeof build.builtAt === 'string' ? build.builtAt : '', + ok: build.ok === true, + rung: typeof build.rung === 'string' ? build.rung : '', + errors: build.counts !== null && typeof build.counts === 'object' ? build.counts.errors : null, + }, + error, + }) + } + return found.sort((left, right) => { + const leftAt = left.build === null ? '' : left.build.at + const rightAt = right.build === null ? '' : right.build.at + if (leftAt !== rightAt) return String(rightAt).localeCompare(String(leftAt)) + return left.slug.localeCompare(right.slug) + }) +} + +/** + * The rung a compile-only pass reached. + * + * It is the ONLY honest answer to "did it work": without a server a graph can + * be structurally sound and still name a checkpoint that is not on this + * machine, and the two are not the same claim. + */ +export function compileRung(findings, catalog) { + const errors = findings.filter((entry) => entry.severity === 'error').length + if (errors > 0) return 'v0-failed' + return catalog !== null && catalog.complete === true ? 'v2-schema' : 'v1-structural' +} + +/** + * Compile one spec-driven project and write its four generated files. + * + * @param options - `{ root, slug, catalog, controlAfterGenerate, now, dryRun }`. + * @returns a report: `{ ok, rung, findings, files, prompt, workflow, counts, catalog }`. + */ +export function buildProject(options) { + const paths = projectPaths(options.root, options.slug) + const raw = readJson(paths.spec) + if (raw === null) throw new ComfyError('NO_PROJECT', 'no ' + FILES.spec + ' in ' + paths.dir + '. `comfy_project` action=new writes one.', { path: paths.dir }) + return buildFromSpec({ raw, paths, catalog: options.catalog, controlAfterGenerate: options.controlAfterGenerate, now: options.now, dryRun: options.dryRun === true }) +} + +/** The spec-driven half of `buildProject`, split out so the check can drive it. */ +export function buildFromSpec({ raw, paths, catalog, controlAfterGenerate, now, dryRun, install }) { + const specText = JSON.stringify(raw ?? {}, null, 2) + if (raw !== null && typeof raw === 'object' && raw.source === 'workflow') { + return buildFromWorkflowFile({ raw, paths, catalog, now, dryRun, install }) + } + if (raw !== null && typeof raw === 'object' && raw.source === 'prompt') { + return buildFromPromptFile({ raw, paths, catalog, now, dryRun, install }) + } + const { project, findings } = readSpec(raw, catalog) + const compiled = compileProject(project, catalog, { controlAfterGenerate }) + findings.push(...compiled.findings) + const validated = validatePrompt(compiled.prompt, catalog) + findings.push(...validated.findings) + // The install's own files: the check nobody else could make without a server. + // It runs on the COMPILED prompt, where `@bindings` are already filenames. + const files = checkPromptFiles({ prompt: compiled.prompt, catalog, install, requires: project.requires }) + findings.push(...files.findings) + const errors = findings.filter((entry) => entry.severity === 'error') + const rung = compileRung(findings, catalog) + const report = { + ok: errors.length === 0, + rung, + findings, + prompt: compiled.prompt, + workflow: compiled.workflow, + widgetOrder: compiled.widgetOrder, + files: {}, + fileCheck: { checked: files.checked.length, missing: files.missing, roots: files.roots, skipped: files.skipped }, + counts: { nodes: project.nodes.length, links: compiled.workflow.links.length, errors: errors.length, warnings: findings.filter((entry) => entry.severity === 'warning').length }, + catalog: { source: catalog.source, version: catalog.version, origin: catalog.origin, complete: catalog.complete === true, described: describeCatalog(catalog) }, + } + if (dryRun === true) return report + const builtAt = typeof now === 'function' ? now() : new Date().toISOString() + report.files.workflow = writeJson(paths.workflow, compiled.workflow) + report.files.prompt = writeJson(paths.prompt, compiled.prompt) + report.files.build = writeJson(paths.build, { + schema: BUILD_SCHEMA, + project: project.name, + source: 'spec', + builtAt, + specSha256: sha256(specText), + catalog: report.catalog, + widgetOrder: compiled.widgetOrder, + rung, + ok: report.ok, + counts: report.counts, + fileCheck: report.fileCheck, + findings: findings.slice(0, 200), + files: { workflow: FILES.workflow, prompt: FILES.prompt }, + note: 'workflow.json and prompt.json are GENERATED from project.json by dsh-comfyui. Edit the spec, then build again - editing the canvas loses the edit on the next build.', + }) + report.files.readme = writeText(paths.readme, readmeFor({ project, report, manifest: raw })) + return report +} + +/** The workflow-driven half: a canvas the app wrote, whose prompt is derived. */ +function buildFromWorkflowFile({ raw, paths, catalog, now, dryRun, install }) { + const findings = [] + if (!existsSync(paths.workflow)) { + throw new ComfyError('NO_WORKFLOW', 'this project is source "workflow" but ' + paths.workflow + ' is gone. Re-import it with `comfy_project` action=import.', { path: paths.workflow }) + } + const workflowRaw = readJson(paths.workflow) + const parsed = parseWorkflow(workflowRaw) + findings.push(...parsed.findings) + let prompt = {} + try { + const derived = workflowToPrompt(parsed, catalog) + prompt = derived.prompt + findings.push(...derived.findings) + } catch (error) { + if (!(error instanceof ComfyError)) throw error + findings.push({ severity: 'error', type: error.code, message: error.message }) + } + const validated = Object.keys(prompt).length === 0 ? { findings: [], nodeErrors: {} } : validatePrompt(prompt, catalog) + findings.push(...validated.findings) + const fileCheck = checkPromptFiles({ prompt, catalog, install }) + findings.push(...fileCheck.findings) + const errors = findings.filter((entry) => entry.severity === 'error') + const report = { + ok: errors.length === 0, + rung: compileRung(findings, catalog), + findings, + prompt, + workflow: workflowRaw, + widgetOrder: 'workflow-file', + files: {}, + fileCheck: { checked: fileCheck.checked.length, missing: fileCheck.missing, roots: fileCheck.roots, skipped: fileCheck.skipped }, + counts: { nodes: parsed.nodes.length, links: parsed.links.length, errors: errors.length, warnings: findings.filter((entry) => entry.severity === 'warning').length }, + catalog: { source: catalog.source, version: catalog.version, origin: catalog.origin, complete: catalog.complete === true, described: describeCatalog(catalog) }, + } + if (dryRun === true) return report + const builtAt = typeof now === 'function' ? now() : new Date().toISOString() + if (Object.keys(prompt).length > 0) report.files.prompt = writeJson(paths.prompt, prompt) + report.files.build = writeJson(paths.build, { + schema: BUILD_SCHEMA, + project: typeof raw.name === 'string' ? raw.name : path.basename(paths.dir), + source: 'workflow', + builtAt, + workflowSha256: sha256(JSON.stringify(workflowRaw)), + catalog: report.catalog, + widgetOrder: 'workflow-file', + rung: report.rung, + ok: report.ok, + counts: report.counts, + findings: findings.slice(0, 200), + files: { workflow: FILES.workflow, prompt: FILES.prompt }, + note: 'workflow.json was written by ComfyUI and is NOT regenerated: prompt.json is derived from it on every build.', + }) + report.files.readme = writeText(paths.readme, readmeForWorkflow({ raw, report, parsed })) + return report +} + +/** A generated README: what this is, how to open it, what it needs, what was checked. */ +export function readmeFor({ project, report, manifest }) { + const lines = [] + lines.push('# ' + project.title) + lines.push('') + lines.push('') + lines.push('') + if (project.description !== '') { + lines.push(project.description) + lines.push('') + } + lines.push('| | |') + lines.push('|---|---|') + lines.push('| project | `' + project.name + '` |') + lines.push('| nodes | ' + report.counts.nodes + ' |') + lines.push('| links | ' + report.counts.links + ' |') + lines.push('| built | ' + report.rung + ' · ' + (report.ok ? 'no errors' : report.counts.errors + ' error(s)') + ' |') + lines.push('| catalog | ' + report.catalog.described + ' |') + lines.push('') + lines.push('## Open it') + lines.push('') + lines.push('Drag `workflow.json` onto the ComfyUI canvas. The canvas is generated from `project.json`; a change made in the app is lost on the next build, so change the spec instead.') + lines.push('') + lines.push('## Run it') + lines.push('') + lines.push('```') + lines.push('comfy_run project=' + project.name) + lines.push('```') + lines.push('') + lines.push('`comfy_run` queues `prompt.json` on the server, waits for `/history`, and reports the files it wrote. `comfy_validate` runs the same checks without queueing anything.') + lines.push('') + const models = Object.entries(project.requires.models ?? {}) + const inputs = project.requires.inputFiles ?? [] + if (models.length > 0 || inputs.length > 0) { + lines.push('## What it needs') + lines.push('') + for (const [folder, list] of models) { + for (const name of list) lines.push('- `models/' + folder + '/' + name + '`') + } + for (const name of inputs) lines.push('- `input/' + name + '`') + lines.push('') + lines.push('A file that is not there is reported by `comfy_validate` by name; nothing here downloads one.') + lines.push('') + } + lines.push('## The graph') + lines.push('') + lines.push('| key | class | title |') + lines.push('|---|---|---|') + for (const node of project.nodes) { + lines.push('| `' + node.key + '` | `' + node.class + '` | ' + node.title + ' |') + } + lines.push('') + if (Object.keys(project.bindings).length > 0) { + lines.push('## Bindings') + lines.push('') + lines.push('| name | value |') + lines.push('|---|---|') + for (const [name, value] of Object.entries(project.bindings)) lines.push('| `@' + name + '` | ' + ('`' + String(value) + '`') + ' |') + lines.push('') + } + const errors = report.findings.filter((entry) => entry.severity === 'error') + const warnings = report.findings.filter((entry) => entry.severity === 'warning') + if (report.findings.length > 0) { + lines.push('## Findings from the build') + lines.push('') + for (const entry of [...errors, ...warnings]) lines.push('- **' + entry.severity + '** `' + entry.type + '` — ' + entry.message) + lines.push('') + } + if (manifest !== null && typeof manifest.notes === 'string' && manifest.notes !== '') { + lines.push('## Notes') + lines.push('') + lines.push(manifest.notes) + lines.push('') + } + return lines.join('\n') +} + +/** The prompt-driven half: an imported API prompt is already the truth. */ +function buildFromPromptFile({ raw, paths, catalog, now, dryRun, install }) { + if (!existsSync(paths.prompt)) { + throw new ComfyError('NO_PROMPT', 'this project is source "prompt" but ' + paths.prompt + ' is gone. Re-import it with `comfy_project` action=import.', { path: paths.prompt }) + } + const prompt = readJson(paths.prompt) + const validated = validatePrompt(prompt, catalog) + const findings = [...validated.findings] + const files = checkPromptFiles({ prompt, catalog, install }) + findings.push(...files.findings) + const errors = findings.filter((entry) => entry.severity === 'error') + const report = { + ok: errors.length === 0, + rung: compileRung(findings, catalog), + findings, + prompt, + workflow: null, + widgetOrder: 'prompt-file', + fileCheck: { checked: files.checked.length, missing: files.missing, roots: files.roots, skipped: files.skipped }, + counts: { nodes: Object.keys(prompt ?? {}).length, links: 0, errors: errors.length, warnings: findings.filter((entry) => entry.severity === 'warning').length }, + catalog: { source: catalog.source, version: catalog.version, origin: catalog.origin, complete: catalog.complete === true, described: describeCatalog(catalog) }, + files: {}, + } + if (dryRun === true) return report + const builtAt = typeof now === 'function' ? now() : new Date().toISOString() + report.files.build = writeJson(paths.build, { + schema: BUILD_SCHEMA, + project: typeof raw.name === 'string' ? raw.name : path.basename(paths.dir), + source: 'prompt', + builtAt, + promptSha256: sha256(JSON.stringify(prompt)), + catalog: report.catalog, + widgetOrder: 'prompt-file', + rung: report.rung, + ok: report.ok, + counts: report.counts, + findings: findings.slice(0, 200), + files: { prompt: FILES.prompt }, + note: 'this project came in as an API prompt: prompt.json is the source and no canvas exists for it.', + }) + report.files.readme = writeText( + paths.readme, + [ + '# ' + (typeof raw.title === 'string' && raw.title !== '' ? raw.title : path.basename(paths.dir)), + '', + '', + '', + typeof raw.description === 'string' && raw.description !== '' ? raw.description : 'An API prompt imported with `comfy_project` action=import.', + '', + '| | |', + '|---|---|', + '| project | `' + path.basename(paths.dir) + '` |', + '| nodes | ' + report.counts.nodes + ' |', + '| rung | ' + report.rung + ' · ' + (report.ok ? 'no errors' : report.counts.errors + ' error(s)') + ' |', + '| catalog | ' + report.catalog.described + ' |', + '', + 'An API prompt has no canvas: there is nothing to drag into the app, and no `workflow.json` here.', + 'Run it with `comfy_run project=' + path.basename(paths.dir) + '`.', + findings.length === 0 ? '' : '', + ...findings.filter((entry) => entry.severity === 'error').map((entry) => '- **error** `' + entry.type + '` — ' + entry.message), + ].join('\n'), + ) + return report +} + +/** The same README for a project whose source is the canvas. */ +export function readmeForWorkflow({ raw, report, parsed }) { + const name = typeof raw.name === 'string' ? raw.name : 'project' + const title = typeof raw.title === 'string' && raw.title !== '' ? raw.title : name + const lines = [] + lines.push('# ' + title) + lines.push('') + lines.push('') + lines.push('') + if (typeof raw.description === 'string' && raw.description !== '') { + lines.push(raw.description) + lines.push('') + } + lines.push('| | |') + lines.push('|---|---|') + lines.push('| project | `' + name + '` |') + lines.push('| nodes | ' + parsed.nodes.length + ' |') + lines.push('| links | ' + parsed.links.length + ' |') + lines.push('| prompt | ' + report.rung + ' · ' + (report.ok ? 'derived' : report.counts.errors + ' error(s)') + ' |') + lines.push('| catalog | ' + report.catalog.described + ' |') + lines.push('') + lines.push('## Open it') + lines.push('') + lines.push('`workflow.json` IS the file the app saved: drag it onto the canvas to edit it there, then save it back into this folder and rebuild so `prompt.json` follows.') + lines.push('') + lines.push('## Run it') + lines.push('') + lines.push('```') + lines.push('comfy_run project=' + name) + lines.push('```') + lines.push('') + lines.push('`comfy_run` queues `prompt.json`, which is DERIVED from the canvas - `widgets_values` is an unnamed array, so the derivation needs the server\'s node catalog and is redone on every build.') + lines.push('') + const errors = report.findings.filter((entry) => entry.severity === 'error') + const warnings = report.findings.filter((entry) => entry.severity === 'warning') + if (report.findings.length > 0) { + lines.push('## Findings from the build') + lines.push('') + for (const entry of [...errors, ...warnings]) lines.push('- **' + entry.severity + '** `' + entry.type + '` — ' + entry.message) + lines.push('') + } + return lines.join('\n') +} + +/** Write a new project folder from a spec object. An existing folder is refused. */ +export function createProject({ root, spec, overwrite = false }) { + const slug = slugify(spec.name ?? '') + if (slug === '') throw new ComfyError('BAD_NAME', 'a project needs a name (lower case, digits and dashes).') + const paths = projectPaths(root, slug) + if (existsSync(paths.spec) && overwrite !== true) { + throw new ComfyError('PROJECT_EXISTS', 'a project called "' + slug + '" is already at ' + paths.dir + '. Pass overwrite:true to replace its project.json, or pick another name.', { path: paths.dir }) + } + mkdirSync(paths.dir, { recursive: true }) + const clean = { ...spec, name: slug } + writeJson(paths.spec, clean) + return { slug, paths, spec: clean } +} + +/** + * Import a workflow or an API prompt the app produced. + * + * A prompt (`{ id: { class_type, inputs } }`) needs nothing but a folder and a + * `prompt.json`; a canvas needs the catalog to be lowered, and says so when the + * catalog in force is the built-in table rather than a server's. + * + * @returns `{ slug, paths, kind, report }`. + */ +export function importProject({ root, name, source, catalog, now }) { + const slug = slugify(name ?? 'imported-workflow') + if (slug === '') throw new ComfyError('BAD_NAME', 'give the imported project a name.') + if (source === null || typeof source !== 'object' || Array.isArray(source)) { + throw new ComfyError('IMPORT_INVALID', 'that file is not a workflow or a prompt; both are JSON objects.') + } + const looksLikePrompt = Object.values(source).length > 0 && Object.values(source).every((value) => value !== null && typeof value === 'object' && typeof value.class_type === 'string') + const paths = projectPaths(root, slug) + mkdirSync(paths.dir, { recursive: true }) + if (looksLikePrompt) { + writeJson(paths.prompt, source) + writeJson(paths.spec, { + name: slug, + title: slug, + description: 'Imported API prompt. A prompt has no canvas, so there is no workflow.json here.', + source: 'prompt', + importedAt: typeof now === 'function' ? now() : new Date().toISOString(), + nodes: [], + }) + const validated = validatePrompt(source, catalog) + return { + slug, + paths, + kind: 'prompt', + report: { ok: validated.findings.every((entry) => entry.severity !== 'error'), rung: compileRung(validated.findings, catalog), findings: validated.findings, prompt: source, workflow: null, counts: { nodes: Object.keys(source).length, links: 0, errors: validated.findings.filter((entry) => entry.severity === 'error').length, warnings: validated.findings.filter((entry) => entry.severity === 'warning').length } }, + } + } + const parsed = parseWorkflow(source) + writeJson(paths.workflow, source) + writeJson(paths.spec, { + name: slug, + title: typeof source.title === 'string' && source.title !== '' ? source.title : slug, + description: 'Imported from a ComfyUI canvas: workflow.json is the source, prompt.json is derived from it.', + source: 'workflow', + importedAt: typeof now === 'function' ? now() : new Date().toISOString(), + nodes: [], + }) + const report = buildFromWorkflowFile({ raw: readJson(paths.spec), paths, catalog, now, dryRun: false }) + return { slug, paths, kind: 'workflow', report } +} + +/** The spec text one project holds, or '' when there is none. */ +export function specTextOf(paths) { + return existsSync(paths.spec) ? readFileSync(paths.spec, 'utf8') : '' +} + +/** A one-line summary of a report, for a tool's prose. */ +export function reportLine(report) { + const summary = summarizeFindings(report.findings) + return report.rung + (summary === '' ? '' : ' · ' + summary) +} + +/** The classes in a workflow, for a status answer. */ +export function classesInWorkflow(workflow) { + const nodes = workflow !== null && typeof workflow === 'object' && Array.isArray(workflow.nodes) ? workflow.nodes : [] + return [...new Set(nodes.map((node) => String(node.type)))].sort() +} + +/** Every output file a finished history entry lists, plus its node titles. */ +export function describeOutputs(entry, prompt) { + const files = outputsOf(entry) + const titles = new Map() + for (const [id, node] of Object.entries(prompt ?? {})) { + const meta = node !== null && typeof node === 'object' && node._meta !== null && typeof node._meta === 'object' ? node._meta : {} + titles.set(String(id), typeof meta.title === 'string' ? meta.title : typeof node.class_type === 'string' ? node.class_type : id) + } + return files.map((file) => ({ ...file, nodeTitle: titles.get(String(file.node)) ?? file.node })) +} diff --git a/packages/dsh-comfyui/lib/spec.js b/packages/dsh-comfyui/lib/spec.js new file mode 100644 index 0000000..069685e --- /dev/null +++ b/packages/dsh-comfyui/lib/spec.js @@ -0,0 +1,366 @@ +/** + * dsh-comfyui — the project spec: the small file a person (or an agent) edits, + * and the checks that make a bad one fail HERE rather than in the app. + * + * WHY A SPEC AT ALL: a ComfyUI workflow JSON is a serialized canvas - numeric + * node ids, links that point at array positions, and `widgets_values`, an + * UNNAMED array whose meaning depends on the node class's input order and on + * whether that class inserts a `control_after_generate` value after its seed. + * Editing one by hand means counting array positions. A spec names every value + * (`"ckpt_name": "@checkpoint"`), names every wire (`"model": "ckpt.MODEL"`), + * and the compiler derives both generated files from it - so the file a person + * edits is the file they can read. + * + * The sigil is ONE character: a string value starting with `@` is a BINDING, + * resolved from `bindings`. `"@checkpoint"` is how a template says "whichever + * checkpoint this machine has" without baking a filename into a document that + * outlives the download. + * + * Every refusal is a finding with ComfyUI's own `type` where one exists, plus + * the node KEY and input NAME, because those are what the person is looking at. + */ + +import { ComfyError } from './errors.js' +import { knows, linkInputs, nodeIn, outputSlot, widgetInputs } from './nodes.js' + +/** The keys a project may carry, so a typo is refused instead of ignored. */ +const PROJECT_KEYS = ['name', 'title', 'description', 'requires', 'bindings', 'nodes', 'notes', 'tags', 'template', 'source', 'generated'] +const NODE_KEYS = ['key', 'class', 'title', 'pos', 'size', 'widgets', 'wires', 'controlAfterGenerate', 'notes', 'color', 'mode'] + +/** A slug the project folder can be named with. */ +export function slugify(text) { + return String(text ?? '') + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 64) +} + +/** A finding list as one sentence, or '' when there is nothing to say. */ +export function summarizeFindings(findings) { + const errors = findings.filter((entry) => entry.severity === 'error') + const warnings = findings.filter((entry) => entry.severity === 'warning') + const parts = [] + if (errors.length > 0) parts.push(errors.length + ' error(s)') + if (warnings.length > 0) parts.push(warnings.length + ' warning(s)') + return parts.join(', ') +} + +/** One finding, shaped like the rest of the package. */ +function finding(severity, type, message, where = {}) { + return { severity, type, message, ...where } +} + +/** + * Validate and normalize a project spec. + * + * It does NOT need a complete catalog: with the built-in core table it checks + * every node it knows and says which ones it could not check, which is the + * honest answer on a machine where ComfyUI is not running yet. + * + * @param raw - the parsed `project.json`. + * @param catalog - the node catalog in force. + * @returns `{ project, findings }` - `findings` with any `error` means the + * project must not be compiled. + * @throws ComfyError when the file is not a project at all. + */ +export function readSpec(raw, catalog) { + if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) { + throw new ComfyError('SPEC_INVALID', 'project.json must be a JSON object with `name` and `nodes`, not ' + (Array.isArray(raw) ? 'an array' : typeof raw) + '.') + } + const findings = [] + for (const key of Object.keys(raw)) { + if (!PROJECT_KEYS.includes(key)) { + findings.push(finding('warning', 'unknown_field', 'project.json has an unknown field "' + key + '", which nothing reads. Known fields: ' + PROJECT_KEYS.join(', ') + '.')) + } + } + const name = slugify(raw.name ?? '') + if (name === '') { + findings.push(finding('error', 'missing_name', 'project.json needs a `name` (a folder-safe slug, e.g. "text-to-image").')) + } + const requires = normalizeRequires(raw.requires, findings) + const bindings = raw.bindings !== null && typeof raw.bindings === 'object' && !Array.isArray(raw.bindings) ? { ...raw.bindings } : {} + const nodesRaw = Array.isArray(raw.nodes) ? raw.nodes : [] + if (nodesRaw.length === 0) { + findings.push(finding('error', 'missing_nodes', 'project.json needs a non-empty `nodes` array; a graph with no nodes is not a project.')) + } + + const seen = new Map() + const nodes = [] + for (const [index, entry] of nodesRaw.entries()) { + if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) { + findings.push(finding('error', 'bad_node', 'nodes[' + index + '] is not an object.')) + continue + } + for (const key of Object.keys(entry)) { + if (!NODE_KEYS.includes(key)) { + findings.push(finding('warning', 'unknown_field', 'nodes[' + index + '] has an unknown field "' + key + '", which nothing reads. Known fields: ' + NODE_KEYS.join(', ') + '.')) + } + } + const key = typeof entry.key === 'string' ? entry.key.trim() : '' + if (!/^[A-Za-z][A-Za-z0-9_.-]*$/.test(key)) { + findings.push(finding('error', 'bad_key', 'nodes[' + index + '] needs a `key` matching [A-Za-z][A-Za-z0-9_.-]* (it is how other nodes refer to it), got ' + JSON.stringify(entry.key) + '.')) + continue + } + if (seen.has(key)) { + findings.push(finding('error', 'duplicate_key', 'two nodes share the key "' + key + '"; keys are node identities, so they must be unique.')) + continue + } + seen.set(key, true) + const classType = typeof entry.class === 'string' ? entry.class.trim() : '' + if (classType === '') { + findings.push(finding('error', 'missing_class', 'node "' + key + '" has no `class`; it must name a ComfyUI node class such as KSampler.', { node: key })) + continue + } + const node = { + key, + class: classType, + title: typeof entry.title === 'string' && entry.title !== '' ? entry.title : '', + pos: Array.isArray(entry.pos) && entry.pos.length === 2 && entry.pos.every((value) => Number.isFinite(value)) ? [Number(entry.pos[0]), Number(entry.pos[1])] : null, + size: Array.isArray(entry.size) && entry.size.length === 2 && entry.size.every((value) => Number.isFinite(value)) ? [Number(entry.size[0]), Number(entry.size[1])] : null, + widgets: {}, + wires: {}, + controlAfterGenerate: entry.controlAfterGenerate !== null && typeof entry.controlAfterGenerate === 'object' && !Array.isArray(entry.controlAfterGenerate) ? { ...entry.controlAfterGenerate } : {}, + notes: typeof entry.notes === 'string' ? entry.notes : '', + mode: Number.isInteger(entry.mode) ? entry.mode : 0, + } + if (entry.widgets !== null && entry.widgets !== undefined) { + if (typeof entry.widgets !== 'object' || Array.isArray(entry.widgets)) { + findings.push(finding('error', 'bad_widgets', 'node "' + key + '" has `widgets` that is not an object; it maps an input name to a value.', { node: key })) + } else { + node.widgets = { ...entry.widgets } + } + } + if (entry.wires !== null && entry.wires !== undefined) { + if (typeof entry.wires !== 'object' || Array.isArray(entry.wires)) { + findings.push(finding('error', 'bad_wires', 'node "' + key + '" has `wires` that is not an object; it maps an input name to "." (or ".").', { node: key })) + } else { + node.wires = { ...entry.wires } + } + } + nodes.push(node) + } + + const byKey = new Map(nodes.map((node) => [node.key, node])) + for (const node of nodes) { + const spec = nodeIn(catalog, node.class) + if (spec === null) { + if (catalog.complete) { + findings.push(finding('error', 'missing_node_type', 'node "' + node.key + '" is class "' + node.class + '", which this server does not have. A custom node missing from custom_nodes/ is the usual cause.', { node: node.key, class: node.class })) + } else { + findings.push(finding('warning', 'class_unverified', 'node "' + node.key + '" is class "' + node.class + '", which the built-in core table does not cover, so nothing here can confirm it exists. `comfy_status` names a server whose `/object_info` can.', { node: node.key, class: node.class })) + } + continue + } + if (spec.deprecated) { + findings.push(finding('warning', 'deprecated_class', 'node "' + node.key + '" uses "' + node.class + '", which the server marks deprecated.', { node: node.key, class: node.class })) + } + // Widgets: every name must be a widget input of THIS class, and every + // required widget must be set (or be an escape-hatch node). + const widgets = widgetInputs(spec) + const names = new Set(widgets.map((input) => input.name)) + for (const name of Object.keys(node.widgets)) { + if (!names.has(name)) { + findings.push(finding('error', 'unknown_widget', 'node "' + node.key + '" ("' + node.class + '") has no widget input "' + name + '". Its widgets: ' + (names.size === 0 ? '(none)' : [...names].join(', ')) + '.', { node: node.key, input: name, class: node.class })) + } + } + if (node.widgetsValues === null) { + for (const input of widgets) { + if (input.optional || input.name in node.widgets) continue + const fallback = input.options !== undefined && input.options.default !== undefined ? input.options.default : input.enum !== null && input.enum.length > 0 ? input.enum[0] : undefined + if (fallback === undefined) { + findings.push(finding('warning', 'unset_widget', 'node "' + node.key + '" ("' + node.class + '") leaves widget "' + input.name + '" unset and the class has no default for it; the compiled prompt will omit it.', { node: node.key, input: input.name })) + } + } + } + // Wires: the input must exist and be linkable, and the source must resolve. + const linkable = new Set(linkInputs(spec).map((input) => input.name)) + const widgetLinkable = new Set(widgets.map((input) => input.name)) + for (const [input, target] of Object.entries(node.wires)) { + if (!linkable.has(input) && !widgetLinkable.has(input)) { + findings.push(finding('error', 'unknown_input', 'node "' + node.key + '" ("' + node.class + '") has no input named "' + input + '", so nothing can be wired into it. Its inputs: ' + [...linkable, ...widgetLinkable].join(', ') + '.', { node: node.key, input })) + continue + } + const resolved = resolveWire(target, byKey, catalog) + if (resolved.error !== '') { + findings.push(finding('error', resolved.type, 'node "' + node.key + '" input "' + input + '": ' + resolved.error, { node: node.key, input })) + continue + } + if (resolved.key === node.key) { + findings.push(finding('error', 'dependency_cycle', 'node "' + node.key + '" wires its own input "' + input + '" from itself.', { node: node.key, input })) + } + const targetSpec = nodeIn(catalog, byKey.get(resolved.key).class) + if (targetSpec !== null && targetSpec.outputs.length > 0) { + const targetType = targetSpec.outputs[resolved.slot].type + const inputSpec = spec.inputs.find((entry) => entry.name === input) + if (inputSpec !== undefined && !typesCompatible(targetType, inputSpec.type)) { + findings.push(finding('error', 'return_type_mismatch', 'node "' + node.key + '" input "' + input + '" is ' + inputSpec.type + ', but "' + resolved.key + '" output ' + resolved.slot + ' ("' + targetSpec.outputs[resolved.slot].name + '") is ' + targetType + '. ComfyUI refuses this wire.', { node: node.key, input })) + } + } + } + } + + const cycle = findCycle(nodes, catalog) + if (cycle.length > 0) { + findings.push(finding('error', 'dependency_cycle', 'the graph has a dependency cycle: ' + cycle.join(' -> ') + '. A node cannot wait for its own output.', { nodes: cycle })) + } + + const outputNodes = nodes.filter((node) => { + const spec = nodeIn(catalog, node.class) + return spec !== null && spec.outputNode + }) + if (outputNodes.length === 0 && nodes.length > 0) { + const unknown = nodes.filter((node) => nodeIn(catalog, node.class) === null).length + if (unknown > 0) { + findings.push(finding('warning', 'output_unverified', 'no node in this project is a known OUTPUT node (SaveImage, SaveVideo, PreviewImage, ...), and ' + unknown + ' class(es) could not be checked; ComfyUI answers `prompt_no_outputs` for a prompt with nothing to run.', {})) + } else { + findings.push(finding('error', 'prompt_no_outputs', 'no node in this project is an OUTPUT node, so ComfyUI would refuse the prompt with `prompt_no_outputs`. Add a SaveImage / SaveVideo / PreviewImage and wire it.', {})) + } + } + + return { + project: { + name, + title: typeof raw.title === 'string' && raw.title !== '' ? raw.title : name, + description: typeof raw.description === 'string' ? raw.description : '', + requires, + bindings, + nodes, + notes: typeof raw.notes === 'string' ? raw.notes : '', + tags: Array.isArray(raw.tags) ? raw.tags.map(String) : [], + template: typeof raw.template === 'string' ? raw.template : '', + source: typeof raw.source === 'string' ? raw.source : 'spec', + byKey, + findings, + }, + findings, + } +} + +/** `requires`, with every folder a map of names. */ +function normalizeRequires(raw, findings) { + const requires = { models: {}, nodes: [], inputFiles: [], customNodes: [] } + if (raw === null || raw === undefined) return requires + if (typeof raw !== 'object' || Array.isArray(raw)) { + findings.push(finding('warning', 'bad_requires', '`requires` is not an object, so nothing is declared as needed.')) + return requires + } + if (raw.models !== null && typeof raw.models === 'object' && !Array.isArray(raw.models)) { + for (const [folder, list] of Object.entries(raw.models)) { + if (!Array.isArray(list)) continue + requires.models[folder] = list.map(String).filter((entry) => entry !== '') + } + } + if (Array.isArray(raw.nodes)) requires.nodes = raw.nodes.map(String) + if (Array.isArray(raw.customNodes)) requires.customNodes = raw.customNodes.map(String) + if (Array.isArray(raw.inputFiles)) requires.inputFiles = raw.inputFiles.map(String) + return requires +} + +/** + * A wire target: `"."`, `"."`, or `""` for slot 0. + * + * @returns `{ key, slot, error, type }` - `error` is '' on success. + */ +export function resolveWire(target, byKey, catalog) { + const text = String(target ?? '').trim() + if (text === '') return { key: '', slot: -1, error: 'has an empty wire target.', type: 'bad_linked_input' } + const dot = text.lastIndexOf('.') + const key = dot === -1 ? text : text.slice(0, dot) + const suffix = dot === -1 ? '' : text.slice(dot + 1) + if (!byKey.has(key)) { + return { + key, + slot: -1, + error: 'wires from "' + key + '", which is not a node key in this project. Keys: ' + ([...byKey.keys()].join(', ') || '(none)') + '.', + type: 'bad_linked_input', + } + } + const source = byKey.get(key) + const spec = nodeIn(catalog, source.class) + if (suffix === '') { + if (spec !== null && spec.outputs.length === 0) { + return { key, slot: -1, error: 'wires from "' + key + '" (' + source.class + '), which has no outputs.', type: 'bad_linked_input' } + } + return { key, slot: 0, error: '', type: '' } + } + if (spec === null) { + // No schema: only an explicit slot number can be trusted. + const numeric = Number(suffix) + if (Number.isInteger(numeric) && numeric >= 0) return { key, slot: numeric, error: '', type: '' } + return { + key, + slot: -1, + error: 'names output "' + suffix + '" of "' + key + '" (' + source.class + '), and that class is not in the catalog in force, so the output name cannot be resolved to a slot. Write "' + key + '." instead, or start ComfyUI so its `/object_info` can be read.', + type: 'unknown_output', + } + } + const numeric = Number(suffix) + const slot = /^\d+$/.test(suffix) ? outputSlot(spec, numeric) : outputSlot(spec, suffix) + if (slot === -1) { + return { + key, + slot: -1, + error: '"' + key + '" (' + source.class + ') has no output "' + suffix + '". Its outputs: ' + (spec.outputs.length === 0 ? '(none)' : spec.outputs.map((output, index) => index + '=' + output.name + ':' + output.type).join(', ')) + '.', + type: 'unknown_output', + } + } + return { key, slot, error: '', type: '' } +} + +/** + * Whether an output of one type may feed an input of another. + * + * ComfyUI's rule (`comfy_execution.validation.validate_node_input`): both sides + * are comma-separated type sets, `*` matches anything, and a NON-EMPTY + * intersection is enough. Reproducing it here is the difference between a + * validator that agrees with the server and one that refuses valid graphs. + */ +export function typesCompatible(receivedType, inputType) { + const received = String(receivedType ?? '') + const wanted = String(inputType ?? '') + if (received === wanted) return true + if (received === '*' || wanted === '*') return true + const left = new Set(received.split(',').map((entry) => entry.trim())) + const right = new Set(wanted.split(',').map((entry) => entry.trim())) + if (left.has('*') || right.has('*')) return true + for (const entry of left) if (right.has(entry)) return true + return false +} + +/** The first dependency cycle among the node keys, as a readable path, or []. */ +export function findCycle(nodes, catalog) { + const byKey = new Map(nodes.map((node) => [node.key, node])) + const state = new Map() + const stack = [] + let found = null + const walk = (key) => { + if (found !== null) return + const mark = state.get(key) ?? 0 + if (mark === 1) { + const at = stack.indexOf(key) + found = stack.slice(at).concat([key]) + return + } + if (mark === 2) return + state.set(key, 1) + stack.push(key) + const node = byKey.get(key) + if (node !== undefined) { + for (const target of Object.values(node.wires)) { + const resolved = resolveWire(target, byKey, catalog) + if (resolved.error === '' && resolved.key !== '') walk(resolved.key) + } + } + stack.pop() + state.set(key, 2) + } + for (const node of nodes) walk(node.key) + return found ?? [] +} + +/** Whether a catalog can speak about every class in the project. */ +export function fullyKnown(project, catalog) { + return project.nodes.every((node) => knows(catalog, node.class)) +} diff --git a/packages/dsh-comfyui/lib/tools.js b/packages/dsh-comfyui/lib/tools.js new file mode 100644 index 0000000..9d58327 --- /dev/null +++ b/packages/dsh-comfyui/lib/tools.js @@ -0,0 +1,1273 @@ +/** + * dsh-comfyui — the six tools, and the prose that is the product. + * + * Every answer is written for the reader that has to decide what to do next, so + * each one carries its CONDITIONS with its facts: + * + * - `comfy_status` keeps four things apart that fail independently: an install + * on disk, a server answering on loopback, a node catalog, and an + * interpreter. It starts nothing and names the ports it tried; + * - `comfy_nodes` answers from the catalog IN FORCE and says which that is + * (`/object_info`, a cached catalog, or the built-in core table); + * - `comfy_project` writes a folder; `new` rebinds a template to the models + * this machine actually has, and says every rebinding it made; + * - `comfy_validate` runs ComfyUI's own checks offline and names the rung it + * reached, so "it compiles" is never printed as "it runs"; + * - `comfy_run` is the only tool that queues work, and reports what the + * server's `/history` says came out - or the node that raised; + * - `comfy_test` is the ladder over the whole shipped library: compile always, + * run when a server answers, one rung per item. + */ + +import { existsSync, readFileSync } from 'node:fs' +import path from 'node:path' + +import { ComfyError, messageOf } from './errors.js' +import { findServer, fetchObjectInfo, writeCache, readCache, listCache, discoverInstall, queuePrompt, waitForHistory, formatMilliseconds, formatBytes } from './client.js' +import { cliCommand, cliVersion, cliJson, envFacts, whichFacts, depsArgv, runArgv, launchArgv, stopArgv, promptIdFromRunText, explainCliFailure, READ_TIMEOUT_MS, RUN_TIMEOUT_MS } from './cli.js' +import { coreCatalog, catalogFromObjectInfo, categoriesIn, searchCatalog, nodeIn, widgetInputs, SOURCES } from './nodes.js' +import { inventory } from './files.js' +import { slugify } from './spec.js' +import { describeCatalog, CONTROL_AFTER_GENERATE } from './compile.js' +import { validatePrompt, parseWorkflow, workflowToPrompt, findingsFromNodeErrors, errorsOf, errorSentenceFromResponse, outputsOf } from './graph.js' +import { buildFromSpec, createProject, importProject, listProjects, projectPaths, projectsRoot, readJson, RUNGS, FILES, describeOutputs } from './projects.js' +import { listExamples, readExample, requirementLine } from './examples.js' + +/** The output shape every tool returns: prose for the model, a view for the card. */ +const OUTPUT = { + schema: { + type: 'object', + properties: { text: { type: 'string' }, view: { type: 'object' } }, + required: ['text', 'view'], + }, + render: (_args, value) => [{ type: 'text', text: value.text }], + presentationMeta: (_args, value) => value.view, +} + +/** A card for the transcript. */ +function present(title) { + return { + presentCall: () => ({ card: 'generic', title, kind: 'other' }), + presentResult: (_args, result) => ({ card: 'generic', title, content: result && result.text ? result.text : '' }), + } +} + +/** A refusal: a sentence, and a view a caller can branch on. */ +function refusal(code, message, extra) { + return { text: message, view: { ok: false, code, ...(extra ?? {}) } } +} + +/** The same refusal for any thrown failure, keeping a typed code when there is one. */ +function failureOf(error) { + if (error instanceof ComfyError) return refusal(error.code, error.message, { ...error.extra }) + return refusal('FAILED', messageOf(error)) +} + +/** Pad a column, clipping it to its width. */ +function cell(value, width) { + const text = String(value === undefined || value === null ? '' : value) + const cut = text.length > width ? text.slice(0, Math.max(0, width - 1)) + '…' : text + return cut.padEnd(width) +} + +/** A fixed-width table: the header line, then one line per row. */ +function table(headers, rows) { + if (rows.length === 0) return headers.join(' ') + const widths = headers.map((header, index) => Math.min(46, Math.max(header.length, ...rows.map((row) => String(row[index] ?? '').length)))) + const line = (cells) => cells.map((value, index) => cell(value, widths[index])).join(' ').trimEnd() + return [line(headers), ...rows.map(line)].join('\n') +} + +/** The workspace folder for a session, or '' when the host cannot name one. */ +function workspaceOf(ctx, exec, sessionId) { + const header = exec && exec.agent && exec.agent.session ? exec.agent.session.header : undefined + if (header && typeof header.cwd === 'string' && header.cwd !== '') return header.cwd + try { + const sessions = typeof ctx.get === 'function' ? ctx.get('sessions') : undefined + const live = sessions && typeof sessions.get === 'function' && sessionId !== '' ? sessions.get(sessionId) : undefined + const cwd = live && live.header ? live.header.cwd : undefined + if (typeof cwd === 'string' && cwd !== '') return cwd + } catch (error) { + // fall through + } + return '' +} + +/** The session id one call belongs to. */ +function sessionOf(exec) { + const session = exec && exec.agent ? exec.agent.session : undefined + return session && typeof session.id === 'string' ? session.id : '' +} + +/** + * The catalog in force, and how it was obtained. + * + * Order is deliberate: a live server first (it is the only complete catalog), + * then the newest cached one (a server that has since stopped still left the + * truth it reported), then the built-in core table (enough to compile the + * shipped examples on a machine where nothing is installed). + * + * A live read is cached, so the second call in a session costs no request. + */ +async function catalogFor(deps, options = {}) { + const env = deps.env ?? process.env + const found = await findServer(deps, { signal: options.signal, timeoutMs: options.probeTimeoutMs }) + if (found.server !== null) { + try { + const raw = await fetchObjectInfo(deps, found.server.origin, { signal: options.signal }) + const catalog = catalogFromObjectInfo(raw, { origin: found.server.origin, version: found.server.version, fetchedAt: new Date().toISOString() }) + const file = writeCache(env, found.server.origin, { schema: 1, origin: found.server.origin, version: found.server.version, fetchedAt: catalog.fetchedAt, objectInfo: raw }) + return { catalog, server: found.server, probed: found.probed, servers: found.servers, cacheFile: file, note: '' } + } catch (error) { + if (error instanceof ComfyError && error.code === 'TIMEOUT') { + return { catalog: coreCatalog(), server: found.server, probed: found.probed, servers: found.servers, cacheFile: '', note: 'the server answered but /object_info timed out (' + error.message + ')' } + } + throw error + } + } + const cached = listCache(env) + if (cached.length > 0) { + const record = readCache(env, cached[0].origin) + if (record !== null) { + const catalog = catalogFromObjectInfo(record.objectInfo, { origin: record.origin, version: record.version, fetchedAt: record.fetchedAt }) + catalog.source = SOURCES.cache + for (const node of catalog.nodes.values()) node.source = SOURCES.cache + return { catalog, server: null, probed: found.probed, servers: found.servers, cacheFile: cached[0].file, note: 'no server answered, so this catalog is the one cached from ' + (record.origin === '' ? 'an earlier server' : record.origin) + (record.fetchedAt === '' ? '' : ' at ' + record.fetchedAt) } + } + } + return { + catalog: coreCatalog(), + server: null, + probed: found.probed, + servers: found.servers, + cacheFile: '', + note: found.servers.allowed ? 'no server answered and no catalog is cached, so this is the built-in core table' : found.servers.reason, + } +} + +/** Where this session's projects live. */ +function rootOf(deps, exec) { + const cwd = workspaceOf(deps.ctx, exec, sessionOf(exec)) + return projectsRoot(deps.env ?? process.env, cwd === '' ? process.cwd() : cwd) +} + +/** The install on disk, with comfy-cli's own view of the workspaces when it is there. */ +function installOf(deps, cliFacts = null) { + return discoverInstall({ env: deps.env ?? process.env, platform: deps.platform, cli: cliFacts }) +} + +/** + * The install, asking comfy-cli only when the cheap discovery found no base path. + * + * A Desktop config that points at a deleted folder is exactly the machine where + * comfy-cli's \`env\` still knows a live install, and it is the only machine that + * needs the extra process - everywhere else this costs nothing. + */ +async function installFor(deps) { + const plain = installOf(deps) + if (plain.base !== '') return plain + const cli = await cliFactsOf(deps) + return cli.facts === null ? plain : installOf(deps, cli.facts) +} + +/** + * The comfy-cli facts, read ONCE per call. + * + * `comfy env` is the only place a Desktop install's `code_dir`/`data_dir` are + * written down, so it is worth a Python start - but it is also one process, so + * every tool that needs it takes this result rather than asking again. + */ +async function cliFactsOf(deps, options = {}) { + const env = deps.env ?? process.env + if (typeof deps.runner !== 'function') return { version: { found: false, command: '', version: '', error: 'no runner' }, facts: null, which: null, envAnswer: null } + const version = await cliVersion(deps.runner, env, { timeoutMs: options.timeoutMs ?? 8000 }) + if (!version.found) return { version, facts: null, which: null, envAnswer: null } + const envAnswer = await cliJson(deps.runner, ['env'], { env, command: version.command, timeoutMs: READ_TIMEOUT_MS }) + const whichAnswer = await cliJson(deps.runner, ['which'], { env, command: version.command, timeoutMs: READ_TIMEOUT_MS }) + return { + version, + facts: envFacts(envAnswer.data), + which: whichFacts(whichAnswer.data), + envAnswer, + } +} + +/** Resolve a `project` argument: a slug under the root, or a path to a folder. */ +function projectPathsFor(root, argument) { + const text = String(argument ?? '').trim() + if (text === '') return null + const asSlug = slugify(text) + if (asSlug !== '' && existsSync(projectPaths(root, asSlug).spec)) return projectPaths(root, asSlug) + const resolved = path.resolve(text) + if (existsSync(path.join(resolved, FILES.spec))) return projectPaths(path.dirname(resolved), path.basename(resolved)) + if (asSlug !== '' && existsSync(projectPaths(root, asSlug).dir)) return projectPaths(root, asSlug) + return null +} + +/** The one project a call names, or a refusal naming what is there. */ +function requireProject(root, argument) { + const paths = projectPathsFor(root, argument) + if (paths === null) { + const available = listProjects(root).map((entry) => entry.slug) + throw new ComfyError('NO_PROJECT', 'no project "' + String(argument ?? '') + '" under ' + root + '. There: ' + (available.join(', ') || '(none - `comfy_project` action=new writes one, or action=list the examples)') + '.') + } + return paths +} + +/** A findings list as a compact block: errors first, each with its type. */ +function findingsBlock(findings, limit = 40) { + const ordered = [...findings.filter((entry) => entry.severity === 'error'), ...findings.filter((entry) => entry.severity === 'warning')] + if (ordered.length === 0) return '' + const lines = [] + for (const entry of ordered.slice(0, limit)) { + const where = [entry.node === undefined ? '' : 'node ' + entry.node, entry.input === undefined ? '' : 'input ' + entry.input].filter((part) => part !== '').join(' · ') + lines.push(' ' + entry.severity.toUpperCase() + ' ' + entry.type + (where === '' ? '' : ' (' + where + ')') + ': ' + entry.message) + } + if (ordered.length > limit) lines.push(' … ' + (ordered.length - limit) + ' more') + return lines.join('\n') +} + +/** + * A spec rebuilt against the models this machine actually has. + * + * The rule is deliberately narrow: a binding that feeds a FILE input (a + * checkpoint, a LoRA, an input image) is replaced only when the server's own + * list does not contain it - and then only by an exact case-insensitive match + * or, when the list has exactly one entry, by that entry. Anything less certain + * is left alone and reported, because silently pointing a graph at the wrong + * checkpoint produces an image nobody asked for. + */ +export function rebindToCatalog(spec, catalog) { + const changes = [] + const notes = [] + if (catalog === null || catalog.complete !== true) { + notes.push('no complete catalog, so bindings were left exactly as the template declares them') + return { spec, changes, notes } + } + const next = JSON.parse(JSON.stringify(spec)) + for (const node of next.nodes ?? []) { + const nodeSpec = nodeIn(catalog, node.class) + if (nodeSpec === null) continue + for (const [inputName, value] of Object.entries(node.widgets ?? {})) { + if (typeof value !== 'string' || !value.startsWith('@')) continue + const bindingName = value.slice(1) + if (!(bindingName in (next.bindings ?? {}))) continue + const inputSpec = nodeSpec.inputs.find((input) => input.name === inputName) + if (inputSpec === undefined || inputSpec.enum === null || inputSpec.enum.length === 0) continue + const current = String(next.bindings[bindingName]) + if (inputSpec.enum.includes(current)) continue + const insensitive = inputSpec.enum.find((option) => option.toLowerCase() === current.toLowerCase()) + const replacement = insensitive ?? (inputSpec.enum.length === 1 ? inputSpec.enum[0] : '') + if (replacement === '') { + notes.push( + '@' + + bindingName + + ' is "' + + current + + '", which is not in this server\'s list for ' + + node.class + + '.' + + inputName + + ', and the list has ' + + inputSpec.enum.length + + ' entries so nothing was chosen: set it to one of ' + + inputSpec.enum.slice(0, 6).join(', ') + + (inputSpec.enum.length > 6 ? ', …' : '') + + '.', + ) + continue + } + changes.push({ binding: bindingName, from: current, to: replacement, why: inputSpec.enum.length === 1 ? 'the only file this server lists for ' + node.class + '.' + inputName : 'a case-insensitive match in this server\'s list' }) + next.bindings[bindingName] = replacement + } + } + return { spec: next, changes, notes } +} + +/** The sentence a machine with no server gets, naming what would start one. */ +function noServerText(install, probed) { + const lines = [] + lines.push('No ComfyUI server answered. Tried: ' + (probed.filter((entry) => !entry.up).map((entry) => entry.origin).join(', ') || '(nothing - the URL was refused)') + '.') + if (install !== null && install.found) { + lines.push('ComfyUI is installed here' + (install.version === '' ? '' : ' (' + install.version + ')') + (install.app === '' ? '' : ' at ' + install.app) + '.') + lines.push('Start it: open the ComfyUI app, or run `python main.py` in that folder. ComfyUI Desktop picks a port from 8000 upwards (not 8188), which is why this row tries both.') + } else { + lines.push('No ComfyUI install was found either. `comfy_status` names the places this row looks and DSH_COMFYUI_DIR pins one.') + } + lines.push('Nothing was started. Compiling a project needs no server; queueing one does.') + return lines.join('\n') +} + +/** Build the six tools. @param deps - `{ ctx, env, fetch, now, sleep, log }`. */ +export function buildTools(deps) { + /** `comfy_status`: the four facts, kept apart. */ + const status = { + name: 'comfy_status', + description: [ + 'Report what this machine has for ComfyUI, keeping apart four things that fail independently: an INSTALL on disk (a Desktop base path, a portable folder or a checkout - with its version, its python and how many model files each folder holds), a SERVER answering on loopback (`/system_stats`, with the device and VRAM), the NODE CATALOG in force (`/object_info` from a server, a cached one, or the built-in core table), and the projects in the workspace.', + 'Call this FIRST. ComfyUI Desktop does NOT use port 8188 - it picks 8000 upwards - so this tool tries 8188 and the Desktop ports and reports each probe. It also lists the node catalogs cached from earlier servers, which is what lets a project compile with the app closed.', + 'It never starts ComfyUI, downloads a model or writes anything except the catalog cache. Read-only.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + properties: { + timeoutSeconds: { type: 'number', description: 'Deadline for a single probe: 1-60 s. Default 2.5. A server that is there answers in milliseconds.' }, + }, + }, + output: OUTPUT, + ...present('ComfyUI status'), + async execute(args, exec) { + try { + const env = deps.env ?? process.env + // comfy-cli FIRST: its `env` names the Desktop installs and their data + // dirs, which is how a machine whose Desktop config points at a folder + // that is gone still gets its models found. + const cli = await cliFactsOf(deps, { timeoutMs: 8000 }) + const install = installOf(deps, cli.facts) + const stock = inventory(install) + const caches = listCache(env) + // One probe pass, one catalog read: `catalogFor` already reports what + // every origin said, so asking it twice would double every timeout on a + // machine where nothing answers. + const resolved = await catalogFor(deps, { signal: exec && exec.signal, probeTimeoutMs: Number.isFinite(args.timeoutSeconds) ? Math.min(60, Math.max(1, args.timeoutSeconds)) * 1000 : undefined }) + const found = { server: resolved.server, probed: resolved.probed, servers: resolved.servers } + const catalog = resolved + const root = rootOf(deps, exec) + const projects = listProjects(root) + + const lines = [] + const headline = [] + if (install.found) { + headline.push('ComfyUI ' + (install.version === '' ? '(version unknown)' : install.version)) + if (install.app !== '') headline.push('source ' + install.app) + if (install.base !== '') headline.push('base ' + install.base + ' (' + install.baseSource + ')') + } else { + headline.push('ComfyUI: no install found on this machine') + } + lines.push(headline.join(' · ')) + if (install.found && install.base === '') { + lines.push('Base path: none with models/ and custom_nodes/. A model filename cannot be checked against the disk here - the server\'s own lists are the only source of truth until one exists.') + } else if (install.base !== '') { + const folders = Object.entries(stock.folders).filter(([, entry]) => entry.count > 0) + lines.push('Models: ' + (folders.length === 0 ? 'no model files in ' + path.join(install.base, 'models') : stock.files + ' file(s) — ' + folders.map(([folder, entry]) => folder + ' ' + entry.count + ' (' + entry.first.slice(0, 2).join(', ') + (entry.count > 2 ? ', …' : '') + ')').join(' · '))) + lines.push('custom_nodes: ' + (install.customNodes.length === 0 ? '(none)' : install.customNodes.length + ' (' + install.customNodes.slice(0, 8).join(', ') + (install.customNodes.length > 8 ? ', …' : '') + ')')) + } + if (install.python !== '') lines.push('python: ' + install.python) + lines.push('') + if (found.server !== null) { + const server = found.server + lines.push('Server: ' + server.origin + (server.version === '' ? '' : ' · ComfyUI ' + server.version)) + if (server.device !== '') lines.push('Device: ' + server.device + (server.deviceType === '' ? '' : ' (' + server.deviceType + ')') + (server.vramTotal === null ? '' : ' · ' + formatBytes(server.vramTotal) + ' VRAM total, ' + formatBytes(server.vramFree) + ' free')) + if (server.ramTotal !== null) lines.push('RAM: ' + formatBytes(server.ramTotal) + (server.pythonVersion === '' ? '' : ' · python ' + server.pythonVersion) + (server.pytorchVersion === '' ? '' : ' · torch ' + server.pytorchVersion)) + } else { + lines.push(noServerText(install, found.probed)) + } + lines.push('') + const catalogInfo = catalog.catalog + lines.push( + 'Catalog: ' + + (catalogInfo.source === SOURCES.server + ? '/object_info from ' + catalogInfo.origin + ' · ' + catalogInfo.nodes.size + ' classes · also cached' + : catalogInfo.source === SOURCES.cache + ? 'cached (' + catalogInfo.nodes.size + ' classes' + (catalogInfo.fetchedAt === '' ? '' : ', ' + catalogInfo.fetchedAt) + ') · ' + catalog.cacheFile + : 'built-in core table · ' + catalogInfo.nodes.size + ' classes (the nodes the shipped examples use)'), + ) + if (catalog.note !== '') lines.push(' ' + catalog.note) + if (caches.length > 0) lines.push('Cached catalogs: ' + caches.slice(0, 4).map((entry) => (entry.origin === '' ? entry.file : entry.origin) + (entry.version === '' ? '' : ' (' + entry.version + ')') + ' · ' + entry.classes + ' classes').join(' ; ')) + lines.push('') + if (cli.version.found) { + const facts = cli.facts + const where = facts === null ? '' : facts.workspace + const exists = facts === null ? null : facts.workspaceExists + lines.push('comfy-cli: ' + cli.version.version + ' (' + cli.version.command + ')') + if (where !== '') lines.push(' workspace: ' + where + (exists === true ? '' : exists === false ? ' — DOES NOT EXIST' : '')) + if (facts !== null && facts.serverRunning !== null) lines.push(' it reports a server ' + (facts.serverRunning ? 'RUNNING' + (facts.serverUrl === '' ? '' : ' at ' + facts.serverUrl) : 'not running')) + if (facts !== null && facts.gpu !== '') lines.push(' hardware: ' + facts.gpu + (facts.vramBytes === null ? '' : ' · ' + formatBytes(facts.vramBytes) + ' VRAM') + (facts.ramBytes === null ? '' : ' · ' + formatBytes(facts.ramBytes) + ' RAM')) + if (facts !== null && facts.installs.length > 0) { + lines.push(' Desktop install' + (facts.installs.length === 1 ? '' : 's') + ' it knows: ' + facts.installs.map((entry) => (entry.name === '' ? '(unnamed)' : entry.name) + (entry.exists ? '' : ' [gone]') + (entry.dataDir === '' ? '' : ' → ' + entry.dataDir)).join(' ; ')) + } + if (facts !== null && facts.managerMode !== '') lines.push(' ComfyUI-Manager: ' + facts.managerMode + ' (needed by `comfy node deps-in-workflow`)') + if (cli.envAnswer !== null && cli.envAnswer.ok === false && cli.envAnswer.error !== '') lines.push(' `comfy env` said: ' + cli.envAnswer.error) + } else { + lines.push('comfy-cli: no `comfy` on PATH' + (cli.version.error === '' ? '' : ' (' + cli.version.error + ')') + '. `pip install comfy-cli` gives this machine a second, cross-platform way to install, launch, run a workflow and resolve its node dependencies - `comfy_cli` drives it once it is there. Without it the seven HTTP tools are unaffected.') + } + lines.push('') + lines.push('Projects in ' + root + ': ' + projects.length + (projects.length === 0 ? '' : ' (' + projects.filter((entry) => entry.built).length + ' built)')) + for (const entry of projects.slice(0, 10)) lines.push(' ' + entry.slug + (entry.built ? ' · ' + (entry.build === null ? 'built' : entry.build.rung) : ' · not built') + (entry.error === '' ? '' : ' · ' + entry.error)) + if (install.notes.length > 0) { + lines.push('') + for (const note of install.notes) lines.push('Note: ' + note) + } + lines.push('') + lines.push('Next: `comfy_nodes` to read the catalog, `comfy_project` action=new (template= or spec=) to write a project, `comfy_validate` to check one, `comfy_test` action=compile to check them all.') + return { + text: lines.join('\n'), + view: { + ok: true, + install: { found: install.found, app: install.app, base: install.base, baseSource: install.baseSource, version: install.version, python: install.python, models: install.models, modelRoots: install.modelRoots, inventory: stock, customNodes: install.customNodes, configFile: install.configFile }, + server: found.server, + probed: found.probed, + servers: { explicit: found.servers.explicit, origins: found.servers.origins, allowed: found.servers.allowed }, + cli: { found: cli.version.found, command: cli.version.command, version: cli.version.version, facts: cli.facts, which: cli.which }, + catalog: { source: catalogInfo.source, classes: catalogInfo.nodes.size, origin: catalogInfo.origin, version: catalogInfo.version, fetchedAt: catalogInfo.fetchedAt, complete: catalogInfo.complete === true, file: catalog.cacheFile, described: describeCatalog(catalogInfo) }, + caches, + projects: { root, count: projects.length, built: projects.filter((entry) => entry.built).length }, + }, + } + } catch (error) { + return failureOf(error) + } + }, + } + + /** `comfy_nodes`: the catalog in force, by category, by class, or by search. */ + const nodes = { + name: 'comfy_nodes', + description: [ + 'Read the ComfyUI node catalog: `categories` (every category with its class count), `node` (one class\'s exact inputs and outputs - type, whether it is a WIDGET or a LINK, default/min/max and the option list a combo accepts), or `search` (by class, display name, category or description).', + 'This is the catalog a project is compiled and validated against, and every answer says WHERE it came from: a live `/object_info`, a cached catalog from an earlier server, or the built-in core table of eighteen nodes. A class the catalog does not have is not "missing" when the catalog is the core table - it is UNVERIFIED, and the difference decides whether a project can be trusted.', + 'Read-only. Use `node` before wiring an unfamiliar class: the input ORDER is what its `widgets_values` array means.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + properties: { + action: { type: 'string', enum: ['categories', 'node', 'search'], description: 'What to answer. Default categories.' }, + node: { type: 'string', description: 'The class to describe, e.g. KSampler. Required by action=node.' }, + query: { type: 'string', description: 'What to look for (a class name, a display name, a category or a word from a description). Required by action=search.' }, + limit: { type: 'number', description: 'How many search hits: 1-200. Default 40.' }, + }, + }, + output: OUTPUT, + ...present('ComfyUI nodes'), + async execute(args, exec) { + try { + const action = typeof args.action === 'string' ? args.action : 'categories' + const { catalog, server } = await catalogFor(deps, { signal: exec && exec.signal }) + const source = describeCatalog(catalog) + if (action === 'categories') { + const groups = categoriesIn(catalog) + const rows = groups.map((group) => [group.category, String(group.count), group.classes.slice(0, 6).join(', ') + (group.classes.length > 6 ? '…' : '')]) + return { + text: 'Node catalog: ' + source + ' · ' + catalog.nodes.size + ' classes in ' + groups.length + ' categories\n\n' + table(['CATEGORY', 'N', 'EXAMPLES'], rows), + view: { ok: true, source: catalog.source, complete: catalog.complete === true, classes: catalog.nodes.size, categories: groups.map((group) => ({ category: group.category, count: group.count })) }, + } + } + if (action === 'node') { + const wanted = String(args.node ?? '').trim() + if (wanted === '') return refusal('BAD_ARGUMENT', 'action=node needs `node` (a class name, e.g. KSampler).') + const spec = nodeIn(catalog, wanted) + if (spec === null) { + const near = searchCatalog(catalog, wanted, 6) + return refusal('NO_NODE', 'This catalog has no class "' + wanted + '".' + (near.length === 0 ? '' : ' Nearest: ' + near.map((node) => node.class).join(', ') + '.') + (catalog.complete ? '' : ' The catalog in force is the built-in core table (' + catalog.nodes.size + ' classes); start ComfyUI and call `comfy_status` for the full one.'), { classes: near.map((node) => node.class) }) + } + const rows = spec.inputs.map((input) => [ + input.name, + input.type, + input.kind === 'hidden' ? 'hidden' : input.kind, + input.optional ? 'yes' : '', + input.enum === null ? (input.options !== undefined && input.options.default !== undefined ? String(input.options.default) : '') : input.enum.slice(0, 5).join(' | ') + (input.enum.length > 5 ? ' | …(' + input.enum.length + ')' : ''), + ]) + const lines = [] + lines.push(spec.class + ' — ' + spec.displayName + (spec.category === '' ? '' : ' · ' + spec.category) + (spec.outputNode ? ' · OUTPUT NODE' : '') + (spec.deprecated ? ' · deprecated' : '')) + lines.push('catalog: ' + source) + if (spec.description !== '') lines.push('', spec.description) + lines.push('', table(['INPUT', 'TYPE', 'KIND', 'OPT', 'DEFAULT / OPTIONS'], rows)) + if (spec.outputs.length > 0) { + lines.push('', table(['SLOT', 'OUTPUT', 'TYPE'], spec.outputs.map((output, index) => [String(index), output.name, output.type]))) + } else { + lines.push('', 'This class has no outputs (it is an output node: the graph runs to it).') + } + const widgets = widgetInputs(spec) + if (widgets.length > 0) { + const withControl = widgets.filter((input) => input.controlAfterGenerate).map((input) => input.name) + lines.push('', 'widgets_values order: ' + widgets.map((input) => input.name).join(', ') + (withControl.length === 0 ? '' : ' — and an extra control_after_generate value right after ' + withControl.join(', ') + ' ("' + CONTROL_AFTER_GENERATE.join('" / "') + '")')) + } + return { text: lines.join('\n'), view: { ok: true, source: catalog.source, node: spec } } + } + if (action === 'search') { + const query = String(args.query ?? '').trim() + if (query === '') return refusal('BAD_ARGUMENT', 'action=search needs `query`.') + const limit = Number.isFinite(args.limit) ? Math.min(200, Math.max(1, args.limit)) : 40 + const hits = searchCatalog(catalog, query, limit) + if (hits.length === 0) return refusal('NO_MATCH', 'Nothing in this catalog matches "' + query + '". It has ' + catalog.nodes.size + ' classes' + (catalog.complete ? '' : ', and it is the built-in core table rather than a server\'s full catalog') + '.', { source: catalog.source }) + const rows = hits.map((node) => [node.class, node.category, String(node.inputs.filter((input) => input.kind === 'widget').length), String(node.inputs.filter((input) => input.kind === 'link').length), node.outputs.map((output) => output.type).join(',') || (node.outputNode ? 'OUTPUT' : ''), node.outputNode ? 'yes' : '']) + return { + text: table(['CLASS', 'CATEGORY', 'WIDGETS', 'LINKS', 'OUTPUTS', 'OUT NODE'], rows) + '\n\n' + hits.length + ' hit(s) in ' + source, + view: { ok: true, source: catalog.source, query, hits: hits.map((node) => node.class) }, + } + } + return refusal('BAD_ARGUMENT', 'action must be one of categories, node, search.') + } catch (error) { + return failureOf(error) + } + }, + } + + /** `comfy_project`: new, list, show, build, import. */ + const project = { + name: 'comfy_project', + description: [ + 'Work with ComfyUI projects on disk. A project is a FOLDER: `project.json` is the SOURCE (a small readable spec - nodes by KEY, values by NAME, wires by `.`), and `workflow.json` + `prompt.json` + `README.md` + `build.json` are GENERATED from it.', + 'Actions: `new` writes a project from a shipped `template` (see `comfy_test` action=compile for the library) or from an inline `spec` object, and REBINDS the model filenames to what this machine actually has - reporting every rebinding; `list` shows the projects; `show` prints one spec and its build receipt; `build` compiles and writes the generated files; `import` takes a `workflow.json` or an API prompt the app produced and makes a project of it.', + 'A spec value starting with `@` is a BINDING, resolved from `bindings` - that is how a template says "whichever checkpoint this machine has" without freezing a filename into it. `new` picks `@checkpoint` / `@lora` / `@inputImage` from the server\'s own file lists when the declared one is not there; it never guesses between two candidates.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + properties: { + action: { type: 'string', enum: ['new', 'list', 'show', 'build', 'import'], description: 'What to do. Default list.' }, + project: { type: 'string', description: 'A project slug under the workspace projects root (or a path to its folder). Required by show, build and (for the imported name) import.' }, + template: { type: 'string', description: 'For action=new: a shipped example slug (smoke-image, smoke-video, text-to-image, image-to-image).' }, + spec: { type: 'object', description: 'For action=new: the whole spec inline ({ name, title, description, requires, bindings, nodes }). Takes precedence over template.' }, + name: { type: 'string', description: 'For action=new: the folder name (slug). Defaults to the spec\'s own name. For import: the name to give the imported project.' }, + bindings: { type: 'object', description: 'For action=new: overrides for the spec\'s bindings, e.g. {"checkpoint": "sdxl.safetensors", "prompt": "a cat"}. Only the named keys are replaced.' }, + source: { type: 'string', description: 'For action=import: the path to a workflow.json or prompt.json (relative to the workspace).' }, + overwrite: { type: 'boolean', description: 'For action=new: replace an existing project.json. Default false.' }, + dryRun: { type: 'boolean', description: 'For action=build: compile and report without writing the generated files. Default false.' }, + }, + }, + output: OUTPUT, + ...present('ComfyUI project'), + async execute(args, exec) { + try { + const action = typeof args.action === 'string' ? args.action : 'list' + const root = rootOf(deps, exec) + if (action === 'list') { + const projects = listProjects(root) + if (projects.length === 0) { + const examples = listExamples() + return { + text: + 'No projects under ' + + root + + '.\n\nShipped examples you can turn into a project with `comfy_project` action=new template=:\n' + + table(['SLUG', 'NODES', 'NEEDS'], examples.map((entry) => [entry.slug, String(entry.nodes), requirementLine(entry)])) + + '\n\n`comfy_test` action=compile checks them all without writing anything.', + view: { ok: true, root, projects: [], examples: examples.map((entry) => entry.slug) }, + } + } + const rows = projects.map((entry) => [entry.slug, entry.source, String(entry.nodes), entry.built ? (entry.build === null ? 'built' : entry.build.rung) : '—', entry.error === '' ? '' : entry.error]) + return { + text: table(['PROJECT', 'SOURCE', 'NODES', 'BUILT', 'ISSUE'], rows) + '\n\n' + projects.length + ' project(s) in ' + root + '. `comfy_project` action=show project= prints one.', + view: { ok: true, root, projects }, + } + } + if (action === 'new') { + let spec = null + let templateName = '' + if (args.spec !== null && typeof args.spec === 'object' && !Array.isArray(args.spec)) { + spec = args.spec + } else if (typeof args.template === 'string' && args.template !== '') { + templateName = slugify(args.template) + spec = readExample(templateName) + if (spec === null) { + return refusal('NO_TEMPLATE', 'No shipped example "' + args.template + '". Available: ' + listExamples().map((entry) => entry.slug).join(', ') + '.', { examples: listExamples().map((entry) => entry.slug) }) + } + } else { + return refusal('BAD_ARGUMENT', 'action=new needs either `template` (a shipped example) or `spec` (the whole project inline).') + } + const next = JSON.parse(JSON.stringify(spec)) + if (typeof args.name === 'string' && args.name.trim() !== '') next.name = args.name.trim() + next.bindings = next.bindings !== null && typeof next.bindings === 'object' ? next.bindings : {} + if (args.bindings !== null && typeof args.bindings === 'object' && !Array.isArray(args.bindings)) Object.assign(next.bindings, args.bindings) + if (templateName !== '') next.template = templateName + const { catalog } = await catalogFor(deps, { signal: exec && exec.signal }) + const rebound = rebindToCatalog(next, catalog) + const created = createProject({ root, spec: rebound.spec, overwrite: args.overwrite === true }) + const paths = created.paths + const built = buildFromSpec({ raw: readJson(paths.spec), paths, catalog, now: () => new Date().toISOString(), dryRun: false, install: await installFor(deps) }) + const lines = [] + lines.push('Created ' + created.slug + ' at ' + paths.dir) + lines.push(' project.json the spec (the file to edit)') + lines.push(' workflow.json GENERATED — drag it onto the ComfyUI canvas') + lines.push(' prompt.json GENERATED — what comfy_run queues') + lines.push(' build.json the receipt: catalog, rung, findings') + lines.push('') + lines.push('Build: ' + built.rung + ' · ' + built.counts.nodes + ' nodes · ' + built.counts.links + ' links · catalog ' + built.catalog.described) + for (const change of rebound.changes) lines.push(' rebound @' + change.binding + ': "' + change.from + '" -> "' + change.to + '" (' + change.why + ')') + for (const note of rebound.notes) lines.push(' note: ' + note) + const block = findingsBlock(built.findings) + if (block !== '') lines.push('', 'Findings:', block) + lines.push('') + lines.push(built.ok ? 'Next: `comfy_validate` re-checks it without writing, `comfy_run` queues it.' : 'Next: fix the findings above in project.json, then `comfy_project` action=build. `comfy_validate` explains them without writing.') + return { + text: lines.join('\n'), + view: { + ok: true, + project: created.slug, + dir: paths.dir, + rung: built.rung, + built: built.ok, + counts: built.counts, + bindings: rebound.spec.bindings, + rebound: rebound.changes, + notes: rebound.notes, + findings: built.findings, + files: Object.fromEntries(Object.entries(built.files).map(([key, value]) => [key, path.basename(String(value))])), + }, + } + } + if (action === 'show') { + const paths = requireProject(root, args.project) + const spec = readJson(paths.spec) + const build = existsSync(paths.build) ? readJson(paths.build) : null + const lines = [] + lines.push(spec.title !== undefined ? String(spec.title) : path.basename(paths.dir) + ' — ' + paths.dir) + if (typeof spec.description === 'string' && spec.description !== '') lines.push('', spec.description) + lines.push('', 'source: ' + (typeof spec.source === 'string' ? spec.source : 'spec') + ' · ' + (Array.isArray(spec.nodes) ? spec.nodes.length : 0) + ' node(s) in project.json') + if (build !== null) { + lines.push('built: ' + (typeof build.builtAt === 'string' ? build.builtAt : '?') + ' · ' + (typeof build.rung === 'string' ? build.rung : '?') + ' · ' + (build.counts !== null && typeof build.counts === 'object' ? build.counts.nodes + ' nodes, ' + build.counts.errors + ' error(s)' : '') + ' · ' + (build.catalog !== null && typeof build.catalog === 'object' ? build.catalog.described : '')) + } else { + lines.push('built: never — `comfy_project` action=build writes prompt.json and workflow.json') + } + if (spec.source === 'workflow') { + lines.push('', 'This project\'s source is workflow.json (written by ComfyUI). prompt.json is derived from it on every build.') + } else { + lines.push('', 'Nodes:') + for (const node of spec.nodes ?? []) lines.push(' ' + node.key + ' ' + node.class + (node.title === undefined ? '' : ' "' + node.title + '"') + (node.wires === undefined ? '' : ' <- ' + Object.entries(node.wires).map(([input, target]) => input + '=' + target).join(', '))) + const bindings = spec.bindings !== null && typeof spec.bindings === 'object' ? Object.entries(spec.bindings) : [] + if (bindings.length > 0) { + lines.push('', 'Bindings:') + for (const [name, value] of bindings) lines.push(' @' + name + ' = ' + JSON.stringify(value)) + } + } + return { text: lines.join('\n'), view: { ok: true, project: path.basename(paths.dir), spec, build } } + } + if (action === 'build') { + const paths = requireProject(root, args.project) + const { catalog, note } = await catalogFor(deps, { signal: exec && exec.signal }) + const built = buildFromSpec({ raw: readJson(paths.spec), paths, catalog, now: () => new Date().toISOString(), dryRun: args.dryRun === true, install: await installFor(deps) }) + const lines = [] + lines.push((args.dryRun === true ? 'Build (dry run) ' : 'Built ') + path.basename(paths.dir) + ': ' + built.rung + ' · ' + built.counts.nodes + ' nodes · ' + built.counts.links + ' links') + lines.push('catalog: ' + built.catalog.described + (note === '' ? '' : ' (' + note + ')')) + const block = findingsBlock(built.findings) + if (block !== '') lines.push('', 'Findings:', block) + if (args.dryRun !== true) lines.push('', 'Wrote: ' + Object.values(built.files).map((file) => path.basename(String(file))).join(', ')) + lines.push('', built.ok ? 'Next: `comfy_run` queues prompt.json, or drag workflow.json onto the canvas.' : 'Next: fix the findings above, then build again.') + return { text: lines.join('\n'), view: { ok: built.ok, project: path.basename(paths.dir), rung: built.rung, counts: built.counts, findings: built.findings, files: built.files, catalog: built.catalog } } + } + if (action === 'import') { + const source = String(args.source ?? '').trim() + if (source === '') return refusal('BAD_ARGUMENT', 'action=import needs `source`: the path to a workflow.json or prompt.json.') + const file = path.resolve(workspaceOf(deps.ctx, exec, sessionOf(exec)) || process.cwd(), source) + if (!existsSync(file)) return refusal('NO_FILE', 'no file at ' + file + '.') + let raw + try { + raw = JSON.parse(readFileSync(file, 'utf8')) + } catch (error) { + return refusal('BAD_JSON', file + ' is not readable JSON: ' + messageOf(error)) + } + const { catalog } = await catalogFor(deps, { signal: exec && exec.signal }) + const imported = importProject({ root, name: typeof args.name === 'string' ? args.name : path.basename(file, '.json'), source: raw, catalog, now: () => new Date().toISOString() }) + const lines = [] + lines.push('Imported ' + path.basename(file) + ' as project "' + imported.slug + '" (' + imported.kind + ') at ' + imported.paths.dir) + lines.push('Build: ' + imported.report.rung + ' · ' + imported.report.counts.nodes + ' nodes') + const block = findingsBlock(imported.report.findings) + if (block !== '') lines.push('', 'Findings:', block) + if (imported.kind === 'workflow' && imported.report.ok === false) lines.push('', 'A canvas needs the server\'s full node catalog to be lowered to a prompt (widgets_values is an unnamed array). Start ComfyUI, then `comfy_project` action=build again.') + return { text: lines.join('\n'), view: { ok: imported.report.ok, project: imported.slug, kind: imported.kind, rung: imported.report.rung, findings: imported.report.findings, counts: imported.report.counts } } + } + return refusal('BAD_ARGUMENT', 'action must be one of new, list, show, build, import.') + } catch (error) { + return failureOf(error) + } + }, + } + + /** `comfy_validate`: ComfyUI's own checks, offline. */ + const validate = { + name: 'comfy_validate', + description: [ + 'Check a project - or a single workflow.json / prompt.json - against ComfyUI\'s own rules, WITHOUT queueing anything: a class the server does not have, a required input nobody set, a link into a slot that does not exist, a wire whose type does not match, a widget value outside the server\'s list or its min/max, a dependency cycle, a graph with no output node. Every finding carries the `type` string `/prompt` would return (`required_input_missing`, `return_type_mismatch`, `value_not_in_list`, `dependency_cycle`, `prompt_no_outputs`, ...) plus the node KEY and input NAME.', + 'It reports the RUNG it reached: `v2-schema` when the catalog in force is a complete server catalog (the same one the server validates against) and there are no errors, `v1-structural` when it is the built-in core table - structurally sound, but nothing here could confirm the classes exist. A file with a `nodes` array is read as a CANVAS and needs a complete catalog (its `widgets_values` is an unnamed array); a file of `{class_type, inputs}` values is read as a PROMPT and does not.', + 'Read-only: it never writes a project, never queues a prompt, never starts ComfyUI.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + properties: { + project: { type: 'string', description: 'A project slug (or folder path) to validate.' }, + file: { type: 'string', description: 'A workflow.json or prompt.json to validate instead of a project (relative to the workspace).' }, + }, + }, + output: OUTPUT, + ...present('ComfyUI validate'), + async execute(args, exec) { + try { + const hasProject = typeof args.project === 'string' && args.project.trim() !== '' + const hasFile = typeof args.file === 'string' && args.file.trim() !== '' + if (hasProject === hasFile) return refusal('BAD_ARGUMENT', 'pass exactly one of `project` (a slug) or `file` (a workflow.json / prompt.json).') + const { catalog, note } = await catalogFor(deps, { signal: exec && exec.signal }) + if (hasProject) { + const root = rootOf(deps, exec) + const paths = requireProject(root, args.project) + const built = buildFromSpec({ raw: readJson(paths.spec), paths, catalog, dryRun: true, install: await installFor(deps) }) + const lines = [] + lines.push('Validate ' + path.basename(paths.dir) + ': ' + built.rung + ' · ' + built.counts.nodes + ' nodes · ' + (built.ok ? 'no errors' : built.counts.errors + ' error(s), ' + built.counts.warnings + ' warning(s)')) + lines.push('catalog: ' + built.catalog.described + (note === '' ? '' : ' — ' + note)) + const block = findingsBlock(built.findings) + lines.push('') + lines.push(block === '' ? 'No findings. What that proves: ' + (built.rung === 'v2-schema' ? 'every class exists in this server, every required input is set, every wire type matches and every value is in the server\'s list - the same checks /prompt runs.' : 'the graph is structurally sound, against the built-in core table which covers only the nodes the shipped examples use. Start ComfyUI to check the classes themselves.') : block) + const fileCheck = built.fileCheck ?? null + if (fileCheck !== null && fileCheck.checked > 0) lines.push('', 'Files: ' + fileCheck.checked + ' name(s) checked against the install on disk (' + fileCheck.missing + ' missing)' + (fileCheck.roots.length === 0 ? '' : ' in ' + fileCheck.roots.join(', ')) + '.') + else if (fileCheck !== null && fileCheck.skipped !== '') lines.push('', 'Files: none checked - ' + fileCheck.skipped + '.') + lines.push('') + lines.push(built.ok ? 'Next: `comfy_run` queues it (a compiled graph is not a finished render: only /history says what it produced).' : 'Fix these in project.json, then `comfy_project` action=build.') + return { text: lines.join('\n'), view: { ok: built.ok, rung: built.rung, findings: built.findings, counts: built.counts, catalog: built.catalog, project: path.basename(paths.dir) } } + } + const file = path.resolve(workspaceOf(deps.ctx, exec, sessionOf(exec)) || process.cwd(), String(args.file)) + if (!existsSync(file)) return refusal('NO_FILE', 'no file at ' + file + '.') + let raw + try { + raw = JSON.parse(readFileSync(file, 'utf8')) + } catch (error) { + return refusal('BAD_JSON', file + ' is not readable JSON: ' + messageOf(error)) + } + if (raw !== null && typeof raw === 'object' && !Array.isArray(raw) && Array.isArray(raw.nodes)) { + const parsed = parseWorkflow(raw) + const findings = [...parsed.findings] + let prompt = {} + try { + const derived = workflowToPrompt(parsed, catalog) + prompt = derived.prompt + findings.push(...derived.findings) + } catch (error) { + if (!(error instanceof ComfyError)) throw error + findings.push({ severity: 'error', type: error.code, message: error.message }) + } + const validated = Object.keys(prompt).length === 0 ? { findings: [], nodeErrors: {} } : validatePrompt(prompt, catalog) + findings.push(...validated.findings) + const errors = findings.filter((entry) => entry.severity === 'error') + const rung = errors.length > 0 ? 'v0-failed' : catalog.complete === true ? 'v2-schema' : 'v1-structural' + const lines = ['Validate canvas ' + path.basename(file) + ': ' + rung + ' · ' + parsed.nodes.length + ' nodes · ' + (errors.length === 0 ? 'no errors' : errors.length + ' error(s)'), 'catalog: ' + describeCatalog(catalog) + (note === '' ? '' : ' — ' + note), ''] + const block = findingsBlock(findings) + lines.push(block === '' ? 'The canvas lowers to a prompt with no findings.' : block) + return { text: lines.join('\n'), view: { ok: errors.length === 0, rung, kind: 'workflow', findings, nodes: parsed.nodes.length, catalog: describeCatalog(catalog) } } + } + const validated = validatePrompt(raw, catalog) + const errors = validated.findings.filter((entry) => entry.severity === 'error') + const rung = errors.length > 0 ? 'v0-failed' : catalog.complete === true ? 'v2-schema' : 'v1-structural' + const lines = ['Validate prompt ' + path.basename(file) + ': ' + rung + ' · ' + Object.keys(raw).length + ' nodes · ' + (errors.length === 0 ? 'no errors' : errors.length + ' error(s)'), 'catalog: ' + describeCatalog(catalog) + (note === '' ? '' : ' — ' + note), ''] + const block = findingsBlock(validated.findings) + lines.push(block === '' ? 'No findings.' : block) + return { text: lines.join('\n'), view: { ok: errors.length === 0, rung, kind: 'prompt', findings: validated.findings, nodes: Object.keys(raw).length, catalog: describeCatalog(catalog) } } + } catch (error) { + return failureOf(error) + } + }, + } + + /** `comfy_run`: the one tool that queues work. */ + const run = { + name: 'comfy_run', + description: [ + 'Queue a compiled prompt on the ComfyUI server and report what came out: the files `/history` lists (with their `/view` URLs), the node titles that produced them, how long the queue took, and - on failure - the node and the exception. This is the ONLY tool here that executes anything.', + 'It builds a project first (writing `prompt.json`/`workflow.json`) and refuses to queue one that has validation errors: a graph with a missing input is a 400 with `node_errors`, not a render. Pass `file` instead to queue a standalone prompt.json or workflow.json.', + 'A refusal keeps the server\'s own words: `/prompt` answers a rejected graph with `node_errors`, which is the most useful text in the API. Queueing more than ComfyUI can do is not faster - the queue is serial on one GPU - so this waits for its own prompt and reports its own duration.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + properties: { + project: { type: 'string', description: 'A project slug (or folder path) to build and queue.' }, + file: { type: 'string', description: 'A prompt.json or workflow.json to queue instead of a project (relative to the workspace).' }, + waitSeconds: { type: 'number', description: 'How long to wait for the render: 10-3600 s. Default 600. A CPU-only SD 1.5 render at 512px and 4 steps is 10-25 s; a 30-step SDXL render on a CPU is minutes.' }, + }, + }, + output: OUTPUT, + ...present('ComfyUI run'), + async execute(args, exec) { + try { + const hasProject = typeof args.project === 'string' && args.project.trim() !== '' + const hasFile = typeof args.file === 'string' && args.file.trim() !== '' + if (hasProject === hasFile) return refusal('BAD_ARGUMENT', 'pass exactly one of `project` (a slug) or `file` (a prompt.json / workflow.json).') + const install = discoverInstall({ env: deps.env ?? process.env, platform: deps.platform }) + const { catalog, server, probed, note } = await catalogFor(deps, { signal: exec && exec.signal }) + if (server === null) { + return refusal('SERVER_DOWN', noServerText(install, probed) + (note === '' ? '' : '\n(' + note + ')'), { probed }) + } + let prompt = {} + let built = null + let label = '' + if (hasProject) { + const root = rootOf(deps, exec) + const paths = requireProject(root, args.project) + label = path.basename(paths.dir) + built = buildFromSpec({ raw: readJson(paths.spec), paths, catalog, now: () => new Date().toISOString(), dryRun: false, install: await installFor(deps) }) + if (!built.ok) { + return refusal('PROJECT_INVALID', 'not queued: ' + built.counts.errors + ' validation error(s) in ' + label + '. A graph like this is a 400 with `node_errors`, not a render.\n' + findingsBlock(built.findings) + '\nFix them in project.json (or with the app), then run again.', { findings: built.findings, rung: built.rung }) + } + prompt = built.prompt + } else { + const file = path.resolve(workspaceOf(deps.ctx, exec, sessionOf(exec)) || process.cwd(), String(args.file)) + if (!existsSync(file)) return refusal('NO_FILE', 'no file at ' + file + '.') + const raw = readJson(file) + label = path.basename(file) + const looksLikePrompt = raw !== null && typeof raw === 'object' && !Array.isArray(raw) && !Array.isArray(raw.nodes) && Object.values(raw).every((value) => value !== null && typeof value === 'object' && typeof value.class_type === 'string') + if (!looksLikePrompt) { + const parsed = parseWorkflow(raw) + const derived = workflowToPrompt(parsed, catalog) + prompt = derived.prompt + const validated = validatePrompt(prompt, catalog) + const errors = [...derived.findings, ...validated.findings].filter((entry) => entry.severity === 'error') + if (errors.length > 0) return refusal('PROJECT_INVALID', 'not queued: the canvas lowers to a prompt with ' + errors.length + ' error(s).\n' + findingsBlock(errors), { findings: errors }) + } else { + prompt = raw + } + } + const waitMs = (Number.isFinite(args.waitSeconds) ? Math.min(3600, Math.max(10, args.waitSeconds)) : 600) * 1000 + const queued = await queuePrompt(deps, server.origin, prompt, { signal: exec && exec.signal }) + const partial = findingsFromNodeErrors(queued.node_errors) + const waited = await waitForHistory(deps, server.origin, queued.prompt_id, { timeoutMs: waitMs, signal: exec && exec.signal }) + const lines = [] + if (waited.timedOut) { + return refusal( + 'TIMEOUT', + 'Queued as ' + queued.prompt_id + ' on ' + server.origin + ', and it was still not in /history after ' + Math.round(waitMs / 1000) + ' s. That is not a failure - a first run pays the model load, and a CPU render is slow. Ask again with a bigger waitSeconds, or watch the ComfyUI console; `/queue` still lists it if it is waiting.', + { promptId: queued.prompt_id, origin: server.origin, waitedMs: waited.waitedMs }, + ) + } + if (waited.dropped) { + return refusal('DROPPED', 'Queued as ' + queued.prompt_id + ' and it left the queue without a history entry: the server restarted, or the item was deleted. Nothing here retries - run it again.', { promptId: queued.prompt_id }) + } + const entry = waited.entry + const errors = errorsOf(entry) + const files = describeOutputs(entry, prompt) + const statusStr = entry !== null && entry.status !== null && typeof entry.status === 'object' && typeof entry.status.status_str === 'string' ? entry.status.status_str : '' + lines.push(label + ' · ' + (errors.length === 0 && statusStr !== 'error' ? 'completed' : 'FAILED') + ' · ' + formatMilliseconds(waited.waitedMs) + ' · prompt ' + queued.prompt_id) + lines.push('server: ' + server.origin + (server.version === '' ? '' : ' · ComfyUI ' + server.version) + (server.device === '' ? '' : ' · ' + server.device)) + if (partial.length > 0) { + lines.push('', 'The server accepted it with node_errors (those OUTPUT branches will be skipped):') + lines.push(findingsBlock(partial)) + } + if (errors.length > 0) { + lines.push('') + for (const error of errors) { + lines.push('NODE ' + error.node + (error.nodeType === '' ? '' : ' (' + error.nodeType + ')') + (error.exceptionType === '' ? '' : ' raised ' + error.exceptionType) + ':') + lines.push(' ' + (error.message === '' ? '(no message)' : error.message.split('\n').slice(0, 12).join('\n '))) + } + } + if (files.length > 0) { + lines.push('', 'Files (' + files.length + '):') + const install = await installFor(deps) + for (const file of files) { + const onDisk = install.base === '' ? '' : path.join(install.base, 'output', file.subfolder, file.filename) + lines.push(' ' + (file.subfolder === '' ? file.filename : file.subfolder + '/' + file.filename) + ' · ' + file.nodeTitle + ' · ' + server.origin + file.url) + if (onDisk !== '') lines.push(' on disk: ' + onDisk) + } + } else if (errors.length === 0) { + lines.push('', 'No files: the output node saved nothing. A graph runs to its OUTPUT nodes - a preview inside the app is not a saved file.') + } + if (entry !== null && entry.status !== null && typeof entry.status === 'object' && entry.status.completed === false) lines.push('', 'The history entry says completed: false — read the messages above rather than the file list.') + lines.push('', 'Rung: v4-executed (queued and finished with a history entry' + (files.length > 0 ? ' and ' + files.length + ' file(s)' : '') + ').') + return { + text: lines.join('\n'), + view: { + ok: errors.length === 0, + rung: 'v4-executed', + promptId: queued.prompt_id, + origin: server.origin, + waitedMs: waited.waitedMs, + files, + errors, + findings: partial, + status: statusStr, + project: label, + }, + } + } catch (error) { + if (error instanceof ComfyError && error.code === 'HTTP_ERROR' && error.extra && error.extra.body) { + const body = error.extra.body + const findings = findingsFromNodeErrors(body.node_errors) + const sentence = errorSentenceFromResponse(body) + const text = ['The server REFUSED the prompt (HTTP ' + error.extra.status + ').' + (sentence === '' ? '' : ' ' + sentence), findings.length === 0 ? '' : findingsBlock(findings), '', 'This is /prompt\'s own validation - the same checks `comfy_validate` runs offline. Fix the graph, then run again.'].filter((line) => line !== '').join('\n') + return { text, view: { ok: false, code: 'PROMPT_REFUSED', findings, status: error.extra.status, error: body.error ?? null } } + } + return failureOf(error) + } + }, + } + + /** `comfy_test`: the ladder over the shipped library. */ + const test = { + name: 'comfy_test', + description: [ + 'Compile the shipped example library - and optionally the projects in the workspace - and report ONE RUNG per item, so "it compiles" is never printed as "it runs": `v1-structural` (the spec, the wires and the graph are sound, checked against the built-in core table), `v2-schema` (checked against a complete server catalog: every class exists, every value is in the server\'s own list), `v3-queued` (the server accepted it), `v4-executed` (a history entry finished and files came out).', + 'action=compile (the default) writes NOTHING: it compiles every example in memory against the catalog in force. That is the check to run after changing this package, and the one that works on a machine where ComfyUI is not running.', + 'action=run queues each item on a live server and waits for it, one at a time (the ComfyUI queue is serial - a model is loaded on one device). The two model-free smoke examples prove the server, the queue and the output folder work before a 2 GB download is blamed.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + properties: { + action: { type: 'string', enum: ['compile', 'run'], description: 'compile (default, writes nothing) or run (queues each item, needs a server).' }, + examples: { type: 'array', items: { type: 'string' }, description: 'Only these example slugs. Default: every shipped example.' }, + includeProjects: { type: 'boolean', description: 'Also compile the projects in the workspace root. Default false (they are yours, not the library).' }, + waitSeconds: { type: 'number', description: 'For action=run: seconds per item. Default 180, max 3600.' }, + }, + }, + output: OUTPUT, + ...present('ComfyUI test'), + async execute(args, exec) { + try { + const action = typeof args.action === 'string' ? args.action : 'compile' + const only = Array.isArray(args.examples) && args.examples.length > 0 ? args.examples.map((entry) => slugify(entry)) : null + const { catalog, server, probed, note } = await catalogFor(deps, { signal: exec && exec.signal }) + const examples = listExamples() + const chosen = only === null ? examples : examples.filter((entry) => only.includes(entry.slug)) + if (chosen.length === 0) { + return refusal('NO_EXAMPLES', 'No shipped example matches ' + JSON.stringify(args.examples) + '. The library: ' + examples.map((entry) => entry.slug).join(', ') + '.') + } + const root = rootOf(deps, exec) + const items = chosen.map((entry) => ({ slug: entry.slug, kind: 'example', title: entry.title })) + if (args.includeProjects === true) { + for (const entry of listProjects(root)) items.push({ slug: entry.slug, kind: 'project', title: entry.title, paths: projectPaths(root, entry.slug) }) + } + if (action === 'run' && server === null) { + return refusal('SERVER_DOWN', 'action=run needs a ComfyUI server and none answered.\n\n' + noServerText(discoverInstall({ env: deps.env ?? process.env, platform: deps.platform }), probed) + '\n\n`comfy_test` action=compile checks the same library without one.', { probed }) + } + const rows = [] + const results = [] + const waitMs = (Number.isFinite(args.waitSeconds) ? Math.min(3600, Math.max(10, args.waitSeconds)) : 180) * 1000 + for (const item of items) { + if (item.kind === 'example') { + const spec = readExample(item.slug) + const probePaths = { dir: '(in memory)', spec: '', workflow: '', prompt: '', readme: '', build: '' } + const built = buildFromSpec({ raw: spec, paths: probePaths, catalog, dryRun: true, install: await installFor(deps) }) + const firstError = built.findings.find((entry) => entry.severity === 'error') + if (action !== 'run' || firstError !== undefined) { + rows.push([item.slug, built.rung, String(built.counts.nodes), firstError === undefined ? (built.counts.warnings === 0 ? '—' : built.counts.warnings + ' warning(s)') : firstError.type + ': ' + firstError.message.slice(0, 80)]) + results.push({ slug: item.slug, kind: item.kind, rung: built.rung, ok: built.ok, findings: built.findings, counts: built.counts }) + continue + } + // Run: queue it and wait. + const started = Date.now() + try { + const queued = await queuePrompt(deps, server.origin, built.prompt, { signal: exec && exec.signal }) + const waited = await waitForHistory(deps, server.origin, queued.prompt_id, { timeoutMs: waitMs, signal: exec && exec.signal }) + const files = waited.entry === null ? [] : outputsOf(waited.entry) + const errors = waited.entry === null ? [] : errorsOf(waited.entry) + const rung = waited.timedOut ? 'v3-queued' : errors.length === 0 && files.length > 0 ? 'v4-executed' : 'v3-queued' + const why = waited.timedOut ? 'timed out after ' + Math.round(waitMs / 1000) + ' s' : errors.length > 0 ? 'NODE ' + errors[0].node + ': ' + String(errors[0].message).split('\n')[0].slice(0, 90) : files.length === 0 ? 'finished with no files' : String(files.length) + ' file(s)' + rows.push([item.slug, rung, String(built.counts.nodes), formatMilliseconds(Date.now() - started) + ' · ' + why]) + results.push({ slug: item.slug, kind: item.kind, rung, ok: rung === 'v4-executed', promptId: queued.prompt_id, files, errors, waitedMs: Date.now() - started }) + } catch (error) { + const body = error instanceof ComfyError ? error.extra?.body : null + const findings = body === null ? [] : findingsFromNodeErrors(body.node_errors) + const why = findings.length > 0 ? 'REFUSED · ' + findings[0].type + ': ' + findings[0].message.slice(0, 80) : messageOf(error) + rows.push([item.slug, 'v0-failed', String(built.counts.nodes), why]) + results.push({ slug: item.slug, kind: item.kind, rung: 'v0-failed', ok: false, error: messageOf(error), findings }) + } + continue + } + // A workspace project. + const built = buildFromSpec({ raw: readJson(item.paths.spec), paths: item.paths, catalog, dryRun: action !== 'run', install: await installFor(deps) }) + const firstError = built.findings.find((entry) => entry.severity === 'error') + rows.push([item.slug, built.rung, String(built.counts.nodes), firstError === undefined ? (built.counts.warnings === 0 ? '—' : built.counts.warnings + ' warning(s)') : firstError.type + ': ' + firstError.message.slice(0, 80)]) + results.push({ slug: item.slug, kind: item.kind, rung: built.rung, ok: built.ok, findings: built.findings, counts: built.counts }) + } + const passed = results.filter((entry) => entry.ok).length + const lines = [] + lines.push('ComfyUI library · ' + action + (server === null ? ' (offline)' : ' on ' + server.origin) + ' · catalog ' + describeCatalog(catalog)) + if (note !== '') lines.push(' ' + note) + lines.push('') + lines.push(table(['ITEM', 'RUNG', 'NODES', 'RESULT'], rows)) + lines.push('') + lines.push(passed + ' of ' + results.length + ' at the rung they should reach. ' + (action === 'compile' ? 'Nothing was written and nothing was queued.' : 'Each item was queued and awaited in turn.')) + const ladder = results.reduce((counts, entry) => { + counts[entry.rung] = (counts[entry.rung] ?? 0) + 1 + return counts + }, {}) + lines.push('Rungs: ' + RUNGS.filter((rung) => ladder[rung] !== undefined).map((rung) => rung + ' ×' + ladder[rung]).join(' · ') + (ladder['v0-failed'] === undefined ? '' : ' · v0-failed ×' + ladder['v0-failed'])) + if (ladder['v1-structural'] !== undefined) lines.push('v1-structural means the graph is sound but no server catalog confirmed the classes: start ComfyUI for v2.') + return { + text: lines.join('\n'), + view: { ok: results.every((entry) => entry.rung !== 'v0-failed'), action, origin: server === null ? '' : server.origin, catalog: describeCatalog(catalog), results, rungs: ladder, passed, total: results.length }, + } + } catch (error) { + return failureOf(error) + } + }, + } + + /** + * `comfy_cli`: the second test path, through comfy-cli. + * + * It is not a convenience wrapper. `comfy run --workflow` converts a UI + * canvas itself, submits it and waits - so running the workflow this package + * GENERATED through a program that never saw its compiler is an independent + * check on the canvas, and `comfy node deps-in-workflow` answers the one + * question a project cannot answer by itself: which custom nodes it needs + * before it is opened at all. + */ + /** + * `comfy_cli`: the second test path, through comfy-cli. + * + * It is not a convenience wrapper. `comfy run --workflow` converts a UI canvas + * itself, submits it and waits - so running the workflow this package + * GENERATED through a program that never saw its compiler is an independent + * check on the canvas. `comfy node deps-in-workflow` answers the one question a + * project cannot answer by itself: which custom nodes it needs before it is + * opened at all. + * + * TWO PRE-FLIGHT REFUSALS, both measured on 1.29.0 and both reported as + * sentences rather than raw stderr: + * - no workspace: comfy-cli's default is `/comfy/ComfyUI`, which on a + * Desktop machine does not exist. This row passes `--workspace` naming the + * tree `comfy_status` found, so the command has a chance; + * - no ComfyUI-Manager in that workspace: `deps-in-workflow` resolves node + * packs through the Manager's `cm-cli`, and a Desktop install keeps its + * Manager inside the app. `comfy run --workflow` does not need it. + */ + const cli = { + name: 'comfy_cli', + description: [ + 'Drive comfy-cli (`comfy`, from `pip install comfy-cli`) - the cross-platform way to set up, launch and run ComfyUI on Windows, macOS and Linux, and the second opinion on a workflow this package wrote.', + 'Actions: `status` (the CLI version, its own `env` view - workspace and whether it EXISTS, the Desktop installs it knows, the running server, the GPU - and `which`); `deps` (`comfy node deps-in-workflow` on a project\'s workflow.json: the custom nodes and model files it needs); `run` (`comfy run --workflow --wait`, which converts a UI canvas itself and submits it - an independent check on the graph, and the only path that works when this row cannot reach the API); `launch` (`comfy launch --background`, so a server exists to test against); `stop` (`comfy stop`).', + 'Every call is an argv array with the global `--json` BEFORE the subcommand, no shell, and a deadline. When `workspace` is not given and comfy-cli\'s own default does not exist, this passes `--workspace` naming the install `comfy_status` found - otherwise `comfy node ...` refuses with "not a valid ComfyUI workspace" on every Desktop machine.', + 'It NEVER runs `comfy install`, installs a node, downloads a model or removes anything: those change a person\'s machine, and the `comfyui-cli` skill names each command so the person decides.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + properties: { + action: { type: 'string', enum: ['status', 'deps', 'run', 'launch', 'stop'], description: 'What to do. Default status.' }, + project: { type: 'string', description: 'For deps and run: a project slug. Its workflow.json is built first when it is missing or stale.' }, + file: { type: 'string', description: 'For deps and run: a workflow.json path instead of a project.' }, + workspace: { type: 'string', description: 'The ComfyUI tree comfy-cli should act on. Default: the one comfy_status found, when comfy-cli\'s own default does not exist.' }, + timeoutSeconds: { type: 'number', description: 'For run: how long the CLI may take. Default 900, max 3600. For launch: default 120.' }, + download: { type: 'boolean', description: 'For run: after the CLI reports a prompt_id, fetch the outputs with `comfy download` into the project folder. Default false.' }, + }, + }, + output: OUTPUT, + ...present('comfy-cli'), + async execute(args, exec) { + try { + const env = deps.env ?? process.env + const action = typeof args.action === 'string' ? args.action : 'status' + if (typeof deps.runner !== 'function') return refusal('NO_RUNNER', 'this row has no process runner, so comfy-cli cannot be driven.') + const command = cliCommand(env) + const version = await cliVersion(deps.runner, env) + const missingText = + 'No usable comfy-cli: `' + + command + + '` did not answer' + + (version.error === '' ? '' : ' (' + version.error + ')') + + '.\n\nInstall it with `pip install comfy-cli` (Python 3.10+, Windows/macOS/Linux), then `comfy setup -y`. It also accepts a binary PATH does not carry: set DSH_COMFY_CLI to its full path.\n\nThe seven HTTP tools need none of it: `comfy_status`, `comfy_nodes`, `comfy_project`, `comfy_validate`, `comfy_run` and `comfy_test` work with the ComfyUI app alone. It adds `comfy launch --background` (a server to test against), `comfy run --workflow` (an independent run of the generated canvas) and `comfy node deps-in-workflow` (which node packs a graph needs).' + + const envAnswer = version.found ? await cliJson(deps.runner, ['env'], { env, command }) : null + const facts = envAnswer === null ? null : envFacts(envAnswer.data) + const whichAnswer = version.found ? await cliJson(deps.runner, ['which'], { env, command }) : null + const which = whichAnswer === null ? null : whichFacts(whichAnswer.data) + + if (action === 'status') { + if (!version.found) return refusal('CLI_MISSING', missingText, { command }) + const lines = ['comfy-cli ' + version.version + ' (' + command + ')'] + const workspacePath = which !== null && which.workspace !== '' ? which.workspace : facts === null ? '' : facts.workspace + const exists = which !== null && which.exists !== null ? which.exists : facts === null ? null : facts.workspaceExists + if (workspacePath !== '') lines.push('workspace: ' + workspacePath + (exists === true ? '' : exists === false ? ' (DOES NOT EXIST)' : '')) + if (facts !== null && facts.workspaceType !== '') lines.push('workspace type: ' + facts.workspaceType) + if (facts !== null && facts.python !== '') lines.push('python: ' + facts.python + (facts.pythonVersion === '' ? '' : ' (' + facts.pythonVersion + ')')) + if (facts !== null && facts.serverRunning !== null) lines.push('server: ' + (facts.serverRunning ? 'RUNNING' + (facts.serverUrl === '' ? '' : ' at ' + facts.serverUrl) : 'not running')) + if (facts !== null && facts.gpu !== '') lines.push('hardware: ' + facts.gpu + (facts.vramBytes === null ? '' : ' · ' + formatBytes(facts.vramBytes) + ' VRAM') + (facts.ramBytes === null ? '' : ' · ' + formatBytes(facts.ramBytes) + ' RAM')) + if (facts !== null && facts.installs.length > 0) { + lines.push('') + lines.push('Desktop installs comfy-cli knows about:') + for (const install of facts.installs) { + lines.push(' ' + (install.name === '' ? '(unnamed)' : install.name) + (install.exists ? '' : ' [the folder is GONE]') + ' · code ' + (install.codeDir === '' ? '?' : install.codeDir) + (install.dataDir === '' ? '' : ' · data ' + install.dataDir)) + } + } + if (facts !== null && facts.managerMode !== '') { + lines.push('') + lines.push('ComfyUI-Manager: ' + facts.managerMode + (facts.managerMode === 'not-installed' ? ' — `comfy node install` and `node deps-in-workflow` need it; `comfy run` does not' : '')) + } + if (facts !== null && facts.warnings.length > 0) { + lines.push('') + for (const warning of facts.warnings) lines.push('warning: ' + warning.message) + } + lines.push('') + lines.push('`comfy launch --background` starts a server comfy-cli manages; `comfy stop` stops it. `comfy_cli` action=deps answers which custom nodes a project needs; action=run tests the generated canvas through the CLI itself.') + return { + text: lines.join('\n'), + view: { + ok: true, + command, + version: version.version, + workspace: workspacePath, + workspaceExists: exists, + which: which === null ? '' : which.workspace, + comfyuiVersion: facts === null ? '' : facts.comfyuiVersion, + python: facts === null ? '' : facts.python, + serverRunning: facts === null ? null : facts.serverRunning, + serverUrl: facts === null ? '' : facts.serverUrl, + gpu: facts === null ? '' : facts.gpu, + vramBytes: facts === null ? null : facts.vramBytes, + managerMode: facts === null ? '' : facts.managerMode, + installs: facts === null ? [] : facts.installs, + warnings: facts === null ? [] : facts.warnings, + envOk: envAnswer !== null && envAnswer.ok, + }, + } + } + if (!version.found) return refusal('CLI_MISSING', missingText, { command }) + + /** + * The workspace to pass. comfy-cli's own default is a guess that is + * usually wrong on a Desktop machine, and its refusal happens BEFORE it + * reads the graph, so a real tree is the difference between working and + * a message about `comfy install`. + */ + const workspaceFor = async () => { + if (typeof args.workspace === 'string' && args.workspace.trim() !== '') return { workspace: args.workspace.trim(), why: 'the `workspace` you gave' } + const exists = which !== null && which.exists !== null ? which.exists : facts === null ? true : facts.workspaceExists + if (exists === true) return { workspace: '', why: '' } + const install = await installFor(deps) + if (install.app !== '') return { workspace: install.app, why: "comfy-cli's own workspace does not exist, so this passes the install comfy_status found" } + if (install.base !== '') return { workspace: install.base, why: "comfy-cli's own workspace does not exist, so this passes the base path comfy_status found" } + return { workspace: '', why: '' } + } + + // deps and run both need a workflow FILE, which is what the CLI reads. + let workflowFile = '' + let label = '' + if (action === 'deps' || action === 'run') { + const hasProject = typeof args.project === 'string' && args.project.trim() !== '' + const hasFile = typeof args.file === 'string' && args.file.trim() !== '' + if (hasProject === hasFile) return refusal('BAD_ARGUMENT', 'pass exactly one of `project` (a slug) or `file` (a workflow.json).') + if (hasProject) { + const root = rootOf(deps, exec) + const paths = requireProject(root, args.project) + const { catalog } = await catalogFor(deps, { signal: exec && exec.signal }) + const raw = readJson(paths.spec) + if (raw !== null && typeof raw === 'object' && raw.source === 'workflow') { + workflowFile = paths.workflow + } else { + const built = buildFromSpec({ raw, paths, catalog, now: () => new Date().toISOString(), dryRun: false, install: await installFor(deps) }) + if (!built.ok) return refusal('PROJECT_INVALID', 'not handed to the CLI: ' + built.counts.errors + ' validation error(s) in ' + path.basename(paths.dir) + '.\n' + findingsBlock(built.findings), { findings: built.findings }) + workflowFile = paths.workflow + } + label = path.basename(paths.dir) + if (!existsSync(workflowFile)) return refusal('NO_WORKFLOW', 'this project has no workflow.json yet (' + workflowFile + '). `comfy_project` action=build writes it.', { path: workflowFile }) + } else { + workflowFile = path.resolve(workspaceOf(deps.ctx, exec, sessionOf(exec)) || process.cwd(), String(args.file)) + label = path.basename(workflowFile) + if (!existsSync(workflowFile)) return refusal('NO_FILE', 'no file at ' + workflowFile + '.') + } + } + + if (action === 'deps') { + const where = await workspaceFor() + const outFile = path.join(path.dirname(workflowFile), '.deps.json') + const answer = await cliJson(deps.runner, ['node', 'deps-in-workflow', '--workflow=' + workflowFile, '--output=' + outFile], { env, command, workspace: where.workspace, timeoutMs: 180000 }) + const lines = ['comfy node deps-in-workflow · ' + label] + if (where.why !== '') lines.push(' ' + where.why + (where.workspace === '' ? '' : ': ' + where.workspace)) + lines.push('exit code: ' + (answer.status === null ? 'n/a' : answer.status) + (answer.envelope !== null ? ' · envelope ok=' + String(answer.envelope.ok) : '')) + const explained = explainCliFailure(String(answer.stderr ?? '') + '\n' + String(answer.error ?? '')) + if (explained !== '') lines.push('', explained) + let parsed = null + try { + parsed = existsSync(outFile) ? JSON.parse(readFileSync(outFile, 'utf8')) : null + } catch (error) { + parsed = null + } + if (parsed !== null && typeof parsed === 'object') { + const nodes = collectNames(parsed, /custom_?nodes?|nodes?|packs?/i) + const models = collectNames(parsed, /models?|checkpoints?|loras?/i) + if (nodes.length > 0) lines.push('', 'custom nodes it needs: ' + nodes.join(', ')) + if (models.length > 0) lines.push('model files it names: ' + models.join(', ')) + if (nodes.length === 0 && models.length === 0) lines.push('', 'the deps file has no node or model list this row recognises; its keys: ' + Object.keys(parsed).join(', ')) + const { catalog } = await catalogFor(deps, { signal: exec && exec.signal }) + const known = nodes.filter((name) => nodeIn(catalog, name) !== null) + if (nodes.length > 0) lines.push('of those, ' + known.length + ' name(s) match a node CLASS in the catalog (' + describeCatalog(catalog) + ')' + (known.length === 0 ? ' - expected: a deps list names node PACKS, not classes' : '')) + } else { + if (answer.stdout !== '') lines.push('', 'the CLI said:', answer.stdout.split('\n').slice(-8).join('\n')) + if (answer.stderr !== '') lines.push('', 'stderr:', answer.stderr.split('\n').slice(-8).join('\n')) + } + return { text: lines.join('\n'), view: { ok: answer.ok, exitCode: answer.status, workflow: workflowFile, workspace: where.workspace, deps: parsed, error: answer.error } } + } + + if (action === 'run') { + const where = await workspaceFor() + const timeoutMs = (Number.isFinite(args.timeoutSeconds) ? Math.min(3600, Math.max(30, args.timeoutSeconds)) : Math.round(RUN_TIMEOUT_MS / 1000)) * 1000 + const started = Date.now() + const result = await deps.runner(runArgv(command, workflowFile, { workspace: where.workspace }), { timeoutMs, env }) + const elapsed = Date.now() - started + if (result === null || result.status === null) return refusal('CLI_FAILED', 'comfy did not start: ' + (result === null ? 'no result' : result.error ?? 'unknown') + '.') + const text = (String(result.stdout ?? '') + '\n' + String(result.stderr ?? '')).trim() + const promptId = promptIdFromRunText(String(result.stdout ?? '')) + const lines = ['comfy run --workflow ' + label + ' --wait'] + if (where.why !== '') lines.push(' ' + where.why + (where.workspace === '' ? '' : ': ' + where.workspace)) + lines.push('exit code ' + result.status + (result.timedOut ? ' (KILLED at the ' + Math.round(timeoutMs / 1000) + ' s deadline)' : '') + ' · ' + formatMilliseconds(elapsed)) + if (promptId !== '') lines.push('prompt_id: ' + promptId) + const explained = explainCliFailure(text) + if (explained !== '') lines.push('', explained) + const tail = text.split('\n').slice(-24).join('\n') + if (tail !== '') lines.push('', tail) + if (args.download === true && promptId !== '' && result.status === 0) { + const outDir = path.join(path.dirname(workflowFile), 'outputs') + const fetched = await deps.runner([command, 'download', promptId, '-o', outDir], { timeoutMs: 300000, env }) + lines.push('', 'comfy download -> ' + outDir + ' · exit code ' + (fetched === null ? 'n/a' : fetched.status) + (fetched !== null && String(fetched.stdout ?? '').trim() !== '' ? '\n' + String(fetched.stdout).trim().split('\n').slice(-10).join('\n') : '')) + } else if (promptId !== '') { + lines.push('', 'the CLI submitted the job itself; `comfy download ' + promptId + ' -o ` fetches the files, or pass download:true.') + } + lines.push('', 'Rung: ' + (result.status === 0 ? 'v4-executed via comfy-cli' : 'v0-failed via comfy-cli') + ' — the CLI converted the canvas, submitted it and waited, so this is an independent run of the graph comfy_project generated.') + return { text: lines.join('\n'), view: { ok: result.status === 0, rung: result.status === 0 ? 'v4-executed' : 'v0-failed', exitCode: result.status, elapsedMs: elapsed, promptId, workflow: workflowFile, workspace: where.workspace, explanation: explained, timedOut: result.timedOut === true } } + } + + if (action === 'launch') { + const timeoutMs = (Number.isFinite(args.timeoutSeconds) ? Math.min(900, Math.max(10, args.timeoutSeconds)) : 120) * 1000 + const where = await workspaceFor() + const result = await deps.runner(launchArgv(command, { workspace: where.workspace }), { timeoutMs, env }) + const text = (String(result.stdout ?? '') + '\n' + String(result.stderr ?? '')).trim() + if (result === null || result.status === null) return refusal('CLI_FAILED', 'comfy did not start: ' + (result === null ? 'no result' : result.error ?? 'unknown') + '.') + const probe = await findServer(deps, { timeoutMs: 5000, signal: exec && exec.signal }) + const lines = ['comfy launch --background · exit code ' + result.status + (result.timedOut ? ' (timed out)' : '')] + if (where.why !== '') lines.push(' ' + where.why + (where.workspace === '' ? '' : ': ' + where.workspace)) + const explained = explainCliFailure(text) + if (explained !== '') lines.push('', explained) + if (text !== '') lines.push('', text.split('\n').slice(-16).join('\n')) + lines.push('') + if (probe.server !== null) lines.push('A server answers now at ' + probe.server.origin + (probe.server.version === '' ? '' : ' · ComfyUI ' + probe.server.version) + '. `comfy_status` and `comfy_run` can use it.') + else lines.push('No server answered yet at ' + probe.probed.map((entry) => entry.origin).join(', ') + '. A background launch loads models on first use, so give it a moment and call `comfy_status`.') + return { text: lines.join('\n'), view: { ok: result.status === 0, exitCode: result.status, server: probe.server, probed: probe.probed, workspace: where.workspace } } + } + + if (action === 'stop') { + const result = await deps.runner(stopArgv(command), { timeoutMs: 60000, env }) + const text = (String(result.stdout ?? '') + '\n' + String(result.stderr ?? '')).trim() + return { + text: 'comfy stop · exit code ' + (result === null ? 'n/a' : result.status) + (text === '' ? '' : '\n\n' + text.split('\n').slice(-12).join('\n')), + view: { ok: result !== null && result.status === 0, exitCode: result === null ? null : result.status }, + } + } + return refusal('BAD_ARGUMENT', 'action must be one of status, deps, run, launch, stop.') + } catch (error) { + return failureOf(error) + } + }, + } + return [status, nodes, project, validate, run, test, cli] +} + +/** Every string a deps file lists under a matching key, deduplicated. */ +function collectNames(value, keyPattern, depth = 0) { + const found = [] + if (value === null || typeof value !== 'object' || depth > 4) return found + for (const [key, entry] of Object.entries(value)) { + if (keyPattern.test(key)) { + const list = Array.isArray(entry) ? entry : [entry] + for (const item of list) { + if (typeof item === 'string' && item !== '') found.push(item) + else if (item !== null && typeof item === 'object') { + const name = typeof item.name === 'string' ? item.name : typeof item.id === 'string' ? item.id : typeof item.url === 'string' ? item.url : '' + if (name !== '') found.push(name) + } + } + continue + } + if (entry !== null && typeof entry === 'object') found.push(...collectNames(entry, keyPattern, depth + 1)) + } + return [...new Set(found)] +} diff --git a/packages/dsh-comfyui/package.json b/packages/dsh-comfyui/package.json new file mode 100644 index 0000000..7fbbc12 --- /dev/null +++ b/packages/dsh-comfyui/package.json @@ -0,0 +1,30 @@ +{ + "name": "dsh-comfyui", + "version": "0.1.0-alpha.1", + "description": "ComfyUI as a surface the agent can BUILD against: seven `comfy_*` tools over the machine's own ComfyUI (Desktop, portable or a server on loopback) that turn a small, readable project spec into a real workflow.json + prompt.json, validate it against the live node catalog the server reports (`/object_info`) with ComfyUI's own error vocabulary, queue it (`/prompt`) and report what came out of `/history`, and a `comfy_test` that compiles the whole shipped example library and, when a server answers, runs it - each item reporting the rung it actually reached (v1-structural, v2-schema, v3-queued, v4-executed). Seven tools: comfy_status, comfy_nodes, comfy_project, comfy_validate, comfy_run, comfy_test and comfy_cli (which drives the user's own comfy-cli as a second test path and never installs anything). Six bundled skills teach the fundamentals, the two workflow formats, the HTTP API as this install has it, comfy-cli across platforms, authoring a node CLASS, and the project dialect. Host-only: one row, no route, no browser half, zero npm dependencies, no bundled engine, nothing started on its own.", + "type": "module", + "main": "lib/index.js", + "exports": { + ".": "./lib/index.js", + "./package.json": "./package.json" + }, + "files": [ + "lib", + "examples", + "skills", + "checks", + "cordis.patch.yml" + ], + "scripts": { + "check": "node checks/check-comfyui-node.mjs" + }, + "engines": { + "node": ">=22" + }, + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + } + }, + "license": "AGPL-3.0-only" +} diff --git a/packages/dsh-comfyui/skills/comfyui-api/SKILL.md b/packages/dsh-comfyui/skills/comfyui-api/SKILL.md new file mode 100644 index 0000000..0427b75 --- /dev/null +++ b/packages/dsh-comfyui/skills/comfyui-api/SKILL.md @@ -0,0 +1,343 @@ +--- +name: comfyui-api +description: The ComfyUI HTTP API as this install actually has it - the port ComfyUI Desktop uses instead of 8188, /system_stats, /object_info, POST /prompt and the exact node_errors body that rejects a graph, /history and the status.messages events a failure hides in, /queue, /view, /upload/image, /models, /api/jobs and the WebSocket - with curl, Python and JavaScript examples and the twelve validation error types. +whenToUse: Talking to a ComfyUI server directly (curl, fetch, urllib, a script), reading a 400 from /prompt, polling for a finished render, listing the models or node classes a server has, or debugging why a request that "should" work is refused. +--- + +# The API, as a server answers it + +Everything the app does, it does over HTTP to its own server. Two ports matter: + +- **8188** — the default for `python main.py`. +- **8000 and up** — what **ComfyUI Desktop** picks. A probe that only tries 8188 + reports "not running" on a machine where the app is open. Try 8000, 8001, + 8002, 8003. + +`comfy_status` probes both families and prints the origin that answered. + +```bash +curl -s http://127.0.0.1:8188/system_stats +``` + +```json +{ + "system": { + "os": "nt", + "ram_total": 17179869184, + "ram_free": 6442450944, + "comfyui_version": "0.21.1", + "python_version": "3.12.11 (main, ...)", + "pytorch_version": "2.9.0+cu128", + "argv": ["main.py", "--listen", "127.0.0.1"] + }, + "devices": [ + { "name": "cuda:0 NVIDIA GeForce RTX 4060", "type": "cuda", "index": null, + "vram_total": 8589934592, "vram_free": 6871947673, + "torch_vram_total": 8589934592, "torch_vram_free": 6871947673 } + ] +} +``` + +`/system_stats` is the only reliable "is it up" probe: it is answered by the +engine, and it carries the version, the device and the VRAM every later decision +needs. + +## The endpoints + +| Method | Path | Answers | +|---|---|---| +| GET | `/system_stats` | version, device, VRAM, RAM, argv | +| GET | `/object_info` | **every node class**: inputs, outputs, defaults, option lists | +| GET | `/object_info/{class}` | one class, same shape | +| POST | `/prompt` | queue a prompt; `{prompt_id, number, node_errors}` | +| GET | `/prompt` | the queue's own summary | +| GET | `/history` | finished prompts, most recent first | +| GET | `/history/{prompt_id}` | one finished prompt, or `{}` | +| GET | `/queue` | `{queue_running, queue_pending}` | +| POST | `/queue` | `{"clear": true}` or `{"delete": [""]}` | +| POST | `/interrupt` | stop the running prompt (optional `{"prompt_id": "..."}`) | +| POST | `/free` | `{"unload_models": true, "free_memory": true}` | +| GET | `/view?filename=&subfolder=&type=output` | the bytes of one artifact | +| POST | `/upload/image` | multipart upload into `input/` | +| GET | `/models` | every model folder name | +| GET | `/models/{folder}` | the filenames in one folder | +| GET | `/embeddings` | textual inversions | +| GET | `/features` | server feature flags | +| GET | `/api/jobs?status=&limit=&offset=` | the job view (see below) | +| GET | `/ws?clientId=` | the event stream the frontend uses | + +## `/object_info` is the schema + +This is the call that makes anything else possible: it is the only authority on +which inputs are **widgets** (values typed in) rather than **links** (wires), and +on what a combo's options are on THIS machine. + +```bash +curl -s "http://127.0.0.1:8188/object_info/KSampler" +``` + +```json +{ + "KSampler": { + "input": { + "required": { + "model": ["MODEL", { "tooltip": "The model used to denoise the input latent." }], + "seed": ["INT", { "default": 0, "min": 0, "max": 18446744073709551615, "control_after_generate": true }], + "steps": ["INT", { "default": 20, "min": 1, "max": 10000 }], + "cfg": ["FLOAT", { "default": 8.0, "min": 0.0, "max": 100.0, "step": 0.1 }], + "sampler_name": [["euler", "euler_ancestral", "dpmpp_2m", "lcm"], {}], + "scheduler": [["normal", "karras", "sgm_uniform"], {}], + "positive": ["CONDITIONING", {}], + "negative": ["CONDITIONING", {}], + "latent_image": ["LATENT", {}], + "denoise": ["FLOAT", { "default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01 }] + } + }, + "input_order": { "required": ["model", "seed", "steps", "cfg", "sampler_name", "scheduler", "positive", "negative", "latent_image", "denoise"] }, + "output": ["LATENT"], + "output_name": ["LATENT"], + "output_node": false, + "name": "KSampler", + "display_name": "KSampler", + "category": "sampling" + } +} +``` + +Read it like this: + +- an input is `[type, options]`; **a type that is an ARRAY is a combo** whose + options are on this machine right now (`ckpt_name`, `lora_name`, `image`); +- the string `"COMBO"` is the newer spelling of the same thing, with the options + under `options.options` (V3 nodes such as `RepeatImageBatch` answer this way); +- `input_order` is the order `widgets_values` uses; +- `control_after_generate: true` adds one extra value to `widgets_values` right + after that input; +- `forceInput: true` makes a widget link-only; +- `"hidden"` inputs (`prompt`, `extra_pnginfo`, `unique_id`) are filled by the + server and must never be sent. + +The catalog is version-specific — install a node pack and it changes. Never ship +a snapshot as truth; read it, and cache it only for a server that has since +stopped. + +## POST /prompt + +```bash +curl -s -X POST http://127.0.0.1:8188/prompt \ + -H "Content-Type: application/json" \ + -d '{"prompt": {"1": {"class_type": "EmptyImage", "inputs": {"width": 512, "height": 512, "batch_size": 1, "color": 0}}, "2": {"class_type": "SaveImage", "inputs": {"filename_prefix": "api/smoke", "images": ["1", 0]}}}, "client_id": "my-script"}' +``` + +Accepted: + +```json +{ "prompt_id": "1f9c0c1e-8f3d-4a3f-a9a3-0c0a3f2b7d11", "number": 3, "node_errors": {} } +``` + +Rejected — HTTP **400**, and the body is the useful part: + +```json +{ + "error": { + "type": "prompt_outputs_failed_validation", + "message": "Prompt outputs failed validation", + "details": "", + "extra_info": {} + }, + "node_errors": { + "1": { + "errors": [ + { + "type": "value_not_in_list", + "message": "Value not in list", + "details": "ckpt_name: 'sd15.safetensors' not in ['v1-5-pruned-emaonly-fp16.safetensors']", + "extra_info": { "input_name": "ckpt_name", "received_value": "sd15.safetensors" } + } + ], + "dependent_outputs": ["2"], + "class_type": "CheckpointLoaderSimple" + } + } +} +``` + +The twelve `type` strings the validator produces, and what each means: + +| `type` | Meaning | +|---|---| +| `prompt_no_outputs` | no OUTPUT node anywhere in the prompt | +| `missing_node_type` | a node has no `class_type`, or the class does not exist here | +| `required_input_missing` | a required input is not set | +| `bad_linked_input` | a wire is not a `[id, slot]` pair, or points at a node that is not in the prompt | +| `return_type_mismatch` | the source output's type does not match the input's | +| `invalid_input_type` | a value cannot be converted to the declared type | +| `value_smaller_than_min` | below the input's `min` | +| `value_bigger_than_max` | above the input's `max` | +| `value_not_in_list` | a combo value the server does not have | +| `dependency_cycle` | the graph waits on itself | +| `custom_validation_failed` | the node's own `VALIDATE_INPUTS` said no | +| `exception_during_validation` | validating the node raised | + +`dependent_outputs` names the output nodes that would have used the broken node +— which is how you tell "this breaks the save" from "this breaks an optional +branch". + +## GET /history/{prompt_id} + +Polling this is how a script learns a render finished; the WebSocket is how the +app learns it first. + +```json +{ + "prompt_id": { + "prompt": [3, "prompt_id", { "1": { "class_type": "SaveImage", "inputs": {} } }, {}, ["2"]], + "outputs": { + "2": { "images": [ { "filename": "smoke_00001_.png", "subfolder": "dsh-comfyui", "type": "output" } ] } + }, + "status": { + "status_str": "success", + "completed": true, + "messages": [ + ["execution_start", { "prompt_id": "prompt_id", "timestamp": 1764290000000 }], + ["execution_cached", { "nodes": ["1"], "prompt_id": "prompt_id", "timestamp": 1764290000001 }], + ["execution_success", { "prompt_id": "prompt_id", "timestamp": 1764290002100 }] + ] + } + } +} +``` + +- **`outputs` is keyed by node id**, and the inner key depends on the node: + `images` for `SaveImage`, `audio` for `SaveAudio`, `video` (or `images`) for + `SaveVideo`. Read it generically: any array of `{filename, subfolder, type}` + is a saved artifact. +- **an empty object means "not finished yet"** — `/history/{id}` answers `{}` + until the item reaches the front of the queue and completes. +- **the failure is inside `status.messages`**, as an `execution_error` entry + with `node_id`, `node_type`, `exception_message`, `exception_type` and a + `traceback`. `status_str` is `"error"` and `completed` is `false`. +- `execution_interrupted` is a cancel, not a crash. + +A prompt that leaves the queue without ever appearing in `/history` was dropped: +the server restarted, or the item was deleted. + +## Artifacts: /view + +```bash +curl -s -o out.png "http://127.0.0.1:8188/view?filename=smoke_00001_.png&subfolder=dsh-comfyui&type=output" +``` + +`type` is `output` for saved files, `temp` for previews and `input` for uploaded +ones. `subfolder` is the prefix folder a `filename_prefix` like +`dsh-comfyui/smoke` created. + +## A polling loop, in the two languages you will actually use + +```js +const base = 'http://127.0.0.1:8188' +const prompt = { + '1': { class_type: 'EmptyImage', inputs: { width: 512, height: 512, batch_size: 1, color: 0 } }, + '2': { class_type: 'SaveImage', inputs: { filename_prefix: 'api/smoke', images: ['1', 0] } }, +} +const queued = await fetch(base + '/prompt', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ prompt, client_id: 'my-script' }), +}).then(async (response) => { + const body = await response.json() + if (!response.ok) throw new Error(JSON.stringify(body.node_errors)) + return body +}) +for (;;) { + const history = await fetch(base + '/history/' + queued.prompt_id).then((response) => response.json()) + const entry = history[queued.prompt_id] + if (entry !== undefined) { + const status = entry.status + const files = Object.values(entry.outputs ?? {}).flatMap((output) => Object.values(output).flat()) + console.log(status.status_str, status.completed, files.map((file) => file.filename)) + break + } + await new Promise((resolve) => setTimeout(resolve, 500)) +} +``` + +```python +import json, time, urllib.request + +BASE = "http://127.0.0.1:8188" + +def post(path, body): + request = urllib.request.Request( + BASE + path, + data=json.dumps(body).encode("utf-8"), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request) as response: + return json.loads(response.read()) + except urllib.error.HTTPError as error: + detail = json.loads(error.read()) + raise SystemExit(f"refused: {detail.get('node_errors')}") + +prompt = { + "1": {"class_type": "EmptyImage", "inputs": {"width": 512, "height": 512, "batch_size": 1, "color": 0}}, + "2": {"class_type": "SaveImage", "inputs": {"filename_prefix": "api/smoke", "images": ["1", 0]}}, +} +queued = post("/prompt", {"prompt": prompt, "client_id": "my-script"}) +prompt_id = queued["prompt_id"] + +while True: + with urllib.request.urlopen(f"{BASE}/history/{prompt_id}") as response: + history = json.loads(response.read()) + if prompt_id in history: + status = history[prompt_id]["status"] + for node_id, output in history[prompt_id]["outputs"].items(): + for key, files in output.items(): + for entry in files: + print(node_id, key, entry["filename"], entry.get("subfolder", "")) + print(status["status_str"], status["completed"]) + break + time.sleep(0.5) +``` + +Both loops do the same three things: submit, poll the id, read `outputs` and +`status`. A timeout is not a failure — the first run of a graph pays the model +load. + +## `/api/jobs`, and why it is not `/history` + +Newer servers keep a job view with filtering, sorting and pagination: + +```bash +curl -s "http://127.0.0.1:8188/api/jobs?status=completed&limit=5" +``` + +It reports `pending`, `in_progress`, `completed` and `failed` across the queue +AND the history, which is what a dashboard wants. `/history` remains the thing +`comfy_run` waits on, because it is the endpoint every version has. + +## The WebSocket + +`/ws?clientId=…` streams `status`, `execution_start`, `execution_cached`, +`executing`, `progress`, `executed`, `execution_error`, `execution_interrupted` +and binary preview frames. It is the lowest-latency way to watch a render, and +it needs a socket and a message protocol. `dsh-comfyui` deliberately does not +open one: `/history/{id}` is enough for "did it finish, and what came out", and a +polling loop has no reconnection logic to get wrong. Use the socket when you need +live progress, not to find out whether something worked. + +## Rules that save a debugging session + +1. **Probe `/system_stats` first.** A 404 from anything else is usually the wrong + port, not a wrong path. +2. **Never guess a slot index.** Read `output` from `/object_info` — the order of + a class's `RETURN_TYPES` is arbitrary. +3. **A 400 is a diagnosis, not a failure.** Print `node_errors` — the message + names the node, the input and the value. +4. **`/history` answers `{}` for a prompt that has not finished**, and for one + that never existed. Verify the queue if the distinction matters. +5. **Respect the serial queue.** Submitting five prompts does not run them in + parallel; it makes the fifth wait. One device, one model. +6. **Nothing here is authenticated.** Bind ComfyUI to loopback unless you mean to + expose it: the API can write files to the host it runs on. diff --git a/packages/dsh-comfyui/skills/comfyui-cli/SKILL.md b/packages/dsh-comfyui/skills/comfyui-cli/SKILL.md new file mode 100644 index 0000000..0ede76a --- /dev/null +++ b/packages/dsh-comfyui/skills/comfyui-cli/SKILL.md @@ -0,0 +1,295 @@ +--- +name: comfyui-cli +description: comfy-cli - the cross-platform command line for ComfyUI that installs it, launches it, runs a workflow, resolves a workflow's custom nodes and downloads models, with the same commands on Windows, macOS and Linux. Covers workspace selection (--workspace/--here/--recent, which, set-default), comfy run --workflow and its UI-JSON auto-conversion, jobs/download, node deps-in-workflow, the --json envelopes, COMFY_LOCAL_URL, and exactly which commands this pack's tools will and will not run for you. +whenToUse: Installing or updating ComfyUI, launching a server to test against, running a workflow from a terminal, finding out which custom nodes a workflow needs, downloading a model, or scripting any of it - and whenever a machine has no server running but does have (or can have) comfy-cli. +--- + +# comfy-cli: the terminal face of ComfyUI + +One Python package installs, launches, runs and extends ComfyUI, and it behaves +the same on Windows, macOS and Linux. That matters when the alternative is a +`.bat` per platform. + +```bash +pip install comfy-cli +comfy setup -y +``` + +`pip install comfy-cli` needs **Python 3.10+**. `comfy setup` is the interactive +wizard (local vs cloud, sign-in, agent skills); `-y` makes it non-interactive, +which is what a script wants. `comfy --install-completion` adds tab completion. + +```bash +comfy --version +``` + +## Which ComfyUI is it talking to + +Every command acts on a **workspace**. With no flag, the order is: the path from +`comfy set-default `, then the most recently launched or installed one, +then a ComfyUI in the current directory. + +```bash +comfy which +comfy --recent which +comfy --workspace=/home/me/ComfyUI which +comfy set-default /home/me/ComfyUI +``` + +| Flag | Points at | +|---|---| +| `comfy --workspace=` | the ComfyUI installed under `` | +| `comfy --here` | a ComfyUI in the current directory | +| `comfy --recent` | the last one launched or installed | + +Without any of them, `comfy install` installs into `/comfy/ComfyUI`. +`comfy env` prints the resolved workspace, the python it uses and whether a +server is running — that is the one command to run when you are not sure *which* +ComfyUI you are about to change. + +```bash +comfy env +comfy --json env +``` + +## Install, update, launch, stop + +```bash +comfy install +comfy install --fast-deps +comfy --workspace=~/comfy install +comfy update +comfy update all +``` + +`comfy install` downloads the latest ComfyUI **and ComfyUI-Manager**; run inside +an existing checkout it records that checkout instead. `--fast-deps` resolves +requirements with `uv` instead of pip. + +```bash +comfy launch +comfy launch --background +comfy launch -- --cpu --listen 127.0.0.1 --port 8188 +comfy stop +comfy system-stats +comfy free --free-memory +``` + +- `comfy launch` runs ComfyUI in the foreground; `comfy launch --background` + runs an instance `comfy env` lists and `comfy stop` stops. **No background + instance can be stopped by anything but `comfy stop`** — close the laptop and + it is still there next boot. +- Everything after `--` is passed to ComfyUI itself: `--cpu`, `--listen`, + `--port`, `--lowvram`, `--reserve-vram`. +- `comfy system-stats` reports VRAM and RAM through the server; `comfy free` + unloads models (and with `--free-memory` also resets the executor cache). Both + are the command-line twin of `/system_stats` and `POST /free`. + +## Run a workflow + +```bash +comfy run --workflow ./workflow.json --wait +comfy --json run --workflow ./workflow.json --wait +``` + +- **`--workflow` accepts the app's SAVE format** (the canvas). comfy-cli converts + it to the API prompt itself. That is why it is a real second opinion on a + canvas this pack generated: two independent converters, one result. +- `comfy run` submits and prints a `prompt_id`; **without `--wait` it returns + immediately**. With `--wait` it blocks until the render finishes. +- `--prompt ""` runs a bundled default text-to-image graph instead of a + file. That graph loads `v1-5-pruned-emaonly.ckpt`, which comfy-cli does **not** + download for you — either put that checkpoint in `models/checkpoints` or point + the graph elsewhere with `--set checkpoint=`. +- If a graph needs an input image or an audio file, the file has to be in + ComfyUI's `input/` folder (or uploaded) before the run: the CLI submits the + graph, it does not invent the file. + +Follow a job that is already in flight: + +```bash +comfy jobs ls +comfy jobs status +comfy jobs watch +comfy download -o ./outputs +``` + +`comfy download` also reads a `prompt_id` from stdin, so +`comfy run --workflow x.json | comfy download -o out` is a pipeline. + +## Which custom nodes does this workflow need? + +This is the question that decides whether a workflow will open at all, and +comfy-cli can answer it **without a server** — but not without a workspace and +ComfyUI-Manager: + +```bash +comfy --workspace=/path/to/ComfyUI node deps-in-workflow --workflow=./workflow.json --output=./deps.json +comfy node install-deps --workflow=./workflow.json +``` + +`deps-in-workflow` writes a dependency file naming the node packs (and any model +URLs) the graph references; `install-deps` then installs them. `comfy_cli` +action=deps runs the first and reports the names, and never runs the second. + +Two refusals come BEFORE it reads the graph, both measured on 1.29.0: + +| Message | What it means | +|---|---| +| `'' is not a valid ComfyUI workspace.` | comfy-cli's default is `/comfy/ComfyUI`, which does not exist on a Desktop machine. Pass `--workspace=` (the tree must have `main.py`, `comfy/`, `nodes.py`, `comfy_extras/`, `comfy_api/`), or `comfy install`. | +| `ComfyUI-Manager not found. 'cm-cli' command is not available.` | the command resolves node packs through the **Manager**. A tree made by `comfy install` has one; a **Desktop install keeps its Manager inside the app**, so `deps-in-workflow` does not work against it. `comfy run --workflow` does not need the Manager. | + +`comfy_cli` action=deps passes `--workspace` naming the tree `comfy_status` +found when comfy-cli's own default does not exist, so the first refusal is +avoided and the second is explained instead of dumped as raw stderr. + +## Nodes + +```bash +comfy node show installed +comfy node simple-show installed +comfy node install comfyui-impact-pack +comfy node registry-install comfyui-impact-pack +comfy node update all +comfy node save-snapshot +comfy node restore-snapshot +comfy node bisect start +comfy extension list +``` + +- `node install ` goes through **ComfyUI-Manager**'s `cm-cli` and the + Manager's channel database. The id is the **Comfy Registry id**, lower case + (`comfyui-impact-pack`), not the GitHub repository name + (`ComfyUI-Impact-Pack`) — the wrong casing fails to resolve. +- `node registry-install ` talks to the Registry directly, needs no Manager, + and runs the node's own install script. +- `node update all` **can exit 0 even when a custom node failed to update**; + `--exit-on-fail` is what makes a script see it. +- `node save-snapshot` / `restore-snapshot` is the way back from a pile of node + changes; `node bisect` finds the pack that broke a graph. +- After installing a node pack, **restart ComfyUI**. The class only appears in + `/object_info` after the server reloads — and a cached catalog from before the + restart will not have it either. + +## Models + +```bash +comfy model list +comfy model download --url https://huggingface.co/.../model.safetensors --relative-path models/checkpoints +comfy model download --url https://civitai.com/models/12345 --relative-path models/loras +comfy model remove --model-names old.safetensors --relative-path models/checkpoints +``` + +The URL may be a CivitAI model page or a Hugging Face **file** URL; +`--relative-path` says which `models/…` folder it lands in, which is the thing +that decides whether a loader node's dropdown will show it. Tokens come from +`CIVITAI_API_TOKEN` / `HF_API_TOKEN`, or `--set-civitai-api-token` / +`--set-hf-api-token` once. + +## Machine-readable output + +`--json` is a **global option, before the subcommand** — `comfy --json env`, not +`comfy env --json` (which is a usage error: `No such option: --json`). With +stdout piped the CLI picks JSON on its own, but passing it explicitly is what +makes that a contract rather than a coincidence. + +```bash +comfy --json env +comfy --json node show installed +``` + +Every answer is one **envelope**, so a script reads fields instead of prose: + +```json +{ + "schema": "envelope/1", + "type": "envelope", + "ok": true, + "command": "env", + "version": "1.29.0", + "where": null, + "data": { + "python": { "version": "3.12.11", "executable": "C:\\ComfyUI\\.venv\\Scripts\\python.exe" }, + "server": { "running": false, "url": null }, + "hardware": { "gpu": { "model": "NVIDIA GeForce RTX 3090", "vram_bytes": 25769803776 } }, + "workspace": { + "path": "C:\\Users\\me\\Documents\\comfy\\ComfyUI", + "type": "default", + "exists": false, + "desktop": { + "installs": [ + { "name": "sdf", "code_dir": "C:\\Users\\me\\ComfyUI-Installs\\sdf\\ComfyUI", "data_dir": "C:\\Users\\me\\ComfyUI-Installs\\sdf\\ComfyUI", "exists": false } + ], + "model_roots": [] + } + } + }, + "error": null +} +``` + +- the payload is under **`data`**; the CLI's own version is a **top level** + field (there is no need to scrape it); +- a refusal is still an envelope: `ok: false` with + `error: { code, message, hint, details }` — e.g. + `{"code": "server_not_running", "message": "ComfyUI not running on specified address (127.0.0.1:8188)", "hint": "run: comfy launch"}`. + That is where the useful sentence lives, so read `error.code` before deciding + something failed for an unknown reason; +- `data.workspace.desktop.installs[]` names every Desktop install with its + `code_dir` and `data_dir` — the only place those paths are written down + outside the app itself. + +`--json-stream` emits one NDJSON event per line with the envelope last, and +`--help-json` prints machine-readable help for the whole CLI. + +`COMFY_LOCAL_URL` points **every** local-targeting command at a server you +started outside comfy-cli: + +```bash +export COMFY_LOCAL_URL=http://127.0.0.1:8189 +comfy run --workflow ./workflow.json --wait +``` + +It accepts `http://host:port`, `host:port` or `http://host` (port defaults to +8188), with bracketed IPv6 literals. Precedence per command: `--host`/`--port`, +then `COMFY_LOCAL_URL`, then a comfy-cli background instance, then +`127.0.0.1:8188`. + +Telemetry is **opt-in and off**; `DO_NOT_TRACK=1` or `COMFY_NO_TELEMETRY=1` +suppresses it regardless. `comfy tracking disable` turns it off permanently. + +## What this pack runs, and what it will not + +`comfy_cli` drives five things and refuses the rest: + +| `comfy_cli` action | Runs | Why | +|---|---|---| +| `status` | `comfy --version`, `comfy --json env`, `comfy --json which` | read-only facts, and the Desktop install paths it names | +| `deps` | `comfy [--workspace=] --json node deps-in-workflow --workflow=… --output=…` | answers what a graph needs; needs a valid workspace AND ComfyUI-Manager | +| `run` | `comfy [--workspace=] --json run --workflow --wait` (and optionally `comfy download`) | the independent test path; needs a RUNNING server | +| `launch` | `comfy --json launch --background` | gives you a server to test against | +| `stop` | `comfy --json stop` | so `launch` cannot leak | + +**Never run by this pack** — each one changes somebody's machine, so the person +decides: + +- `comfy install`, `comfy update`, `comfy --version` pins; +- `comfy node install` / `registry-install` / `update` / `restore-snapshot`; +- `comfy model download` / `remove`; +- `comfy cloud login`, `comfy generate` (both spend credits); +- `comfy manager`, `comfy extension` (they change what the app loads). + +The skill names them so they are one copy-paste away. That is the division: +**the agent proposes the command, the person runs the ones that write.** + +## When the CLI is the only thing that works + +- **No server, no app open, and you need one:** `comfy launch --background`, + then `comfy_status` finds the port it chose (Desktop ports and 8188 are both + probed). +- **A canvas that the API tools cannot lower** (a subgraph export the app will + not unpack): `comfy run --workflow` converts it itself and reports the failure + from the server, which is a faster answer than reasoning about the JSON. +- **A machine you are setting up from nothing:** `pip install comfy-cli`, + `comfy install`, `comfy model download`, then `comfy run` a smoke graph — + no clicking, and the same lines on all three platforms. diff --git a/packages/dsh-comfyui/skills/comfyui-fundamentals/SKILL.md b/packages/dsh-comfyui/skills/comfyui-fundamentals/SKILL.md new file mode 100644 index 0000000..d5dcb71 --- /dev/null +++ b/packages/dsh-comfyui/skills/comfyui-fundamentals/SKILL.md @@ -0,0 +1,203 @@ +--- +name: comfyui-fundamentals +description: The ComfyUI mental model - a graph is a program, node = function, wire = typed data, models never touch pixels, a prompt is a vector, the seed is the only randomness, a LoRA is a patch - plus the latent arithmetic, the model folders, the sampler dials and how to read a ComfyUI error. Load this before building or debugging any ComfyUI graph, and before deciding which example to start from. +whenToUse: The user asks for a ComfyUI workflow, image, video or audio generation, asks why a graph is slow or gives a bad image, needs the numbers behind steps/cfg/sampler/resolution, or is new to ComfyUI and needs the model of how it works before touching a node. +--- + +# ComfyUI in one page, then the details + +ComfyUI is a graph editor for a diffusion engine. Nothing about it is magic and +nothing about it is a menu: a workflow is a file, a render is a queue item, and +every failure is one of about six things. Learn the six and the app stops being +a box of buttons. + +## The five ideas + +1. **A graph is a program.** A node is a function with typed inputs and typed + outputs; a wire is a value passed between them. The queue executes the graph + every time you press Run, from the nodes that have no inputs towards the + nodes marked as OUTPUT. Nothing is "applied" to a document - the document is + the program. +2. **Models never touch pixels.** An image is decoded to a `LATENT` by a `VAE`, + the sampler works in that latent space, and a second `VAE` pass decodes it + back. Audio has latents too. That is why `Empty Latent Image` and + `VAE Decode` exist at all. +3. **A prompt is a vector, not text.** `CLIP Text Encode` turns a string into + `CONDITIONING` - a stack of vectors. The negative prompt is a *second* + vector, and the sampler is told to move away from it. That is what + classifier-free guidance (`cfg`) scales. +4. **The seed is the only randomness.** Same graph, same seed, same sampler, + same model on the same machine gives the same image. Change the seed and + everything else can stay identical. +5. **A LoRA is a patch, not a model.** 135 MB can turn a 25-step model into a + 4-step one because it plugs into the `MODEL` and `CLIP` wires and modifies + them in place. Everything in ComfyUI is a cartridge plugged into a wire. + +## The types on the wires + +| Type | What travels | Made by | Consumed by | +|---|---|---|---| +| `MODEL` | the denoiser | `Load Checkpoint`, `UNETLoader` | `KSampler`, `LoraLoader` | +| `CLIP` | the text encoder | `Load Checkpoint`, `CLIPLoader` | `CLIP Text Encode` | +| `VAE` | the encoder/decoder | `Load Checkpoint`, `VAELoader` | `VAE Encode`, `VAE Decode` | +| `CONDITIONING` | prompt vectors | `CLIP Text Encode` | `KSampler` positive/negative | +| `LATENT` | the compressed image | `Empty Latent Image`, `VAE Encode` | `KSampler`, `VAE Decode` | +| `IMAGE` | pixels, a batch | `VAE Decode`, `Load Image`, `Empty Image` | `Save Image`, `VAE Encode` | +| `MASK` | one channel | `Load Image` alpha, `SolidMask` | inpainting nodes | +| `AUDIO` | waveform + rate | `VAE Decode Audio`, `Load Audio` | `Save Audio`, `Create Video` | +| `VIDEO` | frames + audio | `Create Video` | `Save Video` | +| `*` | anything | — | a node that accepts any type | + +A wire can only carry what its type says. Connecting `IMAGE` into a `LATENT` +input is refused before anything runs - by the app when you drag, and by +`/prompt` with `return_type_mismatch` when a file does it. + +## The eight-node text-to-image graph + +This is the whole of image generation. Everything else is a variant. + +``` +Load Checkpoint ─ MODEL ─┐ + CLIP ──┼─→ CLIP Text Encode (positive) ─ CONDITIONING ─┐ + VAE ──┼─→ CLIP Text Encode (negative) ─ CONDITIONING ─┤ + │ ├─→ KSampler ─ LATENT ─→ VAE Decode ─→ Save Image +Empty Latent Image ──────┴────────────────────────── LATENT ─────────────┘ ▲ + VAE +``` + +| Node | Why it is there | +|---|---| +| `Load Checkpoint` | one `.safetensors` holding the model, the text encoder and the VAE | +| `CLIP Text Encode` ×2 | the prompt and the anti-prompt, as vectors | +| `Empty Latent Image` | the canvas in latent space: 512×512 becomes 64×64×4 | +| `KSampler` | the loop that turns noise into a picture in N steps | +| `VAE Decode` | latent back to pixels | +| `Save Image` | writes to `output/` and is an OUTPUT node - the graph runs to it | + +`Save Image` is the node the queue executes *for*. A graph with no output node +is refused with `prompt_no_outputs`, no matter how many other nodes it has. + +## The latent arithmetic + +- The VAE compresses by **8** in each direction: 512×512 → 64×64, and the latent + has **4** channels. 512×512×3 = 786,432 pixel values becomes 16,384 latent + values. That ratio is why the sampler is fast and why the VAE passes are not + free. +- Every model family has a native resolution. SD 1.5 is 512, SDXL is 1024, and + Z-Image-Turbo is 1024. Rendering SD 1.5 at 1024 does not give you a sharper + picture; it gives you a repeated subject, because the model has only ever seen + 512-pixel compositions. +- **Cost goes with the pixel count, not the side.** Doubling both sides is 4× + the work. 768×768 is 2.25 × 512×512, and that is why "a bit bigger" is a + different class of wait. +- `Empty Latent Image` rounds to multiples of 8; a width of 500 becomes 496. + +## The dials + +| Dial | What it does | Practical range | +|---|---|---| +| `steps` | denoising iterations | 20-30 normal, **4** for LCM/turbo LoRAs, 6-8 for turbo checkpoints | +| `cfg` | how hard to follow the prompt | 6-8 normal, **1-2** for LCM/turbo (high cfg burns at 4 steps) | +| `sampler_name` | the integrator | `euler`, `dpmpp_2m`, `lcm`, `euler_ancestral` | +| `scheduler` | how the steps are spaced | `normal`, `karras`, `sgm_uniform` | +| `denoise` | how much of the input latent to destroy | 1.0 for text-to-image, 0.35-0.85 for image-to-image | +| `seed` | the only randomness | any integer; the same seed reproduces | + +**Denoise is the image-to-image dial.** At 1.0 the input latent is ignored and +you get a new picture from the prompt; at 0.55 the composition survives and the +prompt repaints it; at 0.35 it is a filter. Below about 0.2, nothing changes. + +## The model folders + +A filename in a node's dropdown is a path relative to one folder in the ComfyUI +install. Putting a file in the wrong one is the most common `value_not_in_list` +there is. + +| Folder | Holds | Loaded by | +|---|---|---| +| `models/checkpoints` | full checkpoints (model + CLIP + VAE) | `Load Checkpoint` | +| `models/loras` | LoRA patches | `Load LoRA` | +| `models/vae` | standalone VAEs | `VAE Loader` | +| `models/text_encoders` | CLIP/T5 encoders | `CLIP Loader` | +| `models/diffusion_models` | UNET-only files | `UNET Loader` | +| `models/controlnet` | ControlNet weights | `ControlNet Loader` | +| `models/upscale_models` | ESRGAN-style upscalers | `Upscale Model Loader` | +| `models/embeddings` | textual inversions | named inline in a prompt | + +A subfolder shows up in the dropdown with a forward slash: a file at +`models/checkpoints/sd/v1-5.safetensors` is `sd/v1-5.safetensors`. + +## The six failures, and what each actually means + +| Message | What it means | The fix | +|---|---|---| +| `value_not_in_list` | a dropdown names a file that is not in that folder | move the file to the right `models/…` folder, or change the widget | +| `missing_node_type` | the graph names a class this server does not have | install the node pack (`comfy node install `), restart ComfyUI | +| `required_input_missing` | a node was saved before a field existed | open the graph in the app so it fills the field, then save | +| `return_type_mismatch` | a wire carries the wrong type | rewire; the types are on the sockets | +| `prompt_no_outputs` | no output node in the graph | add `Save Image` / `Save Video` / `Preview Image` | +| `OutOfMemoryError` | the GPU or RAM ran out | smaller image, smaller batch, `--cpu`, or close other apps | + +Two more that look like failures and are not: `Device: cpu` in the console is +normal on a machine with no GPU (ComfyUI is using the CPU), and a prompt that +stays in the queue while another runs is the queue being serial - one model at a +time on one device. + +## Run it on a CPU, in order + +1. **512×512, batch 1.** Everything else is a measurement you have not made yet. +2. **Four steps with an LCM LoRA** (`lcm-lora-sd15`, 1.0 / 1.0, sampler `lcm`, + scheduler `sgm_uniform`, cfg 1.5). Eight steps costs double, two is visibly + worse. +3. **Plug in, best-performance power plan, close the browser** while it renders. +4. **Time the first image.** 10-25 s is normal for 512 px on a 2020 laptop. If + it is 90 s, something thermal or a swap file is the cause, and you find it in + the first minute rather than the last. + +## The four builds + +| Build | Graphs | Extra nodes over the eight | +|---|---|---| +| text → image | `smoke-image`, `text-to-image` | — | +| image → image | `image-to-image` | `Load Image`, `Upscale Image`, `VAE Encode`, denoise < 1 | +| text → audio | (audio checkpoint + `Empty Latent Audio`) | `VAE Decode Audio`, `Save Audio` | +| image + audio → clip | `smoke-video` | `Repeat Image Batch`, `Create Video`, `Save Video` | + +`smoke-image` and `smoke-video` need **no model at all**: `Empty Image` makes a +coloured rectangle, and `Save Image` writes it. They are how you prove a machine +works before blaming a download. + +## A minimal API prompt, to keep the shape in your head + +```json +{ + "1": { "class_type": "CheckpointLoaderSimple", "inputs": { "ckpt_name": "v1-5-pruned-emaonly-fp16.safetensors" } }, + "2": { "class_type": "CLIPTextEncode", "inputs": { "text": "a lighthouse at dusk", "clip": ["1", 1] } }, + "3": { "class_type": "CLIPTextEncode", "inputs": { "text": "blurry, text", "clip": ["1", 1] } }, + "4": { "class_type": "EmptyLatentImage", "inputs": { "width": 512, "height": 512, "batch_size": 1 } }, + "5": { + "class_type": "KSampler", + "inputs": { + "model": ["1", 0], "seed": 42, "steps": 4, "cfg": 1.5, + "sampler_name": "lcm", "scheduler": "sgm_uniform", + "positive": ["2", 0], "negative": ["3", 0], "latent_image": ["4", 0], "denoise": 1.0 + } + }, + "6": { "class_type": "VAEDecode", "inputs": { "samples": ["5", 0], "vae": ["1", 2] } }, + "7": { "class_type": "SaveImage", "inputs": { "images": ["6", 0], "filename_prefix": "dsh-comfyui/first" } } +} +``` + +`["1", 0]` means "node 1, output slot 0". The slots follow +`CheckpointLoaderSimple`'s `RETURN_TYPES = ("MODEL", "CLIP", "VAE")`, which is +why `["1", 1]` is the CLIP and `["1", 2]` is the VAE. `comfy_nodes` action=node +prints that order for any class; never guess it. + +## What to read next + +- The two file formats, and the trap in `widgets_values` → + `comfyui-workflow-json`. +- The endpoints and the error body → `comfyui-api`. +- `comfy install`, `comfy launch`, `comfy run` → `comfyui-cli`. +- Writing a node of your own → `comfyui-node-class`. +- The project dialect this pack writes → `comfyui-projects`. diff --git a/packages/dsh-comfyui/skills/comfyui-node-class/SKILL.md b/packages/dsh-comfyui/skills/comfyui-node-class/SKILL.md new file mode 100644 index 0000000..355b0c4 --- /dev/null +++ b/packages/dsh-comfyui/skills/comfyui-node-class/SKILL.md @@ -0,0 +1,253 @@ +--- +name: comfyui-node-class +description: Writing a ComfyUI node class - the custom_nodes pack layout, INPUT_TYPES and the classic class contract (RETURN_TYPES, FUNCTION, CATEGORY, OUTPUT_NODE, IS_CHANGED, VALIDATE_INPUTS, INPUT_IS_LIST), the V3 schema API (IO.ComfyNode.define_schema with IO.Image.Input and IO.NodeOutput), returning previews, the web extension hook, and how to verify a class actually loaded with /object_info. +whenToUse: Creating a custom node, a node pack, or a Python class that runs inside ComfyUI; changing an existing node's inputs or return types; debugging a node that does not appear, appears without widgets, or raises during validation. +--- + +# A node is a class with a contract + +ComfyUI finds node classes by importing every folder in `custom_nodes/` and +reading two dictionaries. Everything else is the class's own agreement about +what it takes and what it returns. + +## The pack layout + +``` +ComfyUI/custom_nodes/my-pack/ + __init__.py # exports the mappings - REQUIRED + nodes.py # or any modules you like + requirements.txt # pip-installable deps, if any + pyproject.toml # only needed to publish to the Registry + web/ # optional JS extensions +``` + +```python +# custom_nodes/my-pack/__init__.py +from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS + +WEB_DIRECTORY = "./web" # optional; omit it if you have no JS + +__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"] +``` + +The folder name is the pack's identity. A pack that raises on import is skipped +with a traceback in the console and **none of its nodes appear** — so the first +check after adding code is always: did ComfyUI still start? + +## The classic class + +```python +# custom_nodes/my-pack/nodes.py +import torch + + +class ImageSolidTint: + """Multiply every pixel by a colour, in one pass.""" + + CATEGORY = "image/color" + DESCRIPTION = "Multiplies an image batch by a solid colour, preserving alpha." + SEARCH_ALIASES = ["tint", "colorize", "multiply"] + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "image": ("IMAGE",), + "color": ("INT", {"default": 0xFF8844, "min": 0, "max": 0xFFFFFF, "step": 1, "display": "color"}), + "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}), + "mode": (["multiply", "screen", "overlay"],), + }, + "optional": { + "mask": ("MASK",), + }, + } + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image",) + FUNCTION = "apply" + OUTPUT_NODE = False + + def apply(self, image, color, strength, mode, mask=None): + red = ((color >> 16) & 0xFF) / 255.0 + green = ((color >> 8) & 0xFF) / 255.0 + blue = (color & 0xFF) / 255.0 + tint = torch.tensor([red, green, blue], dtype=image.dtype, device=image.device) + + if mode == "screen": + out = 1.0 - (1.0 - image) * (1.0 - tint) + elif mode == "overlay": + out = torch.where(image < 0.5, 2.0 * image * tint, 1.0 - 2.0 * (1.0 - image) * (1.0 - tint)) + else: + out = image * tint + + out = image + (out - image) * strength + if mask is not None: + out = image + (out - image) * mask.unsqueeze(-1) + return (out,) + + +NODE_CLASS_MAPPINGS = {"ImageSolidTint": ImageSolidTint} +NODE_DISPLAY_NAME_MAPPINGS = {"ImageSolidTint": "Solid Tint"} +``` + +The contract, member by member: + +| Member | Required | Meaning | +|---|---|---| +| `INPUT_TYPES()` | yes, `@classmethod` | `{"required": {...}, "optional": {...}, "hidden": {...}}` | +| `RETURN_TYPES` | yes | a tuple of type strings; `()` for an output node | +| `RETURN_NAMES` | no | display names for the outputs (defaults to the types) | +| `FUNCTION` | yes | the name of the method to call | +| `CATEGORY` | no | the right-click menu path; `/` nests | +| `OUTPUT_NODE` | no | `True` makes it a node the graph can run *to* | +| `INPUT_IS_LIST` | no | receive whole lists instead of the first item | +| `OUTPUT_IS_LIST` | no | one tuple element per output is a list | +| `IS_CHANGED` | no | force re-execution (return a value that changes, or `NaN`) | +| `VALIDATE_INPUTS` | no | your own pre-flight check | +| `DESCRIPTION` | no | the tooltip text in the app | +| `SEARCH_ALIASES` | no | extra words the node search matches | +| `DEPRECATED` / `EXPERIMENTAL` | no | flags the app and `/object_info` report | + +### Input declarations + +| Declaration | Widget | Notes | +|---|---|---| +| `("INT", {"default": 1, "min": 1, "max": 4096})` | integer field | `step` controls the arrows | +| `("FLOAT", {"default": 0.5, "min": 0, "max": 1, "step": 0.01})` | number field | `round` rounds the stored value | +| `("STRING", {"default": "", "multiline": True})` | text box | `dynamicPrompts` enables `{a|b}` | +| `("BOOLEAN", {"default": True})` | toggle | | +| `(["a", "b", "c"],)` | dropdown | a LIST in the type position is a combo | +| `("IMAGE",)` or `("LATENT",)` | a socket only | no widget | +| `("INT", {"forceInput": True})` | a socket only | a widget made link-only | +| `(["euler", "dpmpp_2m"], {"default": "euler"})` | dropdown with a default | | +| `("INT", {"default": 0, "control_after_generate": True})` | integer + the fixed/increment/decrement/randomize control | **adds one value to `widgets_values`** | + +That last row is the one that breaks saved workflows: adding +`control_after_generate` to an input shifts every later value in +`widgets_values`, so every graph saved before the change re-opens with wrong +values. Do not add it to an existing node; add a new node instead. + +`"hidden"` inputs are supplied by the server and never appear in a prompt: + +```python +INPUT_TYPES_HIDDEN = {"hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO", "unique_id": "UNIQUE_ID"}} +``` + +### Returning more than tensors + +A node may return a `ui` payload — that is how `Save Image` makes its preview +appear in the app — together with its `result`: + +```python +def save(self, images, filename_prefix="ComfyUI"): + path = f"{filename_prefix}_00001_.png" + return {"ui": {"images": [{"filename": path, "subfolder": "", "type": "output"}]}, "result": ()} +``` + +### The two hooks worth knowing + +```python +@classmethod +def IS_CHANGED(cls, image, color): + # Re-run whenever the input hash changes; return float("NaN") to always re-run. + return f"{image.shape}-{color}" + +@classmethod +def VALIDATE_INPUTS(cls, image, color, strength): + if not 0.0 <= strength <= 1.0: + return f"strength must be between 0 and 1, got {strength}" + return True +``` + +`VALIDATE_INPUTS` returns `True` or a message string, which becomes +`custom_validation_failed` in the `/prompt` body. Its arguments must be a subset +of the node's declared inputs; a special `input_types` argument receives the +types of what is actually wired in. + +## The V3 schema API + +Newer core nodes declare the same contract as data instead of dictionaries. It +is the same engine — `/object_info` reports both in one shape. + +```python +from comfy_api.latest import IO + + +class RepeatImageBatch(IO.ComfyNode): + @classmethod + def define_schema(cls): + return IO.Schema( + node_id="RepeatImageBatch", + display_name="Repeat Image Batch", + category="image/batch", + search_aliases=["duplicate image", "clone image"], + inputs=[ + IO.Image.Input("image"), + IO.Int.Input("amount", default=1, min=1, max=4096), + IO.Combo.Input("mode", options=["repeat", "tile"], default="repeat"), + ], + outputs=[IO.Image.Output()], + ) + + @classmethod + def execute(cls, image, amount, mode) -> IO.NodeOutput: + return IO.NodeOutput(image.repeat((amount, 1, 1, 1))) + + +NODE_CLASS_MAPPINGS = {"RepeatImageBatch": RepeatImageBatch} +NODE_DISPLAY_NAME_MAPPINGS = {"RepeatImageBatch": "Repeat Image Batch"} +``` + +Useful pieces of `IO`: `Schema(..., is_output_node=True, hidden=[IO.Hidden.prompt, IO.Hidden.extra_pnginfo])`, +`IO.Image/Mask/Latent/Audio/Video/Conditioning/Model/Clip/Vae.Input(...)`, +`IO.Combo.Input(..., options=[...])`, `IO.MatchType` for "anything", and +`IO.NodeOutput(value)` or `IO.NodeOutput(ui=...)`. + +## Verify the class actually loaded + +The console saying nothing is not proof. Ask the server: + +```bash +curl -s "http://127.0.0.1:8188/object_info/ImageSolidTint" +``` + +An empty `{}` means the class is not there: the pack failed to import, or the +server has not been restarted since you wrote it, or `NODE_CLASS_MAPPINGS` does +not contain that key. + +Then check the three things a mapping can get wrong without an error: + +1. **the widgets are there** — `input_order.required` names your inputs in the + order the app shows them; +2. **the outputs line up** — `output` and `output_name` match `RETURN_TYPES` and + `RETURN_NAMES`; +3. **a two-node graph runs** — your class feeding `Save Image`, queued once. + +With this pack: `comfy_nodes` action=node node=ImageSolidTint prints exactly the +catalog entry the server reports, which is the same thing the app draws from. + +## A node that fails, and why + +| Symptom | Cause | +|---|---| +| the class never appears | the pack raised on import (check the console), or the server was not restarted | +| it appears with no widgets | `INPUT_TYPES` is not a `@classmethod`, or returns the wrong shape | +| `KeyError` on a widget | the app sent a value the function signature does not accept | +| `custom_validation_failed` | your `VALIDATE_INPUTS` returned a string — read it, it is the message | +| it re-runs every time | no `IS_CHANGED`, which is correct but slow; add one | +| it runs once and then returns the old value | `IS_CHANGED` returns the same value for different inputs | +| a tensor is on the wrong device | use `comfy.model_management.intermediate_device()` rather than `"cpu"` or `"cuda"` | +| a saved graph's values shifted | you added `control_after_generate` to an existing input | + +Two habits that prevent most of them: **never mutate a default** (a `dict` or +`list` in `INPUT_TYPES` is shared by every execution) and **keep the input order +stable** once anyone has saved a workflow — the order IS the format. + +## A web extension, in one paragraph + +`WEB_DIRECTORY = "./web"` plus a `web/js/my-extension.js` that calls +`app.registerExtension({ name: "my-pack", async beforeRegisterNodeDef(nodeType, nodeData) { ... } })` +is how a node draws something custom on the canvas. It is optional, it is +frontend JavaScript rather than Python, and it cannot change what the server +executes — only how the node looks and what it offers. Ship it only if the node +needs it. diff --git a/packages/dsh-comfyui/skills/comfyui-projects/SKILL.md b/packages/dsh-comfyui/skills/comfyui-projects/SKILL.md new file mode 100644 index 0000000..7b8a185 --- /dev/null +++ b/packages/dsh-comfyui/skills/comfyui-projects/SKILL.md @@ -0,0 +1,247 @@ +--- +name: comfyui-projects +description: The dsh-comfyui project dialect - a folder whose project.json is a small readable spec (nodes by KEY, values by NAME, wires by `.`, `@bindings` for anything that belongs to a machine) from which workflow.json and prompt.json are GENERATED, validated against the server's own node catalog, and run; the four rungs of the ladder and what each proves; the shipped example library; and how to bring an existing ComfyUI workflow in. +whenToUse: Creating, editing, validating or running a ComfyUI project with the comfy_* tools; adding an example to the shipped library; importing a workflow out of the app; deciding whether a graph is merely well-shaped or actually verified; or when a build or run refuses and the finding needs reading. +--- + +# A project is a folder with one file you edit + +``` +comfyui/text-to-image/ + project.json ← the SOURCE. You edit this. + workflow.json ← GENERATED. Drag it onto the ComfyUI canvas. + prompt.json ← GENERATED. What /prompt accepts. + README.md ← GENERATED. What it is, what it needs, what was checked. + build.json ← GENERATED. The receipt: catalog, rung, findings. +``` + +The generated files say so at the top. Editing `workflow.json` by hand is a +counting exercise — its `widgets_values` is an unnamed positional array whose +meaning moves when a class declares `control_after_generate` — so the spec is the +only file worth writing. + +## The spec + +```json +{ + "name": "solid-tint", + "title": "Solid Tint", + "description": "Recolour an existing image with one multiply pass.", + "tags": ["image"], + "requires": { + "nodes": ["LoadImage", "SaveImage"], + "models": {}, + "inputFiles": ["photo.png"] + }, + "bindings": { + "inputImage": "photo.png", + "color": 16745540, + "strength": 0.6, + "mode": "multiply" + }, + "nodes": [ + { + "key": "input", + "class": "LoadImage", + "title": "Load Image", + "pos": [40, 120], + "widgets": { "image": "@inputImage" } + }, + { + "key": "tint", + "class": "ImageSolidTint", + "title": "Solid Tint", + "pos": [420, 120], + "widgets": { "color": "@color", "strength": "@strength", "mode": "@mode" }, + "wires": { "image": "input.IMAGE" } + }, + { + "key": "save", + "class": "SaveImage", + "title": "Save Image", + "pos": [800, 120], + "widgets": { "filename_prefix": "dsh-comfyui/solid-tint" }, + "wires": { "images": "tint.IMAGE" } + } + ] +} +``` + +| Field | Meaning | +|---|---| +| `name` | the folder name; lower case, digits and dashes | +| `title`, `description` | what the generated README and the tool answers show | +| `requires.models` | `{ "": ["file", …] }` — what must exist under `models/` | +| `requires.inputFiles` | files that must exist under `input/` | +| `requires.nodes` | the classes the graph uses (documentation and a check) | +| `bindings` | the machine-specific values, addressed as `@name` | +| `nodes[].key` | the node's identity inside the project; wires refer to it | +| `nodes[].class` | the ComfyUI class, exactly as `/object_info` spells it | +| `nodes[].widgets` | input name → value (or `@binding`) | +| `nodes[].wires` | input name → `"."`, `"."` or `""` | +| `nodes[].controlAfterGenerate` | per-seed `"fixed"` / `"increment"` / `"decrement"` / `"randomize"` | +| `nodes[].pos`, `size` | optional; geometry is computed by dependency depth otherwise | +| `notes` | free text printed into the generated README | + +### Why bindings + +A graph that hardcodes `v1-5-pruned-emaonly-fp16.safetensors` is a graph that +fails on any machine that has a different checkpoint, with `value_not_in_list` +and no clue that a re-download is not the answer. A binding moves that decision +to build time: + +- `comfy_project` action=new **rebinds** a file-ish binding to this machine's + list when the declared file is not there — only on an exact case-insensitive + match or when the server lists exactly one file, never by guessing between + two; +- every rebinding is printed, so the report says `@checkpoint: "a" -> "b"`; +- a binding nobody can resolve is an **error** (`BINDING_UNRESOLVED`), never a + silent default: a graph built against a model nobody chose is a graph whose + first run fails one step from the cause. + +### Why the wire names an OUTPUT + +`"images": "decode.IMAGE"` is resolved through the class's `RETURN_TYPES` order +to a slot index. `decode.0` works too (and is what you need when the class is not +in the catalog). The compiler refuses an output name the class does not have and +lists the real ones — a wrong slot is the quietest way to break a graph. + +## The four rungs, and exactly what each proves + +| Rung | Reached when | What it means | +|---|---|---| +| `v1-structural` | the spec compiles, wires resolve, types line up — against the **built-in core table** | the graph is well-formed, and nothing confirms the classes exist on this machine | +| `v2-schema` | the same, against a complete server catalog (live or cached) | every class exists, every required input is set, every value is in the server's own list — the same checks `/prompt` runs | +| `v3-queued` | the server accepted the prompt (`/prompt` answered a `prompt_id`) | the graph is runnable | +| `v4-executed` | a `/history` entry finished and `outputs` named files | it ran and produced something you can look at | + +Anything below `v2-schema` says one thing plainly: **no server catalog was in +force**. `comfy_status` tells you which catalog is in force and how to get a +better one. + +## The worked sequence + +```bash +comfy_status +``` + +Read three lines: is there a **server** (and on which port), is there an +**install** (and where its models are), and which **catalog** is in force. + +```bash +comfy_nodes action=search query=checkpoint +comfy_nodes action=node node=LoadImage +``` + +The second one is not optional before wiring an unfamiliar class: it prints the +input order, which is what `widgets_values` means. + +```bash +comfy_project action=new template=smoke-image name=first-run +``` + +No model needed. It writes the folder, builds both files, and reports the rung. + +```bash +comfy_validate project=first-run +comfy_run project=first-run +``` + +`comfy_validate` never queues anything and never writes. `comfy_run` builds, +refuses a graph with validation errors, and otherwise submits and waits. + +```bash +comfy_test action=compile +comfy_test action=run waitSeconds=120 +``` + +`compile` is the check that works on a machine with no ComfyUI running, and is +what to run after changing anything. `run` is the same library through a live +server, one item at a time. + +The other way in, when you already have a workflow from the app: + +```bash +comfy_project action=import source=./my-workflow.json name=my-graph +comfy_project action=build project=my-graph +``` + +An imported canvas is stored as `workflow.json` and **never rewritten**; its +`prompt.json` is derived from it on every build. That derivation needs a complete +catalog (the `widgets_values` decode), and says so instead of guessing. + +## The second witness: comfy-cli + +`comfy_cli action=run project=first-run` runs +`comfy run --workflow workflow.json --wait`, which converts the canvas with +comfy-cli's own converter and submits it. Two implementations, one graph: if the +API accepts `prompt.json` and the CLI accepts `workflow.json`, the canvas and the +prompt agree about what the graph *is*. + +`comfy_cli action=deps project=first-run` answers the question a project cannot +answer about itself — which custom node packs it needs — before the graph is even +opened. + +## Adding an example to the shipped library + +An example is a folder under `examples/` with a `project.json` and nothing else +required: + +1. copy the closest example, change `name` and the nodes; +2. `comfy_test action=compile examples=["your-slug"]` — it must reach at least + `v1-structural` (and `v2-schema` whenever a server is up); +3. prefer **no models**: an example that needs a 2 GB download is not the one a + person tries first. `smoke-image` and `smoke-video` exist for exactly that; +4. declare everything it needs in `requires` — a check that cannot say what is + missing is not a check. + +The four shipped examples: + +| Slug | Nodes | Needs | +|---|---|---| +| `smoke-image` | `EmptyImage` → `SaveImage` | nothing | +| `smoke-video` | `EmptyImage` → `RepeatImageBatch` → `CreateVideo` → `SaveVideo` | nothing | +| `text-to-image` | 8 nodes, SD 1.5 + LCM LoRA, 4 steps | a checkpoint and a LoRA | +| `image-to-image` | 10 nodes, denoise 0.55 | both of those plus an input image | + +## `build.json`, the receipt + +```json +{ + "schema": 1, + "project": "first-run", + "source": "spec", + "builtAt": "2026-11-27T23:40:00.000Z", + "specSha256": "…", + "catalog": { "source": "server", "version": "0.21.1", "origin": "http://127.0.0.1:8188", "complete": true }, + "widgetOrder": "server", + "rung": "v2-schema", + "ok": true, + "counts": { "nodes": 2, "links": 1, "errors": 0, "warnings": 0 }, + "findings": [] +} +``` + +Which spec bytes, against which catalog, when, with which findings. A question +about a workflow somebody was handed is answerable from the folder. `widgetOrder` +is `server` / `cache` / `core-table` / `workflow-file` — the one field that says +what the widget layout was actually derived from. + +## When it refuses + +| Refusal | What it means | Fix | +|---|---|---| +| `BINDING_UNRESOLVED` | a `@name` has no value | add it to `bindings` (or pass `bindings` to `action=new`) | +| `unknown_widget` | the input is not a widget of that class | the message lists the real ones | +| `unknown_output` | the wire names an output the class does not have | the message lists `slot=NAME:TYPE` | +| `return_type_mismatch` | the wire carries the wrong type | rewire; check `comfy_nodes` for both ends | +| `value_not_in_list` | a combo value the server does not have — or, with no server, a file missing from `models//` (the message names the folder, how many files are there, and the nearest name) | the message lists options / the nearest file | +| `model_folder_absent` (warning) | the graph needs a file from a folder that does not exist under the base path | nothing can be claimed about it until the folder is there | +| `required_input_missing` | a required input was never set | set it, or the class has no default | +| `prompt_no_outputs` | nothing to run the graph for | add `SaveImage` / `SaveVideo` | +| `class_unverified` (warning) | the core table does not cover the class | start ComfyUI for a real check | +| `SCHEMA_REQUIRED` | a canvas was given to a build with no server catalog | start ComfyUI, or validate the `prompt.json` instead | +| `SUBGRAPH_ONLY` | the file's graph is inside a subgraph | unpack it in the app, or `comfy run --workflow` | + +None of these is a crash and none needs the app open to read: each names the +node key, the input and the value, which is what you are looking at. diff --git a/packages/dsh-comfyui/skills/comfyui-workflow-json/SKILL.md b/packages/dsh-comfyui/skills/comfyui-workflow-json/SKILL.md new file mode 100644 index 0000000..5700408 --- /dev/null +++ b/packages/dsh-comfyui/skills/comfyui-workflow-json/SKILL.md @@ -0,0 +1,188 @@ +--- +name: comfyui-workflow-json +description: The two ComfyUI workflow formats - the CANVAS the app saves (nodes, links, widgets_values) and the API PROMPT /prompt accepts - how they map onto each other, and the positional trap in widgets_values where a class that declares control_after_generate shifts every later value by one. Covers Reroute, PrimitiveNode, muted and bypassed nodes, subgraphs, where workflows live on disk, and how to export each format. +whenToUse: Reading, writing, diffing or generating a ComfyUI workflow file; turning a workflow into an API prompt or the reverse; debugging a graph that opens but produces wrong values, or a workflow that runs when exported as API and fails when saved as a canvas. +--- + +# The two files + +ComfyUI has two JSON dialects for one graph and they are not interchangeable. + +| | CANVAS (`workflow.json`) | PROMPT (`prompt.json`) | +|---|---|---| +| written by | the app's **Save** / **Export** | **Export (API)**, and what `/prompt` takes | +| node ids | integers on the canvas | **strings**, as object keys | +| wire | a `links` row pointing at array positions | `[ "", ]` | +| values | `widgets_values`, an UNNAMED positional array | named keys in `inputs` | +| geometry | `pos`, `size`, groups, colours | none | +| opens in the app | yes, that is its purpose | only as an API prompt | +| runs via `/prompt` | after the frontend converts it | directly | + +A project that has to be both readable and runnable needs both. `dsh-comfyui` +keeps the spec as the source and generates the pair. + +## The canvas + +```json +{ + "last_node_id": 7, + "last_link_id": 6, + "nodes": [ + { + "id": 1, + "type": "CheckpointLoaderSimple", + "pos": [40, 60], + "size": [320, 100], + "flags": {}, + "order": 0, + "mode": 0, + "inputs": [], + "outputs": [ + { "name": "MODEL", "type": "MODEL", "links": [1], "slot_index": 0 }, + { "name": "CLIP", "type": "CLIP", "links": [2, 3], "slot_index": 1 }, + { "name": "VAE", "type": "VAE", "links": [4], "slot_index": 2 } + ], + "properties": { "Node name for S&R": "CheckpointLoaderSimple" }, + "widgets_values": ["v1-5-pruned-emaonly-fp16.safetensors"] + } + ], + "links": [ + { "id": 1, "origin_id": 1, "origin_slot": 0, "target_id": 5, "target_slot": 0, "type": "MODEL" } + ], + "groups": [], + "config": {}, + "extra": { "ds": { "scale": 1, "offset": [0, 0] } }, + "version": 0.4 +} +``` + +Three things to know: + +- **`links` has two spellings.** The 0.4 canvas stores objects + (`{id, origin_id, origin_slot, target_id, target_slot, type}`); every older + install stored arrays (`[id, origin, slot, target, slot, type]`). Read both; + write the object form, which is what the current frontend saves. +- **A widget input appears in `inputs` only when a wire feeds it**, and then it + carries `"widget": { "name": "seed" }` to say "this is still a widget, it is + just driven by the wire". A widget nobody wired is not in `inputs` at all. +- **`order` is the execution index**, `mode` is 0 always / 2 muted / 4 bypassed, + and `properties["Node name for S&R"]` is how the app re-creates the node from + a saved workflow. + +### `widgets_values` is positional, and one class shifts it + +The array holds one value per widget input, in the class's own input order — +and **an input that declares `control_after_generate` adds a SECOND value right +after itself**, one of `"fixed"`, `"increment"`, `"decrement"`, `"randomize"`. + +`KSampler` declares it on `seed`, so its array is seven long: + +| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | +|---|---|---|---|---|---|---|---| +| value | `42` | `"fixed"` | `4` | `1.5` | `"lcm"` | `"sgm_uniform"` | `1.0` | +| means | seed | control_after_generate | steps | cfg | sampler | scheduler | denoise | + +A converter that forgets index 1 does not fail. It writes `steps = "fixed"`, +`cfg = 4`, `sampler = 1.5` — and the app opens a graph whose values are all +shifted, with nothing reporting it. `comfy_nodes` action=node prints the order +and marks the shift for any class. + +In the API prompt the control value disappears entirely: it is a UI behaviour, +not graph state. + +```json +{ "seed": 42, "steps": 4, "cfg": 1.5, "sampler_name": "lcm", "scheduler": "sgm_uniform", "denoise": 1.0 } +``` + +### The traps that are not nodes + +| Thing | Stored as | What to do with it | +|---|---|---| +| `Reroute` | a node with one input and one output | follow it through; it is a bend in a wire | +| `PrimitiveNode` | a node whose `widgets_values[0]` is a literal | inline the literal into the widget it feeds | +| `Note`, `MarkdownNote` | a node with no sockets | drop it | +| muted node | `mode: 2` | drop it (it is not executed) | +| bypassed node | `mode: 4` | refuse rather than drop - bypass REWIRES through the node, so dropping it runs a different graph | +| subgraph | `definitions.subgraphs[]` | a frontend construct with virtual input/output nodes (`-10`, `-20`); unpack it in the app before lowering it | +| `GroupNode` | a node standing in for a group | unpack it | + +A workflow exported from a template often has **no top-level nodes at all** — +its graph is inside a subgraph definition. That file is not broken, it is a +different shape, and `/prompt` cannot receive it. + +## The API prompt + +```json +{ + "1": { "class_type": "CheckpointLoaderSimple", "inputs": { "ckpt_name": "v1-5-pruned-emaonly-fp16.safetensors" }, "_meta": { "title": "Load Checkpoint" } }, + "2": { "class_type": "CLIPTextEncode", "inputs": { "text": "a lighthouse", "clip": ["1", 1] }, "_meta": { "title": "Positive" } }, + "5": { + "class_type": "KSampler", + "inputs": { + "model": ["1", 0], "seed": 42, "steps": 4, "cfg": 1.5, + "sampler_name": "lcm", "scheduler": "sgm_uniform", + "positive": ["2", 0], "negative": ["3", 0], + "latent_image": ["4", 0], "denoise": 1.0 + }, + "_meta": { "title": "KSampler" } + } +} +``` + +- **ids are strings**, and a wire is a 2-element array: `[source id as a string, + output slot index]`. An integer id is a `bad_linked_input` waiting to happen. +- **only real inputs.** Hidden inputs (`prompt`, `extra_pnginfo`, `unique_id`) + are supplied by the server and must not appear; `Save Image` therefore has no + `prompt` key in a valid prompt. +- **`_meta.title` is cosmetic** — the app shows it in the queue — and safe to + omit, but it is what makes a history entry readable. +- **the graph runs to its OUTPUT nodes.** A node that feeds nothing is dropped + from the execution set (ComfyUI warns `prompt_no_outputs` only when the set is + empty). + +## Converting, in both directions + +Canvas → prompt, per node: + +1. skip `Reroute` (follow), `PrimitiveNode` (inline its value), notes and + groups, and muted nodes; +2. decode `widgets_values` against the class's widget inputs **in order**, with + the `control_after_generate` shift; +3. for each link into the node, look up the target input's NAME at + `target_slot`, and write `inputs[name] = [String(origin_id), origin_slot]`; +4. skip hidden inputs. + +That decode needs `/object_info`. The array has no names in it, so without the +catalog the numbers cannot be attributed — which is why every tool that reads a +canvas refuses without a complete catalog and says so. + +Prompt → canvas: the reverse, and it also needs geometry the prompt does not +have. Generate it (columns by dependency depth is enough) rather than leaving +every node on `[0, 0]`, or the person opens a graph they cannot see. + +## Where workflows live + +| What | Where | +|---|---| +| the app's own saves | `user/default/workflows/` in the ComfyUI base path | +| templates | shipped with the frontend, listed under **Templates** in the sidebar | +| blueprints (this app version) | `blueprints/*.json` in the ComfyUI source tree | +| API exports | wherever you saved them; nothing in ComfyUI reads them back | + +The base path is what `comfy_status` reports as `base`; on ComfyUI Desktop it is +NOT the app folder — the app is under `Programs/ComfyUI/resources/ComfyUI` and +the models, `input/`, `output/` and `user/` are in the base path. + +## Verifying a file you did not write + +1. `comfy_validate file=` — it identifies a canvas by its `nodes` array and + a prompt by its `{class_type, inputs}` values, and runs the right checks. +2. Look at the RUNG: `v2-schema` means a complete server catalog confirmed every + class and every value; `v1-structural` means only the shapes were checked. +3. Only then `comfy_run file=` — a validated graph is not a finished + render. + +Two rules that catch most bad files: a `links` row whose `target_slot` does not +match the target's `inputs` order, and a `widgets_values` array whose length is +one short for a class that declares `control_after_generate`. Both are silent in +the app until a value is wrong.