sdk

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 30 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sdk is a Go client for the Comfy API v2: Comfy Cloud, or any deployment that speaks the same contract, such as comfy-api-proxy in front of a self-hosted ComfyUI. Code written against it runs unchanged on either; only the base URL and key differ.

It is a port of the Python comfy-sdk's v2 surface: local blake3 dedup uploads, core/ASSET substitution, idempotent submit with Retry-After backoff, polling with an adaptive schedule, a live SSE event stream backed by polling, range-aware downloads, and typed errors.

client, err := sdk.New(sdk.WithBaseURL("http://127.0.0.1:8189")) // or COMFY_BASE_URL
wf, err := sdk.WorkflowFromFile("workflow_api.json")
wf.SetInput("10", "image", client.AssetFromFile("photo.png"))
job, err := client.Run(ctx, wf, sdk.SubmitOptions{})
err = job.GetOutputs("9")[0].ToFile(ctx, "out.png", nil)

Targets and credentials

The base URL is WithBaseURL, else COMFY_BASE_URL, else CloudBaseURL. The key is WithAPIKey, else COMFY_API_KEY. Comfy Cloud requires a key; another deployment without auth needs none. The bearer token is sent only to the base URL's origin and the Comfy Router origin.

Errors

Every failure the API reports is an *APIError. Match it with errors.Is against a sentinel such as ErrNotFound, or read its fields with errors.As. A failure that produced no response is a *TransportError. A job that ends other than succeeded is a *JobFailedError from Job.Result and Client.Run.

Comfy Router

Client.Models runs hosted models on Comfy Router with the same key. Model runs are billed; see Models.Run and RetryPolicy.

Concurrency

A Client, Job, Asset, and Models are safe for concurrent use.

Index

Examples

Constants

View Source
const (
	// CloudBaseURL is the hosted Comfy Cloud deployment, the default target.
	CloudBaseURL = "https://cloud.comfy.org"
	// BaseURLEnv names another deployment to target.
	BaseURLEnv = "COMFY_BASE_URL"
	// APIKeyEnv is read when no key is passed.
	APIKeyEnv = "COMFY_API_KEY"
	// RouterBaseURL is Comfy Router, where client.Models sends requests. A
	// separate host from the v2 API: one serves jobs and assets, the other
	// model-id addressed runs, and neither serves the other's routes.
	RouterBaseURL = "https://api.comfy.org"
	// RouterBaseURLEnv names another Router deployment.
	RouterBaseURLEnv = "COMFY_ROUTER_BASE_URL"
)
View Source
const (
	StatusQueued    = "queued"
	StatusRunning   = "running"
	StatusSucceeded = "succeeded"
	StatusCanceling = "canceling"
	StatusCanceled  = "canceled"
	StatusFailed    = "failed"
	StatusExpired   = "expired"
)

Job statuses. Canceling is not terminal: cancellation lands at the next node boundary and can take seconds.

View Source
const (

	// Completed is the queue status of a finished request, failed or not.
	Completed = "COMPLETED"
)

Router paths, under the Router base URL.

Variables

View Source
var (
	ErrMissingAPIKey       = errors.New("missing API key")
	ErrNotFound            = errors.New("not found")
	ErrInvalidWorkflow     = errors.New("invalid workflow")
	ErrWorkflowFormatUI    = errors.New("workflow is in UI-export format")
	ErrMissingAsset        = errors.New("missing asset")
	ErrHashMismatch        = errors.New("hash mismatch")
	ErrBlobNotFound        = errors.New("blob not found")
	ErrIdempotencyKeyReuse = errors.New("idempotency key reuse")
	ErrQueueFull           = errors.New("queue full")
	ErrUnauthorized        = errors.New("unauthorized")
	ErrForbidden           = errors.New("forbidden")
	ErrInsufficientCredits = errors.New("insufficient credits")
	ErrJobFailed           = errors.New("job failed")
	ErrInvalidResponse     = errors.New("invalid response")
)

Sentinel errors for the failure kinds a caller branches on. Every error the API returns is an *APIError, and errors.Is matches it against these by its code, so callers write errors.Is(err, sdk.ErrNotFound).

View Source
var (
	ErrRouter                   = errors.New("router error")
	ErrInvalidInput             = errors.New("invalid input")
	ErrContentPolicyViolation   = errors.New("content policy violation")
	ErrProviderError            = errors.New("provider error")
	ErrProviderTimeout          = errors.New("provider timeout")
	ErrModelNotFound            = errors.New("model not found")
	ErrConcurrencyLimitExceeded = errors.New("concurrency limit exceeded")
	ErrClientDisconnected       = errors.New("client disconnected")
	ErrInternalError            = errors.New("internal error")
	ErrDeadlineExceeded         = errors.New("deadline exceeded")
	ErrNotEnabled               = errors.New("not enabled")
	ErrServiceUnavailable       = errors.New("service unavailable")
	ErrRateLimited              = errors.New("rate limited")
	ErrCancelled                = errors.New("cancelled")
	ErrQueueTimeout             = errors.New("queue timeout")
	ErrRequestNotFound          = errors.New("request not found")
	ErrQueueBacklogFull         = errors.New("queue backlog full")
	// ErrCancelRefused is a 409 refusal to cancel; ErrAlreadyCompleted, the
	// one refusal the contract names, also matches it.
	ErrCancelRefused    = errors.New("cancel refused")
	ErrAlreadyCompleted = errors.New("already completed")
)

Comfy Router error buckets, one per x-comfy-error-types value in the Router contract, in its order. ErrRouter matches any of them, and any error the Router labelled with a bucket this SDK does not know yet.

View Source
var DefaultRetry = RetryPolicy{
	MaxElapsed:        60 * time.Second,
	InitialBackoff:    500 * time.Millisecond,
	BackoffFactor:     2,
	MaxBackoff:        15 * time.Second,
	Jitter:            true,
	RetryCollectable:  true,
	CollectMaxElapsed: 20 * time.Minute,
}

DefaultRetry is the policy client.Models uses unless replaced.

View Source
var ErrIdleTimeout = errors.New("response body idle too long")

ErrIdleTimeout reports a response body that sent nothing for the idle limit. It arrives wrapped in a *TransportError.

View Source
var NoRetry = RetryPolicy{InitialBackoff: 500 * time.Millisecond, BackoffFactor: 2, MaxBackoff: 15 * time.Second}

NoRetry makes every Router call exactly one attempt.

View Source
var RouterErrorTypes = []string{
	"invalid_input", "content_policy_violation", "provider_error", "provider_timeout",
	"insufficient_credits", "model_not_found", "unauthorized", "forbidden",
	"concurrency_limit_exceeded", "client_disconnected", "internal_error", "deadline_exceeded",
	"not_enabled", "service_unavailable", "rate_limited", "cancelled", "queue_timeout",
	"request_not_found", "queue_backlog_full",
}

RouterErrorTypes lists the Router buckets in contract order.

Functions

func IsTerminal

func IsTerminal(status string) bool

IsTerminal reports whether a job in status will not change again.

func ParseModelID

func ParseModelID(model string) (string, string, error)

ParseModelID splits a "{provider}/{model}" id. A three-segment variant id is not addressable on the run route yet, and "." or ".." segments would walk the request path, so both are refused.

func ParseRequestID

func ParseRequestID(id string) error

ParseRequestID checks a queued request id can address its routes.

func ValidateIdempotencyKey

func ValidateIdempotencyKey(key string) error

ValidateIdempotencyKey checks what the contract can carry: 1 to 255 printable ASCII characters, since the value rides an HTTP header.

Types

type APIError

type APIError struct {
	// Code is the wire code, such as "not_found", or "http_<status>" when the
	// server named none the SDK recognizes.
	Code       string
	Message    string
	HTTPStatus int
	Details    map[string]any
	// RequestID is the server's X-Comfy-Request-Id, cleaned to a bounded,
	// printable token so it is safe to log.
	RequestID string
	// RetryAfter is the Retry-After header in seconds, nil when absent.
	RetryAfter *int
	// IdempotencyKey is the key a failed submit was sent under, so a caller
	// can poll or list for the job an ambiguous failure may have created.
	IdempotencyKey string
	// BodyExcerpt is a cleaned, bounded slice of a body that carried no
	// message, such as a proxy's HTML error page.
	BodyExcerpt string
	// ErrorType is a Comfy Router error bucket, when the server sent one.
	ErrorType string
	// Validation holds a Router validation response's entries.
	Validation []ValidationErrorDetail
	// ResendRefused marks a model run whose retry was refused as a key
	// reuse after an earlier attempt may have claimed the key. The error
	// reported is that earlier attempt's; the generation may have happened
	// and been billed, so collect it rather than starting a new one.
	ResendRefused bool
}

APIError is a failure the API reported, or one the SDK refused locally before sending anything. Fields the failure did not carry are zero.

Example
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
	"sync"

	"github.com/regiellis/comfy-api-proxy-go/sdk"
)

// fakeAPI is a minimal in-process Comfy API v2 deployment for the examples:
// one job, one output, single-use idempotency keys, and metadata stored as
// the client sent it.
type fakeAPI struct {
	mu       sync.Mutex
	keys     map[string]bool
	metadata json.RawMessage
}

func newFakeAPI() (*fakeAPI, *httptest.Server) {
	f := &fakeAPI{keys: map[string]bool{}}
	mux := http.NewServeMux()
	mux.HandleFunc("POST /api/v2/jobs", f.submit)
	mux.HandleFunc("GET /api/v2/jobs", f.list)
	mux.HandleFunc("GET /api/v2/jobs/{id}", f.get)
	mux.HandleFunc("GET /api/v2/jobs/{id}/events", f.events)
	mux.HandleFunc("GET /api/v2/assets/{id}/content", f.content)
	return f, httptest.NewServer(mux)
}

func (f *fakeAPI) job(status string) map[string]any {
	f.mu.Lock()
	defer f.mu.Unlock()
	return map[string]any{
		"id": "job-1", "status": status, "created_at": "2026-10-27T10:00:00Z",
		"metadata": f.metadata,
		"outputs": []any{map[string]any{
			"node_id": "9", "name": "out.png", "type": "image", "content_type": "image/png",
			"size_bytes": 8, "id": "out-1",
		}},
	}
}

func reply(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	if err := json.NewEncoder(w).Encode(v); err != nil {
		return
	}
}

func replyError(w http.ResponseWriter, status int, code, message string) {
	reply(w, status, map[string]any{"error": map[string]any{"code": code, "message": message, "details": nil}})
}

func (f *fakeAPI) submit(w http.ResponseWriter, r *http.Request) {
	var body struct {
		Metadata json.RawMessage `json:"metadata"`
	}
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		replyError(w, http.StatusBadRequest, "invalid_request", err.Error())
		return
	}
	key := r.Header.Get("Idempotency-Key")
	f.mu.Lock()
	reused := f.keys[key]
	f.keys[key] = true
	if !reused {
		f.metadata = body.Metadata
	}
	f.mu.Unlock()
	if reused {
		replyError(w, http.StatusUnprocessableEntity, "idempotency_key_reuse", "This Idempotency-Key has already been used.")
		return
	}
	reply(w, http.StatusCreated, f.job(sdk.StatusQueued))
}

func (f *fakeAPI) list(w http.ResponseWriter, _ *http.Request) {
	reply(w, http.StatusOK, map[string]any{"jobs": []any{f.job(sdk.StatusSucceeded)}})
}

func (f *fakeAPI) get(w http.ResponseWriter, r *http.Request) {
	if r.PathValue("id") != "job-1" {
		replyError(w, http.StatusNotFound, "not_found", "No job "+r.PathValue("id")+".")
		return
	}
	reply(w, http.StatusOK, f.job(sdk.StatusSucceeded))
}

func (f *fakeAPI) events(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "text/event-stream")
	frames := "event: status\ndata: {\"status\":\"running\"}\n\n" +
		"event: progress\ndata: {\"value\":0.5,\"nodes_done\":1,\"nodes_total\":2}\n\n" +
		"event: status\ndata: {\"status\":\"succeeded\"}\n\n"
	if _, err := io.WriteString(w, frames); err != nil {
		return
	}
}

func (f *fakeAPI) content(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "image/png")
	if _, err := io.WriteString(w, "PNG data"); err != nil {
		return
	}
}

func main() {
	_, srv := newFakeAPI()
	defer srv.Close()
	client, err := sdk.New(sdk.WithBaseURL(srv.URL))
	if err != nil {
		log.Fatal(err)
	}

	_, err = client.GetJob(context.Background(), "no-such-job")
	if errors.Is(err, sdk.ErrNotFound) {
		fmt.Println("not found")
	}
	var apiErr *sdk.APIError
	if errors.As(err, &apiErr) {
		fmt.Println(apiErr.HTTPStatus, apiErr.Code, apiErr.Message)
	}
}
Output:
not found
404 not_found No job no-such-job.

func (*APIError) Error

func (e *APIError) Error() string

Error is the server's message, followed by a body excerpt when the response carried no message.

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is matches the sentinel for the error's code, mirroring the Python SDK's class tree: a UI-format workflow is also an invalid workflow, an already-completed refusal is also a cancel refusal, and anything the Router labelled with a bucket is an ErrRouter.

type Asset

type Asset struct {
	// contains filtered or unexported fields
}

Asset is an input file. It is lazy: nothing is hashed or sent until Commit, which a Submit carrying it in the graph calls. Commit first asks the server whether it already holds identical bytes (by blake3 hash) and only uploads when it does not. An Asset is safe for concurrent use.

func (*Asset) Commit

func (a *Asset) Commit(ctx context.Context) (string, error)

Commit makes the asset exist server-side and returns its id. Idempotent: a committed asset returns at once. A retried upload reuses one Idempotency-Key per asset, so it cannot create a second copy.

func (*Asset) CreatedNew

func (a *Asset) CreatedNew() *bool

CreatedNew reports whether the commit stored new bytes (true) or matched bytes the server already had (false). Nil before commit.

func (*Asset) Delete

func (a *Asset) Delete(ctx context.Context) error

Delete removes the committed asset.

func (*Asset) DownloadURL

func (a *Asset) DownloadURL(ctx context.Context) (DownloadURL, error)

DownloadURL commits the asset and resolves a URL for its bytes.

func (*Asset) ExpiresAt

func (a *Asset) ExpiresAt() *time.Time

ExpiresAt is the asset's retention deadline, nil when it has none.

func (*Asset) FilePath

func (a *Asset) FilePath() string

FilePath is the name the asset is uploaded under.

func (*Asset) Hash

func (a *Asset) Hash() (string, error)

Hash is the local blake3 hash, computed once. It is only a dedup hint; the server recomputes it from the bytes it receives.

func (*Asset) ID

func (a *Asset) ID() string

ID is the server's asset id, empty until committed.

func (*Asset) JobID

func (a *Asset) JobID() *string

JobID is the job that produced this asset; nil for uploads.

func (*Asset) Reference

func (a *Asset) Reference(ctx context.Context) (map[string]any, error)

Reference commits the asset and returns its core/ASSET reference, the object a workflow input carries. It holds the asset's operation slot throughout, so a concurrent Delete cannot slip between the commit and the reference it returns.

type BinaryResult

type BinaryResult struct {
	Content     []byte
	ContentType string
	RequestID   string
}

BinaryResult is a model's own bytes, for a partner that answers with the generation itself rather than JSON.

type CatalogModel

type CatalogModel struct {
	ID       string
	Provider string
	Model    string
	// Billing holds per-model billing facts (never prices), as the server
	// sent them, so a field it adds reaches the caller without a release.
	Billing map[string]any
}

CatalogModel is one runnable model.

type Client

type Client struct {

	// Models runs hosted models on Comfy Router, sharing this client's key.
	Models *Models
	// contains filtered or unexported fields
}

Client talks to one Comfy API v2 deployment and to Comfy Router. It is safe for concurrent use.

func New

func New(opts ...Option) (*Client, error)

New builds a client. The target is WithBaseURL, else COMFY_BASE_URL, else Comfy Cloud. The key is WithAPIKey, else COMFY_API_KEY; blank counts as unset at either source. Comfy Cloud always needs a key, so its absence there is ErrMissingAPIKey here rather than a 401 on the first call. Another deployment may have no auth, so there no key means send no credentials.

Example
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
	"sync"

	"github.com/regiellis/comfy-api-proxy-go/sdk"
)

// fakeAPI is a minimal in-process Comfy API v2 deployment for the examples:
// one job, one output, single-use idempotency keys, and metadata stored as
// the client sent it.
type fakeAPI struct {
	mu       sync.Mutex
	keys     map[string]bool
	metadata json.RawMessage
}

func newFakeAPI() (*fakeAPI, *httptest.Server) {
	f := &fakeAPI{keys: map[string]bool{}}
	mux := http.NewServeMux()
	mux.HandleFunc("POST /api/v2/jobs", f.submit)
	mux.HandleFunc("GET /api/v2/jobs", f.list)
	mux.HandleFunc("GET /api/v2/jobs/{id}", f.get)
	mux.HandleFunc("GET /api/v2/jobs/{id}/events", f.events)
	mux.HandleFunc("GET /api/v2/assets/{id}/content", f.content)
	return f, httptest.NewServer(mux)
}

func (f *fakeAPI) job(status string) map[string]any {
	f.mu.Lock()
	defer f.mu.Unlock()
	return map[string]any{
		"id": "job-1", "status": status, "created_at": "2026-10-27T10:00:00Z",
		"metadata": f.metadata,
		"outputs": []any{map[string]any{
			"node_id": "9", "name": "out.png", "type": "image", "content_type": "image/png",
			"size_bytes": 8, "id": "out-1",
		}},
	}
}

func reply(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	if err := json.NewEncoder(w).Encode(v); err != nil {
		return
	}
}

func replyError(w http.ResponseWriter, status int, code, message string) {
	reply(w, status, map[string]any{"error": map[string]any{"code": code, "message": message, "details": nil}})
}

func (f *fakeAPI) submit(w http.ResponseWriter, r *http.Request) {
	var body struct {
		Metadata json.RawMessage `json:"metadata"`
	}
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		replyError(w, http.StatusBadRequest, "invalid_request", err.Error())
		return
	}
	key := r.Header.Get("Idempotency-Key")
	f.mu.Lock()
	reused := f.keys[key]
	f.keys[key] = true
	if !reused {
		f.metadata = body.Metadata
	}
	f.mu.Unlock()
	if reused {
		replyError(w, http.StatusUnprocessableEntity, "idempotency_key_reuse", "This Idempotency-Key has already been used.")
		return
	}
	reply(w, http.StatusCreated, f.job(sdk.StatusQueued))
}

func (f *fakeAPI) list(w http.ResponseWriter, _ *http.Request) {
	reply(w, http.StatusOK, map[string]any{"jobs": []any{f.job(sdk.StatusSucceeded)}})
}

func (f *fakeAPI) get(w http.ResponseWriter, r *http.Request) {
	if r.PathValue("id") != "job-1" {
		replyError(w, http.StatusNotFound, "not_found", "No job "+r.PathValue("id")+".")
		return
	}
	reply(w, http.StatusOK, f.job(sdk.StatusSucceeded))
}

func (f *fakeAPI) events(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "text/event-stream")
	frames := "event: status\ndata: {\"status\":\"running\"}\n\n" +
		"event: progress\ndata: {\"value\":0.5,\"nodes_done\":1,\"nodes_total\":2}\n\n" +
		"event: status\ndata: {\"status\":\"succeeded\"}\n\n"
	if _, err := io.WriteString(w, frames); err != nil {
		return
	}
}

func (f *fakeAPI) content(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "image/png")
	if _, err := io.WriteString(w, "PNG data"); err != nil {
		return
	}
}

func main() {
	_, srv := newFakeAPI()
	defer srv.Close()

	// Against a local comfy-api-proxy you would pass "http://127.0.0.1:8189".
	client, err := sdk.New(
		sdk.WithBaseURL(srv.URL),
		sdk.WithAPIKey("example-token"),
		sdk.WithClientInfo("my-app/1.0"),
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("authenticated:", client.Authenticated())
}
Output:
authenticated: true

func (*Client) AssetFromBytes

func (c *Client) AssetFromBytes(data []byte, filename, contentType string) *Asset

AssetFromBytes uploads an in-memory buffer. An empty filename becomes "upload.bin"; an empty content type is guessed from the filename.

func (*Client) AssetFromFile

func (c *Client) AssetFromFile(p string) *Asset

AssetFromFile streams a file from disk, hashed and uploaded on commit.

func (*Client) AssetFromReader

func (c *Client) AssetFromReader(r io.Reader, filename, contentType string) (*Asset, error)

AssetFromReader reads r to the end and uploads the bytes.

func (*Client) AssetFromURL

func (c *Client) AssetFromURL(ctx context.Context, rawURL string) (*Asset, error)

AssetFromURL downloads url and uploads its bytes. The client's bearer token goes with the download only when url is on the client's own origin, and the download is cancelled if the body stalls for the client's timeout.

func (*Client) Authenticated

func (c *Client) Authenticated() bool

Authenticated reports whether the client sends a bearer token.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL is the target with any embedded credentials redacted.

func (*Client) DeleteAsset

func (c *Client) DeleteAsset(ctx context.Context, id string) error

DeleteAsset deletes an asset by id.

func (*Client) GetAsset

func (c *Client) GetAsset(ctx context.Context, id string) (*Asset, error)

GetAsset fetches an already-committed asset.

func (*Client) GetJob

func (c *Client) GetJob(ctx context.Context, id string) (*Job, error)

GetJob fetches a job by id.

func (*Client) ListJobs

func (c *Client) ListJobs(ctx context.Context, opts ListOptions) iter.Seq2[JobSummary, error]

ListJobs walks every job the client can see, newest first, a page at a time, stopping at the first error.

func (*Client) Run

func (c *Client) Run(ctx context.Context, wf *Workflow, opts SubmitOptions) (*Job, error)

Run submits, then polls until the job ends. A job that ends other than succeeded is a *JobFailedError. Bound it with the context.

Example
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
	"sync"

	"github.com/regiellis/comfy-api-proxy-go/sdk"
)

// fakeAPI is a minimal in-process Comfy API v2 deployment for the examples:
// one job, one output, single-use idempotency keys, and metadata stored as
// the client sent it.
type fakeAPI struct {
	mu       sync.Mutex
	keys     map[string]bool
	metadata json.RawMessage
}

func newFakeAPI() (*fakeAPI, *httptest.Server) {
	f := &fakeAPI{keys: map[string]bool{}}
	mux := http.NewServeMux()
	mux.HandleFunc("POST /api/v2/jobs", f.submit)
	mux.HandleFunc("GET /api/v2/jobs", f.list)
	mux.HandleFunc("GET /api/v2/jobs/{id}", f.get)
	mux.HandleFunc("GET /api/v2/jobs/{id}/events", f.events)
	mux.HandleFunc("GET /api/v2/assets/{id}/content", f.content)
	return f, httptest.NewServer(mux)
}

func (f *fakeAPI) job(status string) map[string]any {
	f.mu.Lock()
	defer f.mu.Unlock()
	return map[string]any{
		"id": "job-1", "status": status, "created_at": "2026-10-27T10:00:00Z",
		"metadata": f.metadata,
		"outputs": []any{map[string]any{
			"node_id": "9", "name": "out.png", "type": "image", "content_type": "image/png",
			"size_bytes": 8, "id": "out-1",
		}},
	}
}

func reply(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	if err := json.NewEncoder(w).Encode(v); err != nil {
		return
	}
}

func replyError(w http.ResponseWriter, status int, code, message string) {
	reply(w, status, map[string]any{"error": map[string]any{"code": code, "message": message, "details": nil}})
}

func (f *fakeAPI) submit(w http.ResponseWriter, r *http.Request) {
	var body struct {
		Metadata json.RawMessage `json:"metadata"`
	}
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		replyError(w, http.StatusBadRequest, "invalid_request", err.Error())
		return
	}
	key := r.Header.Get("Idempotency-Key")
	f.mu.Lock()
	reused := f.keys[key]
	f.keys[key] = true
	if !reused {
		f.metadata = body.Metadata
	}
	f.mu.Unlock()
	if reused {
		replyError(w, http.StatusUnprocessableEntity, "idempotency_key_reuse", "This Idempotency-Key has already been used.")
		return
	}
	reply(w, http.StatusCreated, f.job(sdk.StatusQueued))
}

func (f *fakeAPI) list(w http.ResponseWriter, _ *http.Request) {
	reply(w, http.StatusOK, map[string]any{"jobs": []any{f.job(sdk.StatusSucceeded)}})
}

func (f *fakeAPI) get(w http.ResponseWriter, r *http.Request) {
	if r.PathValue("id") != "job-1" {
		replyError(w, http.StatusNotFound, "not_found", "No job "+r.PathValue("id")+".")
		return
	}
	reply(w, http.StatusOK, f.job(sdk.StatusSucceeded))
}

func (f *fakeAPI) events(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "text/event-stream")
	frames := "event: status\ndata: {\"status\":\"running\"}\n\n" +
		"event: progress\ndata: {\"value\":0.5,\"nodes_done\":1,\"nodes_total\":2}\n\n" +
		"event: status\ndata: {\"status\":\"succeeded\"}\n\n"
	if _, err := io.WriteString(w, frames); err != nil {
		return
	}
}

func (f *fakeAPI) content(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "image/png")
	if _, err := io.WriteString(w, "PNG data"); err != nil {
		return
	}
}

// demoWorkflow is a two-node API-format graph.
func demoWorkflow() *sdk.Workflow {
	return sdk.NewWorkflow(map[string]any{
		"3": map[string]any{"class_type": "KSampler", "inputs": map[string]any{"seed": 42, "steps": 1}},
		"9": map[string]any{"class_type": "SaveImage", "inputs": map[string]any{"images": []any{"3", 0}}},
	})
}

func main() {
	_, srv := newFakeAPI()
	defer srv.Close()
	client, err := sdk.New(sdk.WithBaseURL(srv.URL))
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	job, err := client.Run(ctx, demoWorkflow(), sdk.SubmitOptions{})
	if err != nil {
		log.Fatal(err)
	}
	for _, o := range job.GetOutputs("9") {
		data, err := o.Bytes(ctx, nil)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%s %s %q\n", o.Name(), o.ContentType(), data)
	}
}
Output:
out.png image/png "PNG data"

func (*Client) String

func (c *Client) String() string

String reports the target and whether a key is attached, never the key.

func (*Client) Submit

func (c *Client) Submit(ctx context.Context, wf *Workflow, opts SubmitOptions) (*Job, error)

Submit sends a workflow and returns its job. Asset handles in the graph are uploaded (or deduped) first and replaced with core/ASSET references. A 429 carrying Retry-After is retried for up to a minute. Any error from the submission carries the idempotency key it was sent under.

Example
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
	"sync"

	"github.com/regiellis/comfy-api-proxy-go/sdk"
)

// fakeAPI is a minimal in-process Comfy API v2 deployment for the examples:
// one job, one output, single-use idempotency keys, and metadata stored as
// the client sent it.
type fakeAPI struct {
	mu       sync.Mutex
	keys     map[string]bool
	metadata json.RawMessage
}

func newFakeAPI() (*fakeAPI, *httptest.Server) {
	f := &fakeAPI{keys: map[string]bool{}}
	mux := http.NewServeMux()
	mux.HandleFunc("POST /api/v2/jobs", f.submit)
	mux.HandleFunc("GET /api/v2/jobs", f.list)
	mux.HandleFunc("GET /api/v2/jobs/{id}", f.get)
	mux.HandleFunc("GET /api/v2/jobs/{id}/events", f.events)
	mux.HandleFunc("GET /api/v2/assets/{id}/content", f.content)
	return f, httptest.NewServer(mux)
}

func (f *fakeAPI) job(status string) map[string]any {
	f.mu.Lock()
	defer f.mu.Unlock()
	return map[string]any{
		"id": "job-1", "status": status, "created_at": "2026-10-27T10:00:00Z",
		"metadata": f.metadata,
		"outputs": []any{map[string]any{
			"node_id": "9", "name": "out.png", "type": "image", "content_type": "image/png",
			"size_bytes": 8, "id": "out-1",
		}},
	}
}

func reply(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	if err := json.NewEncoder(w).Encode(v); err != nil {
		return
	}
}

func replyError(w http.ResponseWriter, status int, code, message string) {
	reply(w, status, map[string]any{"error": map[string]any{"code": code, "message": message, "details": nil}})
}

func (f *fakeAPI) submit(w http.ResponseWriter, r *http.Request) {
	var body struct {
		Metadata json.RawMessage `json:"metadata"`
	}
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		replyError(w, http.StatusBadRequest, "invalid_request", err.Error())
		return
	}
	key := r.Header.Get("Idempotency-Key")
	f.mu.Lock()
	reused := f.keys[key]
	f.keys[key] = true
	if !reused {
		f.metadata = body.Metadata
	}
	f.mu.Unlock()
	if reused {
		replyError(w, http.StatusUnprocessableEntity, "idempotency_key_reuse", "This Idempotency-Key has already been used.")
		return
	}
	reply(w, http.StatusCreated, f.job(sdk.StatusQueued))
}

func (f *fakeAPI) list(w http.ResponseWriter, _ *http.Request) {
	reply(w, http.StatusOK, map[string]any{"jobs": []any{f.job(sdk.StatusSucceeded)}})
}

func (f *fakeAPI) get(w http.ResponseWriter, r *http.Request) {
	if r.PathValue("id") != "job-1" {
		replyError(w, http.StatusNotFound, "not_found", "No job "+r.PathValue("id")+".")
		return
	}
	reply(w, http.StatusOK, f.job(sdk.StatusSucceeded))
}

func (f *fakeAPI) events(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "text/event-stream")
	frames := "event: status\ndata: {\"status\":\"running\"}\n\n" +
		"event: progress\ndata: {\"value\":0.5,\"nodes_done\":1,\"nodes_total\":2}\n\n" +
		"event: status\ndata: {\"status\":\"succeeded\"}\n\n"
	if _, err := io.WriteString(w, frames); err != nil {
		return
	}
}

func (f *fakeAPI) content(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "image/png")
	if _, err := io.WriteString(w, "PNG data"); err != nil {
		return
	}
}

// demoWorkflow is a two-node API-format graph.
func demoWorkflow() *sdk.Workflow {
	return sdk.NewWorkflow(map[string]any{
		"3": map[string]any{"class_type": "KSampler", "inputs": map[string]any{"seed": 42, "steps": 1}},
		"9": map[string]any{"class_type": "SaveImage", "inputs": map[string]any{"images": []any{"3", 0}}},
	})
}

func main() {
	_, srv := newFakeAPI()
	defer srv.Close()
	client, err := sdk.New(sdk.WithBaseURL(srv.URL))
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	job, err := client.Submit(ctx, demoWorkflow(), sdk.SubmitOptions{IdempotencyKey: "order-1234"})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("submitted:", job.ID(), job.Status())

	// Keys are single-use. A second submit under the same key is refused,
	// and the error carries the key so the caller can look the job up.
	_, err = client.Submit(ctx, demoWorkflow(), sdk.SubmitOptions{IdempotencyKey: "order-1234"})
	var apiErr *sdk.APIError
	if errors.Is(err, sdk.ErrIdempotencyKeyReuse) && errors.As(err, &apiErr) {
		fmt.Println("refused:", apiErr.HTTPStatus, apiErr.Code, apiErr.IdempotencyKey)
	}

	if err := job.Wait(ctx); err != nil {
		log.Fatal(err)
	}
	fmt.Println("finished:", job.Status())
}
Output:
submitted: job-1 queued
refused: 422 idempotency_key_reuse order-1234
finished: succeeded

type DownloadURL

type DownloadURL struct {
	URL       string
	ExpiresAt *time.Time
}

DownloadURL is where the asset's bytes can be fetched, with its expiry when the server issued a signed URL.

type Event

type Event interface {
	// contains filtered or unexported methods
}

Event is one item from a job's live stream: *Progress, *Preview, *OutputReady, *StatusChange, or *Log.

type Job

type Job struct {
	// contains filtered or unexported fields
}

Job is a submitted job. Its fields are the snapshot from the last call that returned it; Refresh, Wait, and Cancel update them. Safe for concurrent use.

func (*Job) Cancel

func (j *Job) Cancel(ctx context.Context) error

Cancel asks the server to cancel. A running job reads canceling until the interrupt lands; Wait for the terminal state.

func (*Job) CreatedAt

func (j *Job) CreatedAt() time.Time

CreatedAt is when the job was created.

func (*Job) Events

func (j *Job) Events(ctx context.Context) iter.Seq2[Event, error]

Events streams the job's live events until a terminal status. The stream is best effort and poll-backed: a dropped connection reconnects, a stream that ends without a terminal status falls back to GET /jobs/{id}, and a server without the endpoint (501) ends the iteration quietly. The last event is always a terminal *StatusChange unless an error ends it first.

Example
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
	"sync"

	"github.com/regiellis/comfy-api-proxy-go/sdk"
)

// fakeAPI is a minimal in-process Comfy API v2 deployment for the examples:
// one job, one output, single-use idempotency keys, and metadata stored as
// the client sent it.
type fakeAPI struct {
	mu       sync.Mutex
	keys     map[string]bool
	metadata json.RawMessage
}

func newFakeAPI() (*fakeAPI, *httptest.Server) {
	f := &fakeAPI{keys: map[string]bool{}}
	mux := http.NewServeMux()
	mux.HandleFunc("POST /api/v2/jobs", f.submit)
	mux.HandleFunc("GET /api/v2/jobs", f.list)
	mux.HandleFunc("GET /api/v2/jobs/{id}", f.get)
	mux.HandleFunc("GET /api/v2/jobs/{id}/events", f.events)
	mux.HandleFunc("GET /api/v2/assets/{id}/content", f.content)
	return f, httptest.NewServer(mux)
}

func (f *fakeAPI) job(status string) map[string]any {
	f.mu.Lock()
	defer f.mu.Unlock()
	return map[string]any{
		"id": "job-1", "status": status, "created_at": "2026-10-27T10:00:00Z",
		"metadata": f.metadata,
		"outputs": []any{map[string]any{
			"node_id": "9", "name": "out.png", "type": "image", "content_type": "image/png",
			"size_bytes": 8, "id": "out-1",
		}},
	}
}

func reply(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	if err := json.NewEncoder(w).Encode(v); err != nil {
		return
	}
}

func replyError(w http.ResponseWriter, status int, code, message string) {
	reply(w, status, map[string]any{"error": map[string]any{"code": code, "message": message, "details": nil}})
}

func (f *fakeAPI) submit(w http.ResponseWriter, r *http.Request) {
	var body struct {
		Metadata json.RawMessage `json:"metadata"`
	}
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		replyError(w, http.StatusBadRequest, "invalid_request", err.Error())
		return
	}
	key := r.Header.Get("Idempotency-Key")
	f.mu.Lock()
	reused := f.keys[key]
	f.keys[key] = true
	if !reused {
		f.metadata = body.Metadata
	}
	f.mu.Unlock()
	if reused {
		replyError(w, http.StatusUnprocessableEntity, "idempotency_key_reuse", "This Idempotency-Key has already been used.")
		return
	}
	reply(w, http.StatusCreated, f.job(sdk.StatusQueued))
}

func (f *fakeAPI) list(w http.ResponseWriter, _ *http.Request) {
	reply(w, http.StatusOK, map[string]any{"jobs": []any{f.job(sdk.StatusSucceeded)}})
}

func (f *fakeAPI) get(w http.ResponseWriter, r *http.Request) {
	if r.PathValue("id") != "job-1" {
		replyError(w, http.StatusNotFound, "not_found", "No job "+r.PathValue("id")+".")
		return
	}
	reply(w, http.StatusOK, f.job(sdk.StatusSucceeded))
}

func (f *fakeAPI) events(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "text/event-stream")
	frames := "event: status\ndata: {\"status\":\"running\"}\n\n" +
		"event: progress\ndata: {\"value\":0.5,\"nodes_done\":1,\"nodes_total\":2}\n\n" +
		"event: status\ndata: {\"status\":\"succeeded\"}\n\n"
	if _, err := io.WriteString(w, frames); err != nil {
		return
	}
}

func (f *fakeAPI) content(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "image/png")
	if _, err := io.WriteString(w, "PNG data"); err != nil {
		return
	}
}

// demoWorkflow is a two-node API-format graph.
func demoWorkflow() *sdk.Workflow {
	return sdk.NewWorkflow(map[string]any{
		"3": map[string]any{"class_type": "KSampler", "inputs": map[string]any{"seed": 42, "steps": 1}},
		"9": map[string]any{"class_type": "SaveImage", "inputs": map[string]any{"images": []any{"3", 0}}},
	})
}

func main() {
	_, srv := newFakeAPI()
	defer srv.Close()
	client, err := sdk.New(sdk.WithBaseURL(srv.URL))
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	job, err := client.Submit(ctx, demoWorkflow(), sdk.SubmitOptions{})
	if err != nil {
		log.Fatal(err)
	}
	for ev, err := range job.Events(ctx) {
		if err != nil {
			log.Fatal(err)
		}
		switch e := ev.(type) {
		case *sdk.StatusChange:
			fmt.Println("status", e.Status)
		case *sdk.Progress:
			fmt.Printf("progress %.0f%%\n", e.Value*100)
		}
	}
}
Output:
status running
progress 50%
status succeeded

func (*Job) Failure

func (j *Job) Failure() *JobError

Failure is the server's account of a failed job, nil otherwise. The returned value is a copy.

func (*Job) GetOutputs

func (j *Job) GetOutputs(nodeID string) []*Output

GetOutputs are the outputs one node produced.

func (*Job) ID

func (j *Job) ID() string

ID is the job id.

func (*Job) Metadata

func (j *Job) Metadata() map[string]string

Metadata is the job's labels; empty when it has none, or when the server sends metadata that is neither a string map nor a JSON-encoded string map.

func (*Job) Outputs

func (j *Job) Outputs() []*Output

Outputs are the job's outputs so far.

func (*Job) Progress

func (j *Job) Progress() *JobProgress

Progress is a copy of the last progress snapshot, nil when the server sent none.

func (*Job) QueuePosition

func (j *Job) QueuePosition() *int

QueuePosition is the job's place in the queue while queued.

func (*Job) Refresh

func (j *Job) Refresh(ctx context.Context) error

Refresh re-reads the job. GET /jobs/{id} is authoritative.

func (*Job) Result

func (j *Job) Result(ctx context.Context) error

Result waits, then reports a job that did not succeed as *JobFailedError.

func (*Job) Status

func (j *Job) Status() string

Status is the last known status.

func (*Job) String

func (j *Job) String() string

String reports id and status.

func (*Job) Wait

func (j *Job) Wait(ctx context.Context) error

Wait polls until the job is terminal, on a schedule that starts at half a second and settles at five. Bound it with the context.

func (*Job) Workflow

func (j *Job) Workflow(ctx context.Context) (JobWorkflow, error)

Workflow fetches the graph the job ran with.

type JobError

type JobError struct {
	Code      string  `json:"code"`
	Message   string  `json:"message"`
	NodeID    *string `json:"node_id"`
	ClassType *string `json:"class_type"`
	Traceback *string `json:"traceback"`
}

JobError is the server's account of why a job failed.

type JobFailedError

type JobFailedError struct {
	JobID  string
	Status string
	// Err is the server's account of the failure, nil when it gave none.
	Err *JobError
}

JobFailedError reports a job that reached a terminal state other than succeeded. errors.Is(err, ErrJobFailed) matches it.

func (*JobFailedError) Error

func (e *JobFailedError) Error() string

Error names the job and the status it ended in.

func (*JobFailedError) Is

func (e *JobFailedError) Is(target error) bool

Is matches ErrJobFailed.

type JobProgress

type JobProgress struct {
	Value            float64 `json:"value"`
	NodesDone        int     `json:"nodes_done"`
	NodesTotal       int     `json:"nodes_total"`
	CurrentNode      *string `json:"current_node"`
	CurrentNodeClass *string `json:"current_node_class"`
	Step             *int    `json:"step"`
	Steps            *int    `json:"steps"`
	Message          *string `json:"message"`
}

JobProgress is the latest progress snapshot on a job.

type JobSummary

type JobSummary struct {
	ID           string
	Status       string
	CreateTime   *time.Time
	UpdateTime   *time.Time
	DeploymentID *string
	Metadata     map[string]string
	// Data is the item as the server sent it, for fields not lifted above.
	Data map[string]any
}

JobSummary is one entry of the job list.

type JobWorkflow

type JobWorkflow struct {
	Graph  map[string]any
	Format string
}

JobWorkflow is the graph a job ran with. Format is "api" for an executed graph or "save" for the original authoring workflow.

type ListModelsOptions

type ListModelsOptions struct {
	Cursor string
	Limit  int
}

ListModelsOptions page the catalog.

type ListOptions

type ListOptions struct {
	// Metadata keeps only jobs carrying every pair. The server filters by
	// it, and the SDK filters again locally. With WithProxyMetadata only the
	// local filter runs, over the jobs the server returns.
	Metadata map[string]string
	// Limit is the page size the server is asked for; zero leaves it unset.
	Limit int
}

ListOptions filter the job list.

type Log

type Log struct{ Level, Message string }

Log is a server log line.

type ModelPage

type ModelPage struct {
	Data []CatalogModel
	// HasMore is whether another page exists; walk on it, never on a short
	// Data.
	HasMore    bool
	NextCursor string
	// Limit is the page size served; a request above 100 is clamped.
	Limit     int
	RequestID string
}

ModelPage is one page of the catalog.

type Models

type Models struct {
	// contains filtered or unexported fields
}

Models runs hosted models on Comfy Router (client.Models). It shares the client's key and follows its RetryPolicy.

func (*Models) BaseURL

func (m *Models) BaseURL() string

BaseURL is the Router target with any embedded credentials redacted.

func (*Models) Handle

func (m *Models) Handle(model, requestID string) (*RequestHandle, error)

Handle rebuilds a handle for a request submitted earlier.

func (*Models) List

List walks the whole catalog, page by page, stopping at the first error.

func (*Models) Page

func (m *Models) Page(ctx context.Context, opts ListModelsOptions) (ModelPage, error)

Page fetches one catalog page.

func (*Models) Retry

func (m *Models) Retry() RetryPolicy

Retry is the policy Router calls fail under.

func (*Models) Run

func (m *Models) Run(ctx context.Context, model string, args map[string]any, opts RunOptions) (RunOutput, error)

Run invokes a model and waits for its output. It is billed. A failure the Router may have acted on (a 5xx, a dropped connection) is retried only when the policy allows it; retries reuse one Idempotency-Key, so a retry cannot bill twice. If a retry is refused as a key reuse after an earlier attempt may have claimed the key, the earlier failure is returned with ResendRefused set: the generation may exist, so collect it under the key.

func (*Models) RunDetailed

func (m *Models) RunDetailed(ctx context.Context, model string, args map[string]any, opts RunOptions) (RunResult, error)

RunDetailed is Run with Router's disclosures beside the output.

func (*Models) Schema

func (m *Models) Schema(ctx context.Context, model, etag string) (SchemaResult, error)

Schema fetches a model's schemas. Pass the ETag from an earlier call to get Unchanged instead of the document again.

func (*Models) Submit

func (m *Models) Submit(ctx context.Context, model string, args map[string]any, opts RunOptions) (*RequestHandle, error)

Submit queues a model run and returns its handle. It is billed when it runs. Collect with Get, follow with Updates, or stop with Cancel.

func (*Models) Subscribe

func (m *Models) Subscribe(ctx context.Context, model string, args map[string]any, opts RunOptions, onUpdate func(QueueUpdate)) (RunOutput, error)

Subscribe submits, follows the queue (passing each change to onUpdate when it is non-nil), and collects the output. When ctx ends first, the request is cancelled on a best-effort basis before the error returns, so an abandoned wait does not leave a generation running.

type Option

type Option func(*options)

Option configures New.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the bearer token. It wins over COMFY_API_KEY. An empty value counts as not given.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL targets a deployment, winning over COMFY_BASE_URL. An empty value counts as not given.

func WithClientInfo

func WithClientInfo(info string) Option

WithClientInfo appends "app/<info>" to the User-Agent.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient replaces the HTTP client. Its timeouts then apply as set, to every call including synchronous model runs, so a response-header limit on it must allow for a whole generation. The SDK still strips the bearer token on a redirect that leaves the configured origins.

func WithProxyMetadata

func WithProxyMetadata() Option

WithProxyMetadata encodes job labels as a JSON string for comfy-api-proxy. ListJobs filters labels locally, since the proxy has no label-map filter. Omit this option for deployments that accept metadata objects. Comfy Cloud refuses labels for now with an *APIError whose Code is "metadata_not_supported".

Example
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
	"sync"

	"github.com/regiellis/comfy-api-proxy-go/sdk"
)

// fakeAPI is a minimal in-process Comfy API v2 deployment for the examples:
// one job, one output, single-use idempotency keys, and metadata stored as
// the client sent it.
type fakeAPI struct {
	mu       sync.Mutex
	keys     map[string]bool
	metadata json.RawMessage
}

func newFakeAPI() (*fakeAPI, *httptest.Server) {
	f := &fakeAPI{keys: map[string]bool{}}
	mux := http.NewServeMux()
	mux.HandleFunc("POST /api/v2/jobs", f.submit)
	mux.HandleFunc("GET /api/v2/jobs", f.list)
	mux.HandleFunc("GET /api/v2/jobs/{id}", f.get)
	mux.HandleFunc("GET /api/v2/jobs/{id}/events", f.events)
	mux.HandleFunc("GET /api/v2/assets/{id}/content", f.content)
	return f, httptest.NewServer(mux)
}

func (f *fakeAPI) job(status string) map[string]any {
	f.mu.Lock()
	defer f.mu.Unlock()
	return map[string]any{
		"id": "job-1", "status": status, "created_at": "2026-10-27T10:00:00Z",
		"metadata": f.metadata,
		"outputs": []any{map[string]any{
			"node_id": "9", "name": "out.png", "type": "image", "content_type": "image/png",
			"size_bytes": 8, "id": "out-1",
		}},
	}
}

func reply(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	if err := json.NewEncoder(w).Encode(v); err != nil {
		return
	}
}

func replyError(w http.ResponseWriter, status int, code, message string) {
	reply(w, status, map[string]any{"error": map[string]any{"code": code, "message": message, "details": nil}})
}

func (f *fakeAPI) submit(w http.ResponseWriter, r *http.Request) {
	var body struct {
		Metadata json.RawMessage `json:"metadata"`
	}
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		replyError(w, http.StatusBadRequest, "invalid_request", err.Error())
		return
	}
	key := r.Header.Get("Idempotency-Key")
	f.mu.Lock()
	reused := f.keys[key]
	f.keys[key] = true
	if !reused {
		f.metadata = body.Metadata
	}
	f.mu.Unlock()
	if reused {
		replyError(w, http.StatusUnprocessableEntity, "idempotency_key_reuse", "This Idempotency-Key has already been used.")
		return
	}
	reply(w, http.StatusCreated, f.job(sdk.StatusQueued))
}

func (f *fakeAPI) list(w http.ResponseWriter, _ *http.Request) {
	reply(w, http.StatusOK, map[string]any{"jobs": []any{f.job(sdk.StatusSucceeded)}})
}

func (f *fakeAPI) get(w http.ResponseWriter, r *http.Request) {
	if r.PathValue("id") != "job-1" {
		replyError(w, http.StatusNotFound, "not_found", "No job "+r.PathValue("id")+".")
		return
	}
	reply(w, http.StatusOK, f.job(sdk.StatusSucceeded))
}

func (f *fakeAPI) events(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "text/event-stream")
	frames := "event: status\ndata: {\"status\":\"running\"}\n\n" +
		"event: progress\ndata: {\"value\":0.5,\"nodes_done\":1,\"nodes_total\":2}\n\n" +
		"event: status\ndata: {\"status\":\"succeeded\"}\n\n"
	if _, err := io.WriteString(w, frames); err != nil {
		return
	}
}

func (f *fakeAPI) content(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "image/png")
	if _, err := io.WriteString(w, "PNG data"); err != nil {
		return
	}
}

// demoWorkflow is a two-node API-format graph.
func demoWorkflow() *sdk.Workflow {
	return sdk.NewWorkflow(map[string]any{
		"3": map[string]any{"class_type": "KSampler", "inputs": map[string]any{"seed": 42, "steps": 1}},
		"9": map[string]any{"class_type": "SaveImage", "inputs": map[string]any{"images": []any{"3", 0}}},
	})
}

func main() {
	fake, srv := newFakeAPI()
	defer srv.Close()
	client, err := sdk.New(sdk.WithBaseURL(srv.URL), sdk.WithProxyMetadata())
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	job, err := client.Submit(ctx, demoWorkflow(), sdk.SubmitOptions{
		Metadata: map[string]string{"project": "demo", "shot": "12"},
	})
	if err != nil {
		log.Fatal(err)
	}
	fake.mu.Lock()
	fmt.Println("sent:", string(fake.metadata))
	fake.mu.Unlock()
	fmt.Println("labels:", job.Metadata())

	for s, err := range client.ListJobs(ctx, sdk.ListOptions{Metadata: map[string]string{"project": "demo"}}) {
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println("listed:", s.ID, s.Status)
	}
}
Output:
sent: "{\"project\":\"demo\",\"shot\":\"12\"}"
labels: map[project:demo shot:12]
listed: job-1 succeeded

func WithRetry

func WithRetry(p RetryPolicy) Option

WithRetry sets the policy client.Models calls fail under. It does not govern Submit and Run, which follow the server's Retry-After.

func WithRouterBaseURL

func WithRouterBaseURL(u string) Option

WithRouterBaseURL targets another Comfy Router, winning over COMFY_ROUTER_BASE_URL.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout bounds connecting and waiting for response headers, and how long a streamed body may sit idle. It is not a cap on a whole download. The default is 30 seconds. Synchronous model runs keep a 600 second limit on response headers, since Router answers only when the generation is done.

type Output

type Output struct {
	// contains filtered or unexported fields
}

Output is one file a job produced.

func (*Output) Bytes

func (o *Output) Bytes(ctx context.Context, rng *Range) ([]byte, error)

Bytes reads the whole output (or rng of it) into memory.

func (*Output) ContentType

func (o *Output) ContentType() string

ContentType is the output's media type.

func (*Output) DownloadURL

func (o *Output) DownloadURL(ctx context.Context) (DownloadURL, error)

DownloadURL resolves a URL for the output's bytes: a signed URL with its expiry on Comfy Cloud, the content endpoint itself on a self-hosted proxy.

func (*Output) ID

func (o *Output) ID() string

ID is the output's asset id.

func (*Output) JobID

func (o *Output) JobID() *string

JobID is the job that produced the output.

func (*Output) Name

func (o *Output) Name() string

Name is the output's filename.

func (*Output) NodeID

func (o *Output) NodeID() string

NodeID is the node that produced the output.

func (*Output) SizeBytes

func (o *Output) SizeBytes() int64

SizeBytes is the size the server reported, zero when it did not know.

func (*Output) String

func (o *Output) String() string

String reports node id, name, and asset id.

func (*Output) ToFile

func (o *Output) ToFile(ctx context.Context, path string, rng *Range) error

ToFile streams the output to path, creating or truncating it. A failed download removes the partial file.

func (*Output) ToWriter

func (o *Output) ToWriter(ctx context.Context, w io.Writer, rng *Range) (int64, error)

ToWriter streams the output (or rng of it, when non-nil) into w and reports the bytes written.

func (*Output) Type

func (o *Output) Type() string

Type is image, video, audio, text, file, or latent.

func (*Output) URLExpiresAt

func (o *Output) URLExpiresAt() time.Time

URLExpiresAt is when the output's content URL stops working.

type OutputReady

type OutputReady struct{ Output *Output }

OutputReady carries an output the moment it is committed.

type Preview

type Preview struct {
	NodeID      string
	ContentType string
	Data        []byte
}

Preview is an in-progress image.

type Progress

type Progress struct {
	Value       float64
	Message     *string
	NodesDone   *int
	NodesTotal  *int
	CurrentNode *string
	Step        *int
	Steps       *int
}

Progress is a full progress snapshot, so a dropped one costs nothing.

type QueueUpdate

type QueueUpdate struct {
	RequestID     string
	Status        string
	QueuePosition *int
	ErrorType     string
	// RetryAfter is the pace the server asked for, in seconds.
	RetryAfter *int
	Raw        map[string]any
}

QueueUpdate is one observed state of a queued request.

func (QueueUpdate) IsCompleted

func (u QueueUpdate) IsCompleted() bool

IsCompleted reports a finished request, failed or not.

type Range

type Range struct{ Start, End int64 }

Range is an inclusive byte range for a partial download.

type RequestHandle

type RequestHandle struct {
	// contains filtered or unexported fields
}

RequestHandle is a queued model request.

func (*RequestHandle) Cancel

func (h *RequestHandle) Cancel(ctx context.Context) (QueueUpdate, error)

Cancel asks the queue to stop the request.

func (*RequestHandle) Get

func (h *RequestHandle) Get(ctx context.Context) (RunOutput, error)

Get waits for the request to complete, then collects its output. A completion that names an error_type is returned as that Router error.

func (*RequestHandle) Model

func (h *RequestHandle) Model() string

Model is the model id the request runs.

func (*RequestHandle) RequestID

func (h *RequestHandle) RequestID() string

RequestID is the queue's id for the request.

func (*RequestHandle) Status

func (h *RequestHandle) Status(ctx context.Context) (QueueUpdate, error)

Status reads the request's current state.

func (*RequestHandle) String

func (h *RequestHandle) String() string

String reports the model and request id.

func (*RequestHandle) Updates

Updates polls the request, yielding each change of status or position, and ends after COMPLETED. Polls follow the queue's Retry-After (capped at a minute), else a schedule from half a second to five. Bound it with ctx.

type RetryPolicy

type RetryPolicy struct {
	// MaxElapsed bounds the whole retry window; zero disables retrying.
	MaxElapsed time.Duration
	// InitialBackoff, BackoffFactor, and MaxBackoff shape the exponential
	// backoff used when the server names no Retry-After.
	InitialBackoff time.Duration
	BackoffFactor  float64
	MaxBackoff     time.Duration
	// Jitter draws each wait uniformly below its ceiling.
	Jitter bool
	// RetryPossiblyInFlight also retries a 5xx or a dropped connection.
	RetryPossiblyInFlight bool
	// RetryCollectable collects a still-running generation under its key.
	RetryCollectable bool
	// CollectMaxElapsed bounds collecting; generations can take minutes.
	CollectMaxElapsed time.Duration
}

RetryPolicy decides which failed Router calls (client.Models) are retried and for how long. It does not govern the workflow surface (Submit, Run), whose 429 handling follows the server's Retry-After.

Retried without asking: a 429 that names Retry-After, and a failure that never reached the server (refused connection, connect timeout). A 5xx or a connection dropped mid-request may have run, and a model run is billed, so those retry only with RetryPossiblyInFlight. A run the Router is still working on (409 concurrency_limit_exceeded or 504 deadline_exceeded, each with Retry-After) is collected under the same key on its own longer budget.

func (RetryPolicy) Validate

func (p RetryPolicy) Validate() error

Validate reports a policy that cannot be followed.

type RunOptions

type RunOptions struct {
	// IdempotencyKey is minted fresh when empty. Reuse it to retry a run
	// without paying twice.
	IdempotencyKey string
	// ModelProvider routes to an alternate provider, translating the body.
	ModelProvider string
	// StrictMode refuses translation that would drop fields.
	StrictMode *bool
	// FallbackProvider is "true", "false", or a provider to fall back to.
	FallbackProvider string
}

RunOptions are the optional parts of a model run.

type RunOutput

type RunOutput struct {
	JSON   map[string]any
	Binary *BinaryResult
}

RunOutput is a model's native output: JSON for a partner that answers JSON, Binary for one that answers bytes. Exactly one is set.

type RunResult

type RunResult struct {
	Output RunOutput
	// ServingProvider is the provider that served the call after a
	// fallback succeeded; nil means the requested provider served it.
	ServingProvider *string
	// DroppedParams names native fields translation could not carry.
	DroppedParams []string
	// Replayed means the response came from the key's record and was not
	// run, or billed, again.
	Replayed  bool
	RequestID string
	// CreditsUsed is what Router priced the run at, as its decimal string.
	// Nil means not reported, never free; "0" is a real reported cost.
	CreditsUsed *string
}

RunResult is a run's output plus what Router disclosed about it.

type SchemaResult

type SchemaResult struct {
	// Unchanged is true on a 304: the document is the one the etag names.
	Unchanged bool
	// Document is a standalone OpenAPI document, nil when Unchanged.
	Document  map[string]any
	ETag      string
	RequestID string
}

SchemaResult is a model's input and output schemas.

type StatusChange

type StatusChange struct {
	Status        string
	QueuePosition *int
}

StatusChange is a status transition; the stream ends after a terminal one.

type SubmitOptions

type SubmitOptions struct {
	// PartnerAPIKey authenticates partner (API) nodes in the workflow, sent
	// as extra_data.api_key_comfy_org. Unrelated to the client's own key.
	PartnerAPIKey string
	// IdempotencyKey is minted fresh when empty. A reused key is rejected
	// (ErrIdempotencyKeyReuse), not replayed.
	IdempotencyKey string
	// Metadata labels the job. Use WithProxyMetadata when targeting
	// comfy-api-proxy, which requires string metadata instead of an object.
	Metadata map[string]string
}

SubmitOptions are the optional parts of a submission.

type TransportError

type TransportError struct {
	IdempotencyKey string
	// ResendRefused: see APIError.ResendRefused.
	ResendRefused bool
	Err           error
}

TransportError wraps a failure that never produced a response: refused connection, timeout, a stream cut mid-body. It keeps the idempotency key a submit was sent under. Whether the server saw the request is unknown, so poll or list before resubmitting under the same key.

func (*TransportError) Error

func (e *TransportError) Error() string

Error is the underlying failure's message.

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

Unwrap returns the underlying failure, so errors.Is can find ErrIdleTimeout or context.Canceled.

type ValidationErrorDetail

type ValidationErrorDetail struct {
	Loc   []any
	Msg   string
	Type  string
	Ctx   map[string]any
	Input any
}

ValidationErrorDetail is one entry of a Router validation response.

func (ValidationErrorDetail) Location

func (d ValidationErrorDetail) Location() string

Location joins Loc into a dotted path such as "body.prompt".

type Workflow

type Workflow struct {
	Graph map[string]any
}

Workflow is an API-format graph: node id to {class_type, inputs}.

func NewWorkflow

func NewWorkflow(graph map[string]any) *Workflow

NewWorkflow wraps a graph.

func WorkflowFromFile

func WorkflowFromFile(path string) (*Workflow, error)

WorkflowFromFile reads an API-format graph from disk.

func WorkflowFromJSON

func WorkflowFromJSON(data []byte) (*Workflow, error)

WorkflowFromJSON parses an API-format graph. Numbers stay exact, so a 64-bit seed survives.

Example
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/regiellis/comfy-api-proxy-go/sdk"
)

func main() {
	// A seed above 2^53 would lose precision as a float64. WorkflowFromJSON
	// keeps every number exact, so it reaches the server unchanged.
	wf, err := sdk.WorkflowFromJSON([]byte(`{"3": {"class_type": "KSampler", "inputs": {"seed": 18446744073709551615}}}`))
	if err != nil {
		log.Fatal(err)
	}
	wf.SetInput("3", "steps", 20)
	out, err := json.Marshal(wf.Graph)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(out))
}
Output:
{"3":{"class_type":"KSampler","inputs":{"seed":18446744073709551615,"steps":20}}}

func (*Workflow) RemoveNode

func (w *Workflow) RemoveNode(nodeID string)

RemoveNode deletes a node. When the removed node had exactly one linked input, links that pointed at it are rewired to that input's source, so a pass-through node (an upscale, a preview) can be cut out; otherwise links to it are dropped.

func (*Workflow) SetInput

func (w *Workflow) SetInput(nodeID, field string, value any)

SetInput sets a node input, creating the node and its inputs map when missing. An *Asset value is uploaded on submit and replaced with its core/ASSET reference.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL