[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-854bc3c6-445d-4ec1-bd2e-0bb831087264":3,"$f1KXmColhclgfm6laexTEbvNQiRaDuhPbXal9jwc95Qo":42},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":33},"854bc3c6-445d-4ec1-bd2e-0bb831087264","comfyui-gateway","ComfyUI服务器REST API网关。工作流程管理、任务排队、webhooks、缓存、认证、速率限制和图像交付（URL + base64）。","cat_coding_backend","mod_coding","sickn33,coding","---\nname: comfyui-gateway\ndescription: REST API gateway for ComfyUI servers. Workflow management, job queuing, webhooks, caching, auth, rate limiting, and image delivery (URL + base64).\nrisk: safe\nsource: community\ndate_added: '2026-03-06'\nauthor: renat\ntags:\n- comfyui\n- api-gateway\n- image-generation\n- typescript\ntools:\n- claude-code\n- antigravity\n- cursor\n- gemini-cli\n- codex-cli\n---\n\n# ComfyUI Gateway\n\n## Overview\n\nREST API gateway for ComfyUI servers. Workflow management, job queuing, webhooks, caching, auth, rate limiting, and image delivery (URL + base64).\n\n## When to Use This Skill\n\n- When the user mentions \"comfyui\" or related topics\n- When the user mentions \"comfy ui\" or related topics\n- When the user mentions \"stable diffusion api gateway\" or related topics\n- When the user mentions \"gateway comfyui\" or related topics\n- When the user mentions \"api gateway imagens\" or related topics\n- When the user mentions \"queue imagens\" or related topics\n\n## Do Not Use This Skill When\n\n- The task is unrelated to comfyui gateway\n- A simpler, more specific tool can handle the request\n- The user needs general-purpose assistance without domain expertise\n\n## How It Works\n\nA production-grade REST API gateway that transforms any ComfyUI server into a universal,\nsecure, and scalable service. Supports workflow templates with placeholders, job queuing\nwith priorities, webhook callbacks, result caching, and multiple storage backends.\n\n## Architecture Overview\n\n```\n┌─────────────┐     ┌──────────────────────────────────┐     ┌──────────┐\n│   Clients    │────▶│        ComfyUI Gateway           │────▶│ ComfyUI  │\n│ (curl, n8n,  │     │                                  │     │ Server   │\n│  Claude,     │     │  ┌─────────┐  ┌──────────────┐  │     │ (local\u002F  │\n│  Lovable,    │     │  │ Fastify │  │ BullMQ Queue │  │     │  remote) │\n│  Supabase)   │     │  │ API     │──│ (or in-mem)  │  │     └──────────┘\n│              │◀────│  └─────────┘  └──────────────┘  │\n│              │     │  ┌─────────┐  ┌──────────────┐  │     ┌──────────┐\n│              │     │  │ Auth +  │  │ Storage      │  │────▶│ S3\u002FMinIO │\n│              │     │  │ RateL.  │  │ (local\u002FS3)   │  │     │(optional)│\n│              │     │  └─────────┘  └──────────────┘  │     └──────────┘\n└─────────────┘     └──────────────────────────────────┘\n```\n\n## Components\n\n| Component | Purpose | File(s) |\n|-----------|---------|---------|\n| **API Gateway** | REST endpoints, validation, CORS | `src\u002Fapi\u002F` |\n| **Worker** | Processes jobs, talks to ComfyUI | `src\u002Fworker\u002F` |\n| **ComfyUI Client** | HTTP + WebSocket to ComfyUI | `src\u002Fcomfyui\u002F` |\n| **Workflow Manager** | Template storage, placeholder rendering | `src\u002Fworkflows\u002F` |\n| **Storage Provider** | Local disk + S3-compatible | `src\u002Fstorage\u002F` |\n| **Cache** | Hash-based deduplication | `src\u002Fcache\u002F` |\n| **Notifier** | Webhook with HMAC signing | `src\u002Fnotifications\u002F` |\n| **Auth** | API key + JWT + rate limiting | `src\u002Fauth\u002F` |\n| **DB** | SQLite (better-sqlite3) or Postgres | `src\u002Fdb\u002F` |\n| **CLI** | Init, add-workflow, run, worker | `src\u002Fcli\u002F` |\n\n## Quick Start\n\n```bash\n\n## 1. Install\n\ncd comfyui-gateway\nnpm install\n\n## 2. Configure\n\ncp .env.example .env\n\n## 3. Initialize\n\nnpx tsx src\u002Fcli\u002Findex.ts init\n\n## 4. Add A Workflow\n\nnpx tsx src\u002Fcli\u002Findex.ts add-workflow .\u002Fworkflows\u002Fsdxl_realism_v1.json \\\n  --id sdxl_realism_v1 --schema .\u002Fworkflows\u002Fsdxl_realism_v1.schema.json\n\n## 5. Start (Api + Worker In One Process)\n\nnpm run dev\n\n## Or Separately:\n\nnpm run start:api   # API only\nnpm run start:worker # Worker only\n```\n\n## Environment Variables\n\nAll configuration is via `.env` — nothing is hardcoded:\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `PORT` | `3000` | API server port |\n| `HOST` | `0.0.0.0` | API bind address |\n| `COMFYUI_URL` | `http:\u002F\u002F127.0.0.1:8188` | ComfyUI server URL |\n| `COMFYUI_TIMEOUT_MS` | `300000` | Max wait for ComfyUI (5min) |\n| `API_KEYS` | `\"\"` | Comma-separated API keys (`key:role`) |\n| `JWT_SECRET` | `\"\"` | JWT signing secret (empty = JWT disabled) |\n| `REDIS_URL` | `\"\"` | Redis URL (empty = in-memory queue) |\n| `DATABASE_URL` | `.\u002Fdata\u002Fgateway.db` | SQLite path or Postgres URL |\n| `STORAGE_PROVIDER` | `local` | `local` or `s3` |\n| `STORAGE_LOCAL_PATH` | `.\u002Fdata\u002Foutputs` | Local output directory |\n| `S3_ENDPOINT` | `\"\"` | S3\u002FMinIO endpoint |\n| `S3_BUCKET` | `\"\"` | S3 bucket name |\n| `S3_ACCESS_KEY` | `\"\"` | S3 access key |\n| `S3_SECRET_KEY` | `\"\"` | S3 secret key |\n| `S3_REGION` | `us-east-1` | S3 region |\n| `WEBHOOK_SECRET` | `\"\"` | HMAC signing secret for webhooks |\n| `WEBHOOK_ALLOWED_DOMAINS` | `*` | Comma-separated allowed callback domains |\n| `MAX_CONCURRENCY` | `1` | Parallel jobs per GPU |\n| `MAX_IMAGE_SIZE` | `2048` | Maximum dimension (width or height) |\n| `MAX_BATCH_SIZE` | `4` | Maximum batch size |\n| `CACHE_ENABLED` | `true` | Enable result caching |\n| `CACHE_TTL_SECONDS` | `86400` | Cache TTL (24h) |\n| `RATE_LIMIT_MAX` | `100` | Requests per window |\n| `RATE_LIMIT_WINDOW_MS` | `60000` | Rate limit window (1min) |\n| `LOG_LEVEL` | `info` | Pino log level |\n| `PRIVACY_MODE` | `false` | Redact prompts from logs |\n| `CORS_ORIGINS` | `*` | Allowed CORS origins |\n| `NODE_ENV` | `development` | Environment |\n\n## Health & Capabilities\n\n```\nGET \u002Fhealth\n→ { ok: true, version, comfyui: { reachable, url, models? }, uptime }\n\nGET \u002Fcapabilities\n→ { workflows: [...], maxSize, maxBatch, formats, storageProvider }\n```\n\n## Workflows (Crud)\n\n```\nGET    \u002Fworkflows            → list all workflows\nPOST   \u002Fworkflows            → register new workflow\nGET    \u002Fworkflows\u002F:id        → workflow details + input schema\nPUT    \u002Fworkflows\u002F:id        → update workflow\nDELETE \u002Fworkflows\u002F:id        → remove workflow\n```\n\n## Jobs\n\n```\nPOST   \u002Fjobs                 → create job (returns jobId immediately)\nGET    \u002Fjobs\u002F:jobId          → status + progress + outputs\nGET    \u002Fjobs\u002F:jobId\u002Flogs     → sanitized execution logs\nPOST   \u002Fjobs\u002F:jobId\u002Fcancel   → request cancellation\nGET    \u002Fjobs                 → list jobs (filters: status, workflowId, after, before, limit)\n```\n\n## Outputs\n\n```\nGET    \u002Foutputs\u002F:jobId       → list output files + metadata\nGET    \u002Foutputs\u002F:jobId\u002F:file → download\u002Fstream file\n```\n\n## Job Lifecycle\n\n```\nqueued → running → succeeded\n                 → failed\n                 → canceled\n```\n\n1. Client POSTs to `\u002Fjobs` with workflowId + inputs\n2. Gateway validates, checks cache, checks idempotency\n3. If cache hit → returns existing outputs immediately (status: `cache_hit`)\n4. Otherwise → enqueues job, returns `jobId` + `pollUrl`\n5. Worker picks up job, renders workflow template, submits to ComfyUI\n6. Worker polls ComfyUI for progress (or listens via WebSocket)\n7. On completion → downloads outputs, stores them, updates DB\n8. If callbackUrl → sends signed webhook POST\n9. Client polls `\u002Fjobs\u002F:jobId` or receives webhook\n\n## Workflow Templates\n\nWorkflows are ComfyUI JSON with `{{placeholder}}` tokens. The gateway resolves\nthese at runtime using the job's `inputs` and `params`:\n\n```json\n{\n  \"3\": {\n    \"class_type\": \"KSampler\",\n    \"inputs\": {\n      \"seed\": \"{{seed}}\",\n      \"steps\": \"{{steps}}\",\n      \"cfg\": \"{{cfg}}\",\n      \"sampler_name\": \"{{sampler}}\",\n      \"scheduler\": \"normal\",\n      \"denoise\": 1,\n      \"model\": [\"4\", 0],\n      \"positive\": [\"6\", 0],\n      \"negative\": [\"7\", 0],\n      \"latent_image\": [\"5\", 0]\n    }\n  },\n  \"6\": {\n    \"class_type\": \"CLIPTextEncode\",\n    \"inputs\": {\n      \"text\": \"{{prompt}}\",\n      \"clip\": [\"4\", 1]\n    }\n  }\n}\n```\n\nEach workflow has an `inputSchema` (Zod) that validates what the client sends.\n\n## Security Model\n\n- **API Keys**: `X-API-Key` header; keys configured via `API_KEYS` env var as `key1:admin,key2:user`\n- **JWT**: Optional; when `JWT_SECRET` is set, accepts `Authorization: Bearer \u003Ctoken>`\n- **Roles**: `admin` (full CRUD on workflows + jobs), `user` (create jobs, read own jobs)\n- **Rate Limiting**: Per key + per IP, configurable window and max\n- **Webhook Security**: HMAC-SHA256 signature in `X-Signature` header\n- **Callback Allowlist**: Only approved domains receive webhooks\n- **Privacy Mode**: When enabled, prompts are redacted from logs and DB\n- **Idempotency**: `metadata.requestId` prevents duplicate processing\n- **CORS**: Configurable allowed origins\n- **Input Validation**: Zod schemas on every endpoint; max size\u002Fbatch enforced\n\n## Comfyui Integration\n\nThe gateway communicates with ComfyUI via its native HTTP API:\n\n| ComfyUI Endpoint | Gateway Usage |\n|------------------|---------------|\n| `POST \u002Fprompt` | Submit rendered workflow |\n| `GET \u002Fhistory\u002F{id}` | Poll job completion |\n| `GET \u002Fview?filename=...` | Download generated images |\n| `GET \u002Fobject_info` | Discover available nodes\u002Fmodels |\n| `WS \u002Fws?clientId=...` | Real-time progress (optional) |\n\nThe client auto-detects ComfyUI version and adapts:\n- Tries WebSocket first for progress, falls back to polling\n- Handles both `\u002Fhistory` response formats\n- Detects OOM errors and classifies them with recommendations\n\n## Cache Strategy\n\nCache key = SHA-256 of `workflowId + sorted(inputs) + sorted(params) + checkpoint`.\nOn cache hit, the gateway returns a \"virtual\" job with pre-existing outputs — no GPU\ncomputation needed. Cache is stored alongside job data in the DB with configurable TTL.\n\n## Error Classification\n\n| Error Code | Meaning | Retry? |\n|------------|---------|--------|\n| `COMFYUI_UNREACHABLE` | Cannot connect to ComfyUI | Yes (with backoff) |\n| `COMFYUI_OOM` | Out of memory on GPU | No (reduce dimensions) |\n| `COMFYUI_TIMEOUT` | Execution exceeded timeout | Maybe (increase timeout) |\n| `COMFYUI_NODE_ERROR` | Node execution failed | No (check workflow) |\n| `VALIDATION_ERROR` | Invalid inputs | No (fix request) |\n| `WORKFLOW_NOT_FOUND` | Unknown workflowId | No (register workflow) |\n| `RATE_LIMITED` | Too many requests | Yes (wait) |\n| `AUTH_FAILED` | Invalid\u002Fmissing credentials | No (fix auth) |\n| `CACHE_HIT` | (Not an error) Served from cache | N\u002FA |\n\n## Bundled Workflows\n\nThree production-ready workflow templates are included:\n\n## 1. `Sdxl_Realism_V1` — Photorealistic Generation\n\n- Checkpoint: SDXL base\n- Optimized for: Portraits, landscapes, product shots\n- Default: 1024x1024, 30 steps, cfg 7.0\n\n## 2. `Sprite_Transparent_Bg` — Game Sprites With Alpha\n\n- Checkpoint: SD 1.5 or SDXL\n- Optimized for: 2D game assets, transparent backgrounds\n- Default: 512x512, 25 steps, cfg 7.5\n\n## 3. `Icon_512` — App Icons With Optional Upscale\n\n- Checkpoint: SDXL base\n- Optimized for: Square icons, clean edges\n- Default: 512x512, 20 steps, cfg 6.0, optional 2x upscale\n\n## Observability\n\n- **Structured Logs**: Pino JSON logs with `correlationId` on every request\n- **Metrics**: Jobs queued\u002Frunning\u002Fsucceeded\u002Ffailed, avg processing time, cache hit rate\n- **Audit Log**: Admin actions (workflow CRUD, key management) logged with timestamp + actor\n\n## Cli Reference\n\n```bash\nnpx tsx src\u002Fcli\u002Findex.ts init                    # Create dirs, .env.example\nnpx tsx src\u002Fcli\u002Findex.ts add-workflow \u003Cfile>      # Register workflow template\n  --id \u003Cid> --name \u003Cname> --schema \u003Cschema.json>\nnpx tsx src\u002Fcli\u002Findex.ts list-workflows           # Show registered workflows\nnpx tsx src\u002Fcli\u002Findex.ts run                      # Start API server\nnpx tsx src\u002Fcli\u002Findex.ts worker                   # Start job worker\nnpx tsx src\u002Fcli\u002Findex.ts health                   # Check ComfyUI connectivity\n```\n\n## Troubleshooting\n\nRead `references\u002Ftroubleshooting.md` for detailed guidance on:\n- ComfyUI not reachable (firewall, wrong port, Docker networking)\n- OOM errors (reduce resolution, batch, or steps)\n- Slow generation (GPU utilization, queue depth, model loading)\n- Webhook failures (DNS, SSL, timeout, domain allowlist)\n- Redis connection issues (fallback to in-memory)\n- Storage permission errors (local path, S3 credentials)\n\n## Integration Examples\n\nRead `references\u002Fintegration.md` for ready-to-use examples with:\n- curl commands for every endpoint\n- n8n webhook workflow\n- Supabase Edge Function caller\n- Claude Code \u002F Claude.ai integration\n- Python requests client\n- JavaScript fetch client\n\n## File Structure\n\n```\ncomfyui-gateway\u002F\n├── SKILL.md\n├── package.json\n├── tsconfig.json\n├── .env.example\n├── src\u002F\n│   ├── api\u002F\n│   │   ├── server.ts          # Fastify setup + plugins\n│   │   ├── routes\u002F\n│   │   │   ├── health.ts      # GET \u002Fhealth, \u002Fcapabilities\n│   │   │   ├── workflows.ts   # CRUD \u002Fworkflows\n│   │   │   ├── jobs.ts        # CRUD \u002Fjobs\n│   │   │   └── outputs.ts     # GET \u002Foutputs\n│   │   ├── middleware\u002F\n│   │   │   └── error-handler.ts\n│   │   └── plugins\u002F\n│   │       ├── auth.ts        # API key + JWT\n│   │       ├── rate-limit.ts\n│   │       └── cors.ts\n│   ├── worker\u002F\n│   │   └── processor.ts       # Job processor\n│   ├── comfyui\u002F\n│   │   └── client.ts          # ComfyUI HTTP + WS client\n│   ├── storage\u002F\n│   │   ├── index.ts           # Provider factory\n│   │   ├── local.ts           # Local filesystem\n│   │   └── s3.ts              # S3-compatible\n│   ├── workflows\u002F\n│   │   └── manager.ts         # Template CRUD + rendering\n│   ├── cache\u002F\n│   │   └── index.ts           # Hash-based cache\n│   ├── notifications\u002F\n│   │   └── webhook.ts         # HMAC-signed callbacks\n│   ├── auth\u002F\n│   │   └── index.ts           # Key\u002FJWT validation + roles\n│   ├── db\u002F\n│   │   ├── index.ts           # DB factory (SQLite\u002FPostgres)\n│   │   └── migrations.ts      # Schema creation\n│   ├── cli\u002F\n│   │   └── index.ts           # CLI commands\n│   ├── utils\u002F\n│   │   ├── config.ts          # Env loading + validation\n│   │   ├── errors.ts          # Error classes\n│   │   ├── logger.ts          # Pino setup\n│   │   └── hash.ts            # SHA-256 hashing\n│   └── index.ts               # Main entrypoint\n├── config\u002F\n│   └── workflows\u002F             # Bundled workflow templates\n│       ├── sdxl_realism_v1.json\n│       ├── sdxl_realism_v1.schema.json\n│       ├── sprite_transparent_bg.json\n│       ├── sprite_transparent_bg.schema.json\n│       ├── icon_512.json\n│       └── icon_512.schema.json\n├── data\u002F\n│   ├── outputs\u002F               # Generated images\n│   ├── workflows\u002F             # User-added wor\n\n## Best Practices\n\n- Provide clear, specific context about your project and requirements\n- Review all suggestions before applying them to production code\n- Combine with other complementary skills for comprehensive analysis\n\n## Common Pitfalls\n\n- Using this skill for tasks outside its domain expertise\n- Applying recommendations without understanding your specific context\n- Not providing enough project context for accurate analysis\n\n## Related Skills\n\n- `ai-studio-image` - Complementary skill for enhanced analysis\n- `image-studio` - Complementary skill for enhanced analysis\n- `stability-ai` - Complementary skill for enhanced analysis\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,137,2077,"2026-05-16 13:12:17",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"编程开发","coding","mdi-code-braces","代码生成、调试、审查，提升开发效率",2,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":25,"skillCount":32,"createdAt":26},"后端开发","backend","mdi-server","API、数据库、服务端架构",296,[34],{"id":35,"skillId":4,"version":36,"fileName":37,"fileSize":38,"filePath":39,"fileHash":40,"manifest":41,"createdAt":19},"1d17c485-7eec-49d7-a7b6-638e92690cc8","1.0.0","comfyui-gateway.zip",30471,"uploads\u002Fskills\u002F854bc3c6-445d-4ec1-bd2e-0bb831087264\u002Fcomfyui-gateway.zip","dc1691bba3753efa091f082e6db3e1a6f5389050876f5120814a98754a2994ea","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":16299},{\"path\":\"references\u002Fintegration.md\",\"isDirectory\":false,\"size\":48284},{\"path\":\"references\u002Ftroubleshooting.md\",\"isDirectory\":false,\"size\":29528}]",{"code":43,"message":44,"data":45},200,"success",{"items":46,"stats":47,"page":50},[],{"averageRating":48,"totalRatings":48,"ratingCounts":49},0,[48,48,48,48,48],{"limit":51,"offset":48,"hasMore":52,"nextOffset":51,"ratedOnly":16},15,false]