mirror of
https://github.com/bitbaum/openclaw.git
synced 2026-12-05 03:57:59 +01:00
* feat(comfy): support custom headers and per-request seed randomization Local-mode ComfyUI requests only ever sent Content-Type, so a local instance reachable behind HTTP auth (Basic auth, a bearer token) had no way to authenticate. Add a generic headers config key, merged over the plugin's own headers -- same shape as the ollama plugin's established remote.headers pattern, rather than inventing a comfy-specific scheme. Also add optional seedNodeId/seedInputName: without it, a static workflow file's sampler seed never changes between submissions, so every generation was silently identical whenever the operator's workflow relies on a fresh random seed per run. * fix(comfy): resolve headers through the SecretInput path, not plaintext-only The new headers config accepted only literal strings, so a credential-bearing value (Authorization for a gated ComfyUI instance) had no path to secret storage -- unlike the existing apiKey field, which already resolves through resolveSecretInputString with an env-backed fallback. Mirrors that same pattern per-header, plus the ollama plugin's established header-secret precedent: a header pointed at a SecretRef that can't be resolved fails the request outright instead of silently sending it unauthenticated. * fix(comfy): resolve non-env header SecretRefs, hide capability on unresolvable ones resolveComfyHeadersConfig only ever resolved env-sourced SecretRefs (a manual process.env fallback bolted onto inspect-mode); any file, keychain, or plugin-backed reference always threw, despite the schema and docs advertising the same SecretRef shape apiKey accepts. Now resolves through resolveConfiguredSecretInputString (the same async resolver the ollama plugin's own headers use) for the non-literal case, so a real non-env credential provider actually works. Separately, isComfyCapabilityConfigured returned true for local mode without ever inspecting headers, so an unavailable Authorization SecretRef advertised an image/video/music tool that would always throw on invocation. Extends the same sync inspect-based veto resolveComfyApiKey already applies for cloud mode's apiKey. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6 * fix(comfy): don't veto a resolvable non-env header secret from provider selection hasUnavailableComfyHeaderSecret treated any non-env SecretRef as unavailable for the isComfyCapabilityConfigured gate, on the theory that inspect mode can't confirm it -- but "can't confirm yet" isn't "won't resolve": the async request path can and does resolve a real file/keychain/plugin-backed ref. That made a perfectly valid, already-working header credential permanently hide the image/video/music tools from the agent, which is a worse outcome than a rare genuinely broken ref surfacing its error at actual invocation. Only a definitely missing/empty env var (decidable synchronously, no I/O) still vetoes. Added a permanent committed integration test (workflow-runtime.header-secrets.integration.test.ts) that proves this, plus the env/non-env header resolution and fail-closed paths, over real sockets with no SDK/ssrf-runtime mocking -- replacing the throwaway proof script from the previous push, which was deleted after running and therefore not rerunnable or reviewable. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6 * fix(comfy): register header SecretRefs in the plugin secret contract headers.* accepts and resolves SecretRef values, but the manifest never declared configContracts.secretInputs for that path -- the canonical plugin secret lifecycle (startup materialization, owner diagnostics, audit/configure discovery, resolved-value redaction) only walks manifest-declared paths, so this credential surface was invisible to all of it despite working correctly at request time. apiKey doesn't need the same declaration (it's covered by the separate, already-wired provider-auth system via setup.providers.envVars/providerAuthChoices); headers.* has no other declaration path. Also fixes two smaller findings from the same review pass: the seed-injection test asserted the freshly-generated seed is nonzero, but randomInt(RANDOM_SEED_EXCLUSIVE_MAX) legitimately can (rarely) return 0 -- a flaky assertion, removed; and documents that a configured Content-Type header is ignored specifically on image-upload requests, where the multipart boundary must come from the runtime. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6 * docs(secrets): register comfy header SecretRefs in the credential matrix The comfy plugin manifest change in e32863dc6cd registered plugins.entries.comfy.config.headers.* as a secret-input target, but the generated docs matrix and its paired markdown list weren't refreshed to match, breaking the docs-sync CI check. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6 * test(comfy): restore inherited header proof env * fix(comfy): redact reflected request credentials across generation failures Reuse the Ollama exact-header redactor through the provider HTTP SDK, scrub structured and truncated diagnostics before retaining them, and cover decoded Basic credentials observed in real ComfyUI proxy failures. Preserve optional header and seed behavior while consolidating tests and documenting the shared boundary. Co-authored-by: Markus Hartung <mail@hartmark.se> * fix(provider-http): handle optional Node header values safely Skip undefined HeaderRecord values allowed by Node types and document the intentional omission of unsafe parser causes in the lint exception. Actual credential and no-header error behavior remain unchanged. Co-authored-by: Markus Hartung <mail@hartmark.se> * test(comfy): explicitly stringify reflected proxy header values Keep the socket fixture compatible with the IncomingHttpHeaders union without changing its reflected-error behavior. Co-authored-by: Markus Hartung <mail@hartmark.se> * test(provider-http): register credential-safe parser error exception Track the intentional preserve-caught-error suppression in the explicit inventory: raw JSON parser causes can quote request credentials. The focused inventory and provider HTTP tests pass; runtime behavior is unchanged. --------- Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com> Co-authored-by: Peter Steinberger <steipete@gmail.com>
954 lines
29 KiB
TypeScript
954 lines
29 KiB
TypeScript
// Comfy plugin module implements workflow runtime behavior.
|
|
import { randomInt } from "node:crypto";
|
|
import fs from "node:fs/promises";
|
|
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
|
|
import { resolveGeneratedMediaMaxBytes } from "openclaw/plugin-sdk/media-generation-runtime";
|
|
import { extensionForMime } from "openclaw/plugin-sdk/media-mime";
|
|
import { resolvePositiveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
|
|
import {
|
|
isProviderApiKeyConfigured,
|
|
type AuthProfileStore,
|
|
} from "openclaw/plugin-sdk/provider-auth";
|
|
import { resolveApiKeyForProvider } from "openclaw/plugin-sdk/provider-auth-runtime";
|
|
import {
|
|
assertOkOrThrowHttpError,
|
|
normalizeBaseUrl,
|
|
readProviderJsonResponse,
|
|
redactProviderResponseErrorText,
|
|
resolveProviderHttpRequestConfig,
|
|
} from "openclaw/plugin-sdk/provider-http";
|
|
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
|
|
import {
|
|
normalizeSecretInputString,
|
|
resolveConfiguredSecretInputString,
|
|
resolveSecretInputString,
|
|
} from "openclaw/plugin-sdk/secret-input-runtime";
|
|
import { canResolveEnvSecretRefInReadOnlyPath } from "openclaw/plugin-sdk/secret-ref-readonly";
|
|
import {
|
|
fetchWithSsrFGuard,
|
|
isPrivateOrLoopbackHost,
|
|
mergeSsrFPolicies,
|
|
ssrfPolicyFromHttpBaseUrlAllowedOrigin,
|
|
type SsrFPolicy,
|
|
} from "openclaw/plugin-sdk/ssrf-runtime";
|
|
import {
|
|
asBoolean,
|
|
isRecord,
|
|
normalizeOptionalLowercaseString,
|
|
normalizeOptionalString,
|
|
uniqueStrings,
|
|
} from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
import { resolveUserPath } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
|
|
const DEFAULT_COMFY_LOCAL_BASE_URL = "http://127.0.0.1:8188";
|
|
const DEFAULT_COMFY_CLOUD_BASE_URL = "https://cloud.comfy.org";
|
|
const DEFAULT_PROMPT_INPUT_NAME = "text";
|
|
const DEFAULT_INPUT_IMAGE_INPUT_NAME = "image";
|
|
const DEFAULT_SEED_INPUT_NAME = "seed";
|
|
const DEFAULT_POLL_INTERVAL_MS = 1_500;
|
|
const DEFAULT_TIMEOUT_MS = 5 * 60_000;
|
|
// randomInt requires a range below 2**48; these seeds also round-trip through JSON exactly.
|
|
const RANDOM_SEED_EXCLUSIVE_MAX = 2 ** 48 - 1;
|
|
|
|
export const DEFAULT_COMFY_MODEL = "workflow";
|
|
|
|
type ComfyMode = "local" | "cloud";
|
|
type ComfyCapability = "image" | "music" | "video";
|
|
type ComfyOutputKind = "audio" | "gifs" | "images" | "videos";
|
|
type ComfyWorkflow = Record<string, unknown>;
|
|
type ComfyProviderConfig = Record<string, unknown>;
|
|
type ComfyFetchGuardParams = Parameters<typeof fetchWithSsrFGuard>[0];
|
|
type ComfyDispatcherPolicy = ComfyFetchGuardParams["dispatcherPolicy"];
|
|
type ComfyPromptResponse = {
|
|
prompt_id?: string;
|
|
};
|
|
type ComfyOutputFile = {
|
|
filename?: string;
|
|
name?: string;
|
|
subfolder?: string;
|
|
type?: string;
|
|
};
|
|
type ComfyHistoryOutputEntry = Partial<Record<ComfyOutputKind, ComfyOutputFile[]>>;
|
|
type ComfyHistoryEntry = {
|
|
outputs?: Record<string, ComfyHistoryOutputEntry>;
|
|
};
|
|
type ComfyUploadResponse = {
|
|
name?: string;
|
|
filename?: string;
|
|
};
|
|
type ComfyStatusResponse = {
|
|
status?: string;
|
|
message?: string;
|
|
error?: string;
|
|
};
|
|
type ComfyNetworkPolicy = {
|
|
apiPolicy?: SsrFPolicy;
|
|
};
|
|
type ComfyApiKeyResolution =
|
|
| {
|
|
status: "available";
|
|
apiKey: string;
|
|
source: string;
|
|
}
|
|
| {
|
|
status: "missing";
|
|
}
|
|
| {
|
|
status: "configured_unavailable";
|
|
};
|
|
|
|
type ComfySourceImage = {
|
|
buffer: Buffer;
|
|
mimeType: string;
|
|
fileName?: string;
|
|
};
|
|
|
|
type ComfyGeneratedAsset = {
|
|
buffer: Buffer;
|
|
mimeType: string;
|
|
fileName: string;
|
|
nodeId: string;
|
|
};
|
|
|
|
type ComfyWorkflowResult = {
|
|
assets: ComfyGeneratedAsset[];
|
|
model: string;
|
|
promptId: string;
|
|
outputNodeIds: string[];
|
|
};
|
|
|
|
function readConfigInteger(config: ComfyProviderConfig, key: string): number | undefined {
|
|
const value = config[key];
|
|
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
|
|
}
|
|
|
|
function getComfyConfig(cfg?: OpenClawConfig): ComfyProviderConfig {
|
|
const pluginConfig = cfg?.plugins?.entries?.comfy?.config;
|
|
if (isRecord(pluginConfig)) {
|
|
return pluginConfig;
|
|
}
|
|
const legacyConfig = cfg?.models?.providers?.comfy;
|
|
return isRecord(legacyConfig) ? legacyConfig : {};
|
|
}
|
|
|
|
function stripNestedCapabilityConfig(config: ComfyProviderConfig): ComfyProviderConfig {
|
|
const next = { ...config };
|
|
delete next.image;
|
|
delete next.video;
|
|
delete next.music;
|
|
return next;
|
|
}
|
|
|
|
function getComfyCapabilityConfig(
|
|
config: ComfyProviderConfig,
|
|
capability: ComfyCapability,
|
|
): ComfyProviderConfig {
|
|
const shared = stripNestedCapabilityConfig(config);
|
|
const nested = config[capability];
|
|
if (!isRecord(nested)) {
|
|
return shared;
|
|
}
|
|
return { ...shared, ...nested };
|
|
}
|
|
|
|
function resolveComfyMode(config: ComfyProviderConfig): ComfyMode {
|
|
return normalizeOptionalString(config.mode) === "cloud" ? "cloud" : "local";
|
|
}
|
|
|
|
function resolveComfyApiKey(
|
|
config: ComfyProviderConfig,
|
|
cfg?: OpenClawConfig,
|
|
): ComfyApiKeyResolution {
|
|
const resolved = resolveSecretInputString({
|
|
value: config.apiKey,
|
|
path: "plugins.entries.comfy.config.apiKey",
|
|
defaults: cfg?.secrets?.defaults,
|
|
mode: "inspect",
|
|
});
|
|
if (resolved.status === "available") {
|
|
const apiKey = normalizeSecretInputString(resolved.value);
|
|
return apiKey
|
|
? {
|
|
status: "available",
|
|
apiKey,
|
|
source: "plugins.entries.comfy.config.apiKey",
|
|
}
|
|
: { status: "missing" };
|
|
}
|
|
if (resolved.status === "configured_unavailable") {
|
|
if (resolved.ref.source !== "env") {
|
|
return { status: "configured_unavailable" };
|
|
}
|
|
const envVarName = resolved.ref.id.trim();
|
|
if (
|
|
!canResolveEnvSecretRefInReadOnlyPath({
|
|
cfg,
|
|
provider: resolved.ref.provider,
|
|
id: envVarName,
|
|
})
|
|
) {
|
|
return { status: "configured_unavailable" };
|
|
}
|
|
const apiKey = normalizeSecretInputString(process.env[envVarName]);
|
|
return apiKey
|
|
? {
|
|
status: "available",
|
|
apiKey,
|
|
source: `plugins.entries.comfy.config.apiKey (${envVarName})`,
|
|
}
|
|
: { status: "configured_unavailable" };
|
|
}
|
|
return { status: "missing" };
|
|
}
|
|
|
|
function getRequiredConfigString(config: ComfyProviderConfig, key: string): string {
|
|
const value = normalizeOptionalString(config[key]);
|
|
if (!value) {
|
|
throw new Error(`plugins.entries.comfy.config.${key} is required`);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function resolveComfyWorkflowSource(config: ComfyProviderConfig): {
|
|
workflow?: ComfyWorkflow;
|
|
workflowPath?: string;
|
|
} {
|
|
const workflow = config.workflow;
|
|
if (isRecord(workflow)) {
|
|
return { workflow: structuredClone(workflow) };
|
|
}
|
|
const workflowPath = normalizeOptionalString(config.workflowPath);
|
|
return { workflowPath };
|
|
}
|
|
|
|
async function loadComfyWorkflow(config: ComfyProviderConfig): Promise<ComfyWorkflow> {
|
|
const source = resolveComfyWorkflowSource(config);
|
|
if (source.workflow) {
|
|
return source.workflow;
|
|
}
|
|
if (!source.workflowPath) {
|
|
throw new Error(
|
|
"plugins.entries.comfy.config.<capability>.workflow or workflowPath is required",
|
|
);
|
|
}
|
|
|
|
const resolvedPath = resolveUserPath(source.workflowPath);
|
|
const raw = await fs.readFile(resolvedPath, "utf8");
|
|
const parsed = JSON.parse(raw) as unknown;
|
|
if (!isRecord(parsed)) {
|
|
throw new Error(`Comfy workflow at ${resolvedPath} must be a JSON object`);
|
|
}
|
|
return parsed;
|
|
}
|
|
|
|
function setWorkflowInput(params: {
|
|
workflow: ComfyWorkflow;
|
|
nodeId: string;
|
|
inputName: string;
|
|
value: unknown;
|
|
}): void {
|
|
const node = params.workflow[params.nodeId];
|
|
if (!isRecord(node)) {
|
|
throw new Error(`Comfy workflow missing node "${params.nodeId}"`);
|
|
}
|
|
const inputs = node.inputs;
|
|
if (!isRecord(inputs)) {
|
|
throw new Error(`Comfy workflow node "${params.nodeId}" is missing an inputs object`);
|
|
}
|
|
inputs[params.inputName] = params.value;
|
|
}
|
|
|
|
async function resolveComfyHeadersConfig(value: unknown, cfg: OpenClawConfig): Promise<Headers> {
|
|
const headers = new Headers();
|
|
if (!isRecord(value)) {
|
|
return headers;
|
|
}
|
|
for (const [name, headerValue] of Object.entries(value)) {
|
|
const path = `plugins.entries.comfy.config.headers.${name}`;
|
|
const inspected = resolveSecretInputString({
|
|
value: headerValue,
|
|
path,
|
|
defaults: cfg.secrets?.defaults,
|
|
mode: "inspect",
|
|
});
|
|
if (inspected.status === "available") {
|
|
headers.set(name, inspected.value);
|
|
continue;
|
|
}
|
|
if (inspected.status === "missing") {
|
|
continue;
|
|
}
|
|
const resolved = await resolveConfiguredSecretInputString({
|
|
config: cfg,
|
|
env: process.env,
|
|
value: headerValue,
|
|
path,
|
|
unresolvedReasonStyle: "detailed",
|
|
});
|
|
if (resolved.unresolvedRefReason) {
|
|
throw new Error(`${path} references an unavailable secret: ${resolved.unresolvedRefReason}`);
|
|
}
|
|
if (resolved.value) {
|
|
headers.set(name, resolved.value);
|
|
}
|
|
}
|
|
return headers;
|
|
}
|
|
|
|
function resolveComfyNetworkPolicy(params: {
|
|
baseUrl: string;
|
|
allowPrivateNetwork: boolean;
|
|
explicitAllowPrivateNetwork: boolean;
|
|
mode: ComfyMode;
|
|
}): ComfyNetworkPolicy {
|
|
let parsed: URL;
|
|
try {
|
|
parsed = new URL(params.baseUrl);
|
|
} catch {
|
|
return {};
|
|
}
|
|
|
|
const hostname = normalizeOptionalLowercaseString(parsed.hostname) ?? "";
|
|
if (!hostname) {
|
|
return {};
|
|
}
|
|
const localHostnamePolicy: SsrFPolicy | undefined =
|
|
params.mode === "local" ? { hostnameAllowlist: [hostname] } : undefined;
|
|
const hostnameOnlyPolicy = localHostnamePolicy ? { apiPolicy: localHostnamePolicy } : {};
|
|
if (!params.allowPrivateNetwork) {
|
|
return hostnameOnlyPolicy;
|
|
}
|
|
// Local mode auto-trusts loopback/IP targets and Compose-style single-label
|
|
// service names; public-looking FQDNs require the operator's explicit
|
|
// allowPrivateNetwork opt-in.
|
|
if (!params.explicitAllowPrivateNetwork && params.mode !== "local") {
|
|
return {};
|
|
}
|
|
if (
|
|
!params.explicitAllowPrivateNetwork &&
|
|
params.mode === "local" &&
|
|
!isPrivateOrLoopbackHost(hostname) &&
|
|
!isSingleLabelServiceHostname(hostname)
|
|
) {
|
|
return hostnameOnlyPolicy;
|
|
}
|
|
|
|
const originPolicy = ssrfPolicyFromHttpBaseUrlAllowedOrigin(params.baseUrl);
|
|
if (!originPolicy) {
|
|
return hostnameOnlyPolicy;
|
|
}
|
|
|
|
return {
|
|
apiPolicy:
|
|
params.mode === "local" ? mergeSsrFPolicies(originPolicy, localHostnamePolicy) : originPolicy,
|
|
};
|
|
}
|
|
|
|
function isSingleLabelServiceHostname(hostname: string): boolean {
|
|
return /^[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?$/u.test(hostname);
|
|
}
|
|
|
|
async function readJsonResponse<T>(params: {
|
|
url: string;
|
|
init?: RequestInit;
|
|
timeoutMs?: number;
|
|
policy?: SsrFPolicy;
|
|
dispatcherPolicy?: ComfyDispatcherPolicy;
|
|
auditContext: string;
|
|
errorPrefix: string;
|
|
}): Promise<T> {
|
|
const { response, release } = await fetchWithSsrFGuard({
|
|
url: params.url,
|
|
init: params.init,
|
|
timeoutMs: params.timeoutMs,
|
|
policy: params.policy,
|
|
dispatcherPolicy: params.dispatcherPolicy,
|
|
auditContext: params.auditContext,
|
|
});
|
|
try {
|
|
const requestHeaders = params.init?.headers;
|
|
await assertOkOrThrowHttpError(response, params.errorPrefix, { requestHeaders });
|
|
return await readProviderJsonResponse<T>(response, params.errorPrefix, { requestHeaders });
|
|
} finally {
|
|
await release();
|
|
}
|
|
}
|
|
|
|
function resolveFileExtension(params: { fileName?: string; mimeType?: string }): string {
|
|
const extension = extensionForMime(params.mimeType);
|
|
if (extension) {
|
|
return extension.slice(1);
|
|
}
|
|
const fileName = params.fileName?.trim();
|
|
if (!fileName) {
|
|
return "bin";
|
|
}
|
|
const dotIndex = fileName.lastIndexOf(".");
|
|
if (dotIndex < 0 || dotIndex === fileName.length - 1) {
|
|
return "bin";
|
|
}
|
|
return fileName.slice(dotIndex + 1);
|
|
}
|
|
|
|
function toBlobBytes(buffer: Buffer): ArrayBuffer {
|
|
const arrayBuffer = new ArrayBuffer(buffer.byteLength);
|
|
new Uint8Array(arrayBuffer).set(buffer);
|
|
return arrayBuffer;
|
|
}
|
|
|
|
async function uploadInputImage(params: {
|
|
baseUrl: string;
|
|
headers: Headers;
|
|
timeoutMs: number;
|
|
policy?: SsrFPolicy;
|
|
dispatcherPolicy?: ComfyDispatcherPolicy;
|
|
image: ComfySourceImage;
|
|
mode: ComfyMode;
|
|
capability: ComfyCapability;
|
|
}): Promise<string> {
|
|
const form = new FormData();
|
|
form.set(
|
|
"image",
|
|
new Blob([toBlobBytes(params.image.buffer)], { type: params.image.mimeType }),
|
|
normalizeOptionalString(params.image.fileName) ||
|
|
`input.${resolveFileExtension({ mimeType: params.image.mimeType })}`,
|
|
);
|
|
form.set("type", "input");
|
|
form.set("overwrite", "true");
|
|
|
|
const headers = new Headers(params.headers);
|
|
headers.delete("Content-Type");
|
|
|
|
const payload = await readJsonResponse<ComfyUploadResponse>({
|
|
url: `${params.baseUrl}${params.mode === "cloud" ? "/api/upload/image" : "/upload/image"}`,
|
|
init: {
|
|
method: "POST",
|
|
headers,
|
|
body: form,
|
|
},
|
|
timeoutMs: params.timeoutMs,
|
|
policy: params.policy,
|
|
dispatcherPolicy: params.dispatcherPolicy,
|
|
auditContext: `comfy-${params.capability}-upload`,
|
|
errorPrefix: "Comfy image upload failed",
|
|
});
|
|
|
|
const uploadedName =
|
|
normalizeOptionalString(payload.filename) || normalizeOptionalString(payload.name);
|
|
if (!uploadedName) {
|
|
throw new Error("Comfy image upload response missing filename");
|
|
}
|
|
return uploadedName;
|
|
}
|
|
|
|
function extractHistoryEntry(history: unknown, promptId: string): ComfyHistoryEntry | null {
|
|
if (!isRecord(history)) {
|
|
return null;
|
|
}
|
|
const directOutputs = history.outputs;
|
|
if (isRecord(directOutputs)) {
|
|
return history as ComfyHistoryEntry;
|
|
}
|
|
const nested = history[promptId];
|
|
if (isRecord(nested)) {
|
|
return nested as ComfyHistoryEntry;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
async function waitForLocalHistory(params: {
|
|
baseUrl: string;
|
|
promptId: string;
|
|
headers: Headers;
|
|
timeoutMs: number;
|
|
pollIntervalMs: number;
|
|
policy?: SsrFPolicy;
|
|
dispatcherPolicy?: ComfyDispatcherPolicy;
|
|
}): Promise<ComfyHistoryEntry> {
|
|
const deadline = Date.now() + params.timeoutMs;
|
|
for (;;) {
|
|
const requestTimeoutMs = resolveComfyRemainingMs(deadline, params.timeoutMs);
|
|
const history = await readJsonResponse<unknown>({
|
|
url: `${params.baseUrl}/history/${params.promptId}`,
|
|
init: {
|
|
method: "GET",
|
|
headers: params.headers,
|
|
},
|
|
timeoutMs: requestTimeoutMs,
|
|
policy: params.policy,
|
|
dispatcherPolicy: params.dispatcherPolicy,
|
|
auditContext: "comfy-history",
|
|
errorPrefix: "Comfy history lookup failed",
|
|
});
|
|
|
|
const entry = extractHistoryEntry(history, params.promptId);
|
|
if (entry?.outputs && Object.keys(entry.outputs).length > 0) {
|
|
return entry;
|
|
}
|
|
|
|
const pollDelayMs = resolveComfyRemainingMs(deadline, params.timeoutMs, params.pollIntervalMs);
|
|
await new Promise((resolve) => {
|
|
setTimeout(resolve, pollDelayMs);
|
|
});
|
|
}
|
|
}
|
|
|
|
async function waitForCloudCompletion(params: {
|
|
baseUrl: string;
|
|
promptId: string;
|
|
headers: Headers;
|
|
timeoutMs: number;
|
|
pollIntervalMs: number;
|
|
policy?: SsrFPolicy;
|
|
dispatcherPolicy?: ComfyDispatcherPolicy;
|
|
}): Promise<void> {
|
|
const deadline = Date.now() + params.timeoutMs;
|
|
for (;;) {
|
|
const requestTimeoutMs = resolveComfyRemainingMs(deadline, params.timeoutMs);
|
|
const status = await readJsonResponse<ComfyStatusResponse>({
|
|
url: `${params.baseUrl}/api/job/${params.promptId}/status`,
|
|
init: {
|
|
method: "GET",
|
|
headers: params.headers,
|
|
},
|
|
timeoutMs: requestTimeoutMs,
|
|
policy: params.policy,
|
|
dispatcherPolicy: params.dispatcherPolicy,
|
|
auditContext: "comfy-status",
|
|
errorPrefix: "Comfy status lookup failed",
|
|
});
|
|
|
|
if (status.status === "completed") {
|
|
return;
|
|
}
|
|
if (status.status === "failed" || status.status === "cancelled") {
|
|
const detail = redactProviderResponseErrorText(
|
|
status.error ?? status.message ?? params.promptId,
|
|
params.headers,
|
|
);
|
|
throw new Error(`Comfy workflow ${status.status}: ${detail}`);
|
|
}
|
|
|
|
const pollDelayMs = resolveComfyRemainingMs(deadline, params.timeoutMs, params.pollIntervalMs);
|
|
await new Promise((resolve) => {
|
|
setTimeout(resolve, pollDelayMs);
|
|
});
|
|
}
|
|
}
|
|
|
|
function resolveComfyRemainingMs(
|
|
deadline: number,
|
|
timeoutMs: number,
|
|
defaultTimeoutMs = timeoutMs,
|
|
) {
|
|
const defaultMs = resolvePositiveTimerTimeoutMs(defaultTimeoutMs, 1);
|
|
const remainingMs = deadline - Date.now();
|
|
if (remainingMs <= 0) {
|
|
throw new Error(`Comfy workflow did not finish within ${Math.ceil(timeoutMs / 1000)}s`);
|
|
}
|
|
return Math.max(1, Math.min(defaultMs, remainingMs));
|
|
}
|
|
|
|
function collectOutputFiles(params: {
|
|
history: ComfyHistoryEntry;
|
|
outputNodeId?: string;
|
|
outputKinds: readonly ComfyOutputKind[];
|
|
capability: ComfyCapability;
|
|
}): Array<{ nodeId: string; file: ComfyOutputFile }> {
|
|
const outputs = params.history.outputs;
|
|
if (!outputs) {
|
|
return [];
|
|
}
|
|
|
|
const nodeIds = params.outputNodeId ? [params.outputNodeId] : Object.keys(outputs);
|
|
const files: Array<{ nodeId: string; file: ComfyOutputFile }> = [];
|
|
for (const nodeId of nodeIds) {
|
|
const entry = outputs[nodeId];
|
|
if (!entry) {
|
|
continue;
|
|
}
|
|
for (const kind of params.outputKinds) {
|
|
const bucket = entry[kind];
|
|
if (!Array.isArray(bucket)) {
|
|
continue;
|
|
}
|
|
for (const file of bucket) {
|
|
if (params.capability === "video" && kind === "images") {
|
|
// Comfy SaveVideo shares the images bucket with real image outputs.
|
|
// Filter before download so mixed workflows cannot return images as videos.
|
|
const fileName =
|
|
normalizeOptionalString(file.filename) || normalizeOptionalString(file.name);
|
|
if (!fileName || !/\.(?:mp4|webm)$/i.test(fileName)) {
|
|
continue;
|
|
}
|
|
}
|
|
files.push({ nodeId, file });
|
|
}
|
|
}
|
|
}
|
|
return files;
|
|
}
|
|
|
|
async function downloadOutputFile(params: {
|
|
baseUrl: string;
|
|
headers: Headers;
|
|
timeoutMs: number;
|
|
policy?: SsrFPolicy;
|
|
dispatcherPolicy?: ComfyDispatcherPolicy;
|
|
file: ComfyOutputFile;
|
|
mode: ComfyMode;
|
|
capability: ComfyCapability;
|
|
maxBytes: number;
|
|
}): Promise<{ buffer: Buffer; mimeType: string }> {
|
|
const fileName =
|
|
normalizeOptionalString(params.file.filename) || normalizeOptionalString(params.file.name);
|
|
if (!fileName) {
|
|
throw new Error("Comfy output entry missing filename");
|
|
}
|
|
|
|
const query = new URLSearchParams({
|
|
filename: fileName,
|
|
subfolder: normalizeOptionalString(params.file.subfolder) ?? "",
|
|
type: normalizeOptionalString(params.file.type) ?? "output",
|
|
});
|
|
const viewPath = params.mode === "cloud" ? "/api/view" : "/view";
|
|
const auditContext = `comfy-${params.capability}-download`;
|
|
|
|
const firstResponse = await fetchWithSsrFGuard({
|
|
url: `${params.baseUrl}${viewPath}?${query.toString()}`,
|
|
init: {
|
|
method: "GET",
|
|
headers: params.headers,
|
|
},
|
|
timeoutMs: params.timeoutMs,
|
|
policy: params.policy,
|
|
dispatcherPolicy: params.dispatcherPolicy,
|
|
auditContext,
|
|
});
|
|
|
|
try {
|
|
await assertOkOrThrowHttpError(firstResponse.response, "Comfy output download failed", {
|
|
requestHeaders: params.headers,
|
|
});
|
|
const mimeType =
|
|
normalizeOptionalString(firstResponse.response.headers.get("content-type")) ||
|
|
"application/octet-stream";
|
|
return {
|
|
buffer: await readResponseWithLimit(firstResponse.response, params.maxBytes, {
|
|
chunkTimeoutMs: params.timeoutMs,
|
|
onOverflow: ({ maxBytes }) =>
|
|
new Error(`Comfy ${params.capability} output download exceeds ${maxBytes} bytes`),
|
|
onIdleTimeout: ({ chunkTimeoutMs }) =>
|
|
new Error(`Comfy ${params.capability} output download stalled after ${chunkTimeoutMs}ms`),
|
|
}),
|
|
mimeType,
|
|
};
|
|
} finally {
|
|
await firstResponse.release();
|
|
}
|
|
}
|
|
|
|
// Only env refs can be checked without I/O. Keep other refs selectable until
|
|
// the async request resolver can establish their availability.
|
|
function hasUnavailableComfyHeaderSecret(value: unknown, cfg?: OpenClawConfig): boolean {
|
|
if (!isRecord(value)) {
|
|
return false;
|
|
}
|
|
return Object.entries(value).some(([name, headerValue]) => {
|
|
const inspected = resolveSecretInputString({
|
|
value: headerValue,
|
|
path: `plugins.entries.comfy.config.headers.${name}`,
|
|
defaults: cfg?.secrets?.defaults,
|
|
mode: "inspect",
|
|
});
|
|
if (inspected.status !== "configured_unavailable" || inspected.ref.source !== "env") {
|
|
return false;
|
|
}
|
|
const envVarName = inspected.ref.id.trim();
|
|
const resolvable =
|
|
canResolveEnvSecretRefInReadOnlyPath({
|
|
cfg,
|
|
provider: inspected.ref.provider,
|
|
id: envVarName,
|
|
}) && Boolean(normalizeSecretInputString(process.env[envVarName]));
|
|
return !resolvable;
|
|
});
|
|
}
|
|
|
|
export function isComfyCapabilityConfigured(params: {
|
|
cfg?: OpenClawConfig;
|
|
agentDir?: string;
|
|
capability: ComfyCapability;
|
|
}): boolean {
|
|
const config = getComfyConfig(params.cfg);
|
|
const capabilityConfig = getComfyCapabilityConfig(config, params.capability);
|
|
const hasWorkflow = Boolean(
|
|
resolveComfyWorkflowSource(capabilityConfig).workflow ||
|
|
normalizeOptionalString(capabilityConfig.workflowPath),
|
|
);
|
|
const hasPromptNode = Boolean(normalizeOptionalString(capabilityConfig.promptNodeId));
|
|
if (!hasWorkflow || !hasPromptNode) {
|
|
return false;
|
|
}
|
|
if (hasUnavailableComfyHeaderSecret(capabilityConfig.headers, params.cfg)) {
|
|
return false;
|
|
}
|
|
if (resolveComfyMode(capabilityConfig) === "local") {
|
|
return true;
|
|
}
|
|
const configuredApiKey = resolveComfyApiKey(capabilityConfig, params.cfg);
|
|
if (configuredApiKey.status === "available") {
|
|
return true;
|
|
}
|
|
if (configuredApiKey.status === "configured_unavailable") {
|
|
return false;
|
|
}
|
|
return isProviderApiKeyConfigured({
|
|
provider: "comfy",
|
|
cfg: params.cfg,
|
|
agentDir: params.agentDir,
|
|
});
|
|
}
|
|
|
|
export async function runComfyWorkflow(params: {
|
|
cfg: OpenClawConfig;
|
|
agentDir?: string;
|
|
authStore?: AuthProfileStore;
|
|
prompt: string;
|
|
model?: string;
|
|
timeoutMs?: number;
|
|
capability: ComfyCapability;
|
|
outputKinds: readonly ComfyOutputKind[];
|
|
inputImage?: ComfySourceImage;
|
|
}): Promise<ComfyWorkflowResult> {
|
|
const config = getComfyConfig(params.cfg);
|
|
const capabilityConfig = getComfyCapabilityConfig(config, params.capability);
|
|
const mode = resolveComfyMode(capabilityConfig);
|
|
const workflow = await loadComfyWorkflow(capabilityConfig);
|
|
const promptNodeId = getRequiredConfigString(capabilityConfig, "promptNodeId");
|
|
const promptInputName =
|
|
normalizeOptionalString(capabilityConfig.promptInputName) ?? DEFAULT_PROMPT_INPUT_NAME;
|
|
const inputImageNodeId = normalizeOptionalString(capabilityConfig.inputImageNodeId);
|
|
const inputImageInputName =
|
|
normalizeOptionalString(capabilityConfig.inputImageInputName) ?? DEFAULT_INPUT_IMAGE_INPUT_NAME;
|
|
const seedNodeId = normalizeOptionalString(capabilityConfig.seedNodeId);
|
|
const seedInputName =
|
|
normalizeOptionalString(capabilityConfig.seedInputName) ?? DEFAULT_SEED_INPUT_NAME;
|
|
const outputNodeId = normalizeOptionalString(capabilityConfig.outputNodeId);
|
|
const pollIntervalMs = resolvePositiveTimerTimeoutMs(
|
|
readConfigInteger(capabilityConfig, "pollIntervalMs"),
|
|
DEFAULT_POLL_INTERVAL_MS,
|
|
);
|
|
const timeoutMs = resolvePositiveTimerTimeoutMs(
|
|
readConfigInteger(capabilityConfig, "timeoutMs") ?? params.timeoutMs,
|
|
DEFAULT_TIMEOUT_MS,
|
|
);
|
|
const providerModel = normalizeOptionalString(params.model) || DEFAULT_COMFY_MODEL;
|
|
|
|
setWorkflowInput({
|
|
workflow,
|
|
nodeId: promptNodeId,
|
|
inputName: promptInputName,
|
|
value: params.prompt,
|
|
});
|
|
|
|
if (seedNodeId) {
|
|
setWorkflowInput({
|
|
workflow,
|
|
nodeId: seedNodeId,
|
|
inputName: seedInputName,
|
|
value: randomInt(RANDOM_SEED_EXCLUSIVE_MAX),
|
|
});
|
|
}
|
|
|
|
const pluginApiKey = resolveComfyApiKey(capabilityConfig, params.cfg);
|
|
const resolvedAuth =
|
|
mode === "cloud"
|
|
? pluginApiKey.status === "available"
|
|
? {
|
|
apiKey: pluginApiKey.apiKey,
|
|
source: pluginApiKey.source,
|
|
mode: "api-key" as const,
|
|
}
|
|
: pluginApiKey.status === "configured_unavailable"
|
|
? null
|
|
: await resolveApiKeyForProvider({
|
|
provider: "comfy",
|
|
cfg: params.cfg,
|
|
agentDir: params.agentDir,
|
|
store: params.authStore,
|
|
})
|
|
: null;
|
|
if (mode === "cloud" && !resolvedAuth?.apiKey) {
|
|
throw new Error("Comfy Cloud API key missing");
|
|
}
|
|
|
|
const explicitAllowPrivateNetwork = asBoolean(capabilityConfig.allowPrivateNetwork) === true;
|
|
const { baseUrl, allowPrivateNetwork, headers, dispatcherPolicy } =
|
|
resolveProviderHttpRequestConfig({
|
|
baseUrl: normalizeOptionalString(capabilityConfig.baseUrl),
|
|
defaultBaseUrl:
|
|
mode === "cloud" ? DEFAULT_COMFY_CLOUD_BASE_URL : DEFAULT_COMFY_LOCAL_BASE_URL,
|
|
allowPrivateNetwork: mode === "local" || explicitAllowPrivateNetwork,
|
|
headers: await resolveComfyHeadersConfig(capabilityConfig.headers, params.cfg),
|
|
defaultHeaders:
|
|
mode === "cloud"
|
|
? {
|
|
"X-API-Key": resolvedAuth?.apiKey ?? "",
|
|
"Content-Type": "application/json",
|
|
}
|
|
: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
provider: "comfy",
|
|
capability: params.capability === "music" ? "audio" : params.capability,
|
|
transport: "http",
|
|
});
|
|
const normalizedBaseUrl =
|
|
normalizeBaseUrl(baseUrl) ||
|
|
(mode === "cloud" ? DEFAULT_COMFY_CLOUD_BASE_URL : DEFAULT_COMFY_LOCAL_BASE_URL);
|
|
const networkPolicy = resolveComfyNetworkPolicy({
|
|
baseUrl: normalizedBaseUrl,
|
|
allowPrivateNetwork,
|
|
explicitAllowPrivateNetwork,
|
|
mode,
|
|
});
|
|
|
|
if (params.inputImage) {
|
|
if (!inputImageNodeId) {
|
|
throw new Error(
|
|
"Comfy edit requests require plugins.entries.comfy.config.<capability>.inputImageNodeId to be configured",
|
|
);
|
|
}
|
|
const uploadedName = await uploadInputImage({
|
|
baseUrl: normalizedBaseUrl,
|
|
headers: new Headers(headers),
|
|
timeoutMs,
|
|
policy: networkPolicy.apiPolicy,
|
|
dispatcherPolicy,
|
|
image: params.inputImage,
|
|
mode,
|
|
capability: params.capability,
|
|
});
|
|
setWorkflowInput({
|
|
workflow,
|
|
nodeId: inputImageNodeId,
|
|
inputName: inputImageInputName,
|
|
value: uploadedName,
|
|
});
|
|
}
|
|
|
|
const submitPayload = {
|
|
prompt: workflow,
|
|
...(mode === "cloud" && resolvedAuth?.apiKey
|
|
? { extra_data: { api_key_comfy_org: resolvedAuth.apiKey } }
|
|
: {}),
|
|
};
|
|
|
|
const promptResponse = await readJsonResponse<ComfyPromptResponse>({
|
|
url: `${normalizedBaseUrl}${mode === "cloud" ? "/api/prompt" : "/prompt"}`,
|
|
init: {
|
|
method: "POST",
|
|
headers,
|
|
body: JSON.stringify(submitPayload),
|
|
},
|
|
timeoutMs,
|
|
policy: networkPolicy.apiPolicy,
|
|
dispatcherPolicy,
|
|
auditContext: `comfy-${params.capability}-generate`,
|
|
errorPrefix: "Comfy workflow submit failed",
|
|
});
|
|
|
|
const promptId = normalizeOptionalString(promptResponse.prompt_id);
|
|
if (!promptId) {
|
|
throw new Error("Comfy workflow submit response missing prompt_id");
|
|
}
|
|
|
|
const history =
|
|
mode === "cloud"
|
|
? await (async () => {
|
|
await waitForCloudCompletion({
|
|
baseUrl: normalizedBaseUrl,
|
|
promptId,
|
|
headers: new Headers(headers),
|
|
timeoutMs,
|
|
pollIntervalMs,
|
|
policy: networkPolicy.apiPolicy,
|
|
dispatcherPolicy,
|
|
});
|
|
return await readJsonResponse<unknown>({
|
|
url: `${normalizedBaseUrl}/api/history_v2/${promptId}`,
|
|
init: {
|
|
method: "GET",
|
|
headers: new Headers(headers),
|
|
},
|
|
timeoutMs,
|
|
policy: networkPolicy.apiPolicy,
|
|
dispatcherPolicy,
|
|
auditContext: "comfy-history",
|
|
errorPrefix: "Comfy history lookup failed",
|
|
});
|
|
})()
|
|
: await waitForLocalHistory({
|
|
baseUrl: normalizedBaseUrl,
|
|
promptId,
|
|
headers: new Headers(headers),
|
|
timeoutMs,
|
|
pollIntervalMs,
|
|
policy: networkPolicy.apiPolicy,
|
|
dispatcherPolicy,
|
|
});
|
|
|
|
const historyEntry = extractHistoryEntry(history, promptId);
|
|
if (!historyEntry) {
|
|
throw new Error(`Comfy history response missing outputs for prompt ${promptId}`);
|
|
}
|
|
|
|
const outputFiles = collectOutputFiles({
|
|
history: historyEntry,
|
|
outputNodeId,
|
|
outputKinds: params.outputKinds,
|
|
capability: params.capability,
|
|
});
|
|
if (outputFiles.length === 0) {
|
|
throw new Error(`Comfy workflow ${promptId} completed without ${params.capability} outputs`);
|
|
}
|
|
|
|
const assets: ComfyGeneratedAsset[] = [];
|
|
const outputKind = params.capability === "music" ? "audio" : params.capability;
|
|
const maxOutputBytes = resolveGeneratedMediaMaxBytes(params.cfg, outputKind);
|
|
let assetIndex = 0;
|
|
for (const output of outputFiles) {
|
|
const downloaded = await downloadOutputFile({
|
|
baseUrl: normalizedBaseUrl,
|
|
headers: new Headers(headers),
|
|
timeoutMs,
|
|
policy: networkPolicy.apiPolicy,
|
|
dispatcherPolicy,
|
|
file: output.file,
|
|
mode,
|
|
capability: params.capability,
|
|
maxBytes: maxOutputBytes,
|
|
});
|
|
assetIndex += 1;
|
|
const originalName =
|
|
normalizeOptionalString(output.file.filename) || normalizeOptionalString(output.file.name);
|
|
assets.push({
|
|
buffer: downloaded.buffer,
|
|
mimeType: downloaded.mimeType,
|
|
fileName:
|
|
originalName ||
|
|
`${params.capability}-${assetIndex}.${resolveFileExtension({ mimeType: downloaded.mimeType })}`,
|
|
nodeId: output.nodeId,
|
|
});
|
|
}
|
|
|
|
return {
|
|
assets,
|
|
model: providerModel,
|
|
promptId,
|
|
outputNodeIds: uniqueStrings(outputFiles.map((entry) => entry.nodeId)),
|
|
};
|
|
}
|
|
/* oxlint-disable max-lines -- TODO: split this grandfathered oversized file. */
|