Files
dsh-comfyui/lib/index.js
T
2026-11-23 09:49:57 +08:00

670 lines
27 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* dsh-comfyui — 把局域网 ComfyUI 接进 DSH(服务端)。
*
* 出口:
* ① 设置页接口
* GET /plugin/comfyui/status 地址 + 是否可达 + 版本 + GPU + 队列 + 模型
* POST /plugin/comfyui/config 保存 baseUrl / outputDir
* POST /plugin/comfyui/test 测试连接
* ② 工具
* comfy_status 只读体检
* comfy_generate_image 内置 Z-Image Turbo 工作流(实测 24s / 1024² / 8 步)
* comfy_run_workflow 跑任意 **API 格式** 工作流(UI 里「Export (API)」导出的那种),
* 支持把本地图片先上传进 ComfyUI 的 input 目录
* comfy_upload 单独上传文件,返回可用于 LoadImage 的文件名
*
* 为什么内置工作流是「解出来的」:ComfyUI 的 /prompt 只吃 API 格式
* ({"节点id": {class_type, inputs}}),而前端模板是 UI 格式(nodes/links/widgets)。
* 官方 image_z_image_turbo.json 用的是子图(definitions.subgraphs),
* 这里已按它的连线还原成 API 图,并在 .4 上实测出图成功。
*
* 设置存放:~/.dsh/storages/dsh-comfyui/config.json(插件自己的状态文件,
* 不去改用户的 cordis.patch.yml)。优先级:状态文件 > 插件 config > 内置默认。
*/
import { createRequire } from "node:module";
import { realpathSync } from "node:fs";
import { mkdir, writeFile, readFile, readdir } from "node:fs/promises";
import { dirname, join, basename } from "node:path";
import { homedir } from "node:os";
export const name = "comfyui";
/** 只依赖三个 seam:HTTP 路由、工具注册、日志。 */
export const inject = ["webServer", "tools"];
const DEFAULTS = {
/** 留空表示未配置:地址请在设置页填写,或写进 profile 的 cordis.patch.yml */
baseUrl: "",
/** 落盘目录;留空 = <cwd>/comfyui */
outputDir: "",
/** 单次等待上限(毫秒) */
timeoutMs: 600_000,
pollIntervalMs: 1_200,
/** 内置 Z-Image Turbo 工作流用的模型(换模型时在设置页改) */
unet: "z_image_turbo_bf16.safetensors",
clip: "qwen_3_4b.safetensors",
clipType: "lumina2",
vae: "ae.safetensors",
};
/* ── 从运行中的 dsh 安装里解析内部包(createRequire 对任何路径都成功,
* 必须逐个候选真的去 req(spec),见 AGENTS.md 记录的坑) ── */
function safeRealpath(p) {
try { return realpathSync(p); } catch { return undefined; }
}
function resolveFromDsh(spec) {
const entry = process.argv[1];
const candidates = [];
if (entry) {
candidates.push(entry);
const real = safeRealpath(entry);
if (real) candidates.push(real);
}
try {
const root = dirname(dirname(process.execPath));
candidates.push(join(root, "lib", "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js"));
} catch { /* 忽略 */ }
for (const c of candidates) {
try {
return createRequire(`file://${c}`)(spec);
} catch { /* 下一个 */ }
}
return undefined;
}
function cfgOf(config) {
if (!config) return {};
if (typeof config.get === "function") {
try { return config.get() ?? {}; } catch { return {}; }
}
return config;
}
const now = () => Date.now();
function stamp() {
const d = new Date();
const p = (n) => String(n).padStart(2, "0");
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
}
function slug(text, max = 24) {
const s = String(text || "").replace(/[\s\n\r\t]+/g, "-").replace(/[^\p{L}\p{N}\-_]/gu, "").slice(0, max);
return s || "output";
}
async function uniquePath(dir, base, ext) {
const taken = new Set(await readdir(dir).catch(() => []));
let name = `${base}.${ext}`;
let n = 1;
while (taken.has(name)) name = `${base}-${++n}.${ext}`;
return join(dir, name);
}
/** 状态文件路径(插件自己的设置,不进 profile 配置)。 */
function stateFile() {
const home = process.env.DSH_HOME || join(homedir(), ".dsh");
return join(home, "storages", "dsh-comfyui", "config.json");
}
/** 把上游错误压成一句话。 */
function errText(status, body) {
if (!body) return `HTTP ${status}`;
if (typeof body === "string") return `${status}: ${body.slice(0, 240)}`;
const ne = body.node_errors || {};
const first = Object.entries(ne)[0];
if (first) {
const [nid, info] = first;
const msg = (info?.errors || []).map((e) => `${e.message || e.type}${e.details ? `:${e.details}` : ""}`).join(";");
return `节点 ${nid} 校验失败:${msg || "未知错误"}`;
}
const e = body.error;
if (typeof e === "string") return e;
if (e?.message) return e.message + (e.details ? `:${e.details}` : "");
return JSON.stringify(body).slice(0, 240);
}
export function apply(ctx, config) {
const cfgNow = () => ({ ...DEFAULTS, ...cfgOf(config) });
const route = (spec) => ctx.effect(() => ctx.webServer.register(spec));
const tool = (def) => ctx.effect(() => { ctx.tools.register(def); });
/* ── 设置:状态文件 > config > 默认 ─────────────────────────── */
let state = {};
async function loadState() {
try {
state = JSON.parse(await readFile(stateFile(), "utf8")) || {};
} catch { state = {}; }
return state;
}
async function saveState(patch) {
const merged = { ...state, ...patch };
const file = stateFile();
await mkdir(dirname(file), { recursive: true });
await writeFile(file, JSON.stringify(merged, null, 2) + "\n", { mode: 0o600 });
state = merged;
return merged;
}
const settings = () => {
const c = cfgNow();
return {
baseUrl: String(state.baseUrl || c.baseUrl || DEFAULTS.baseUrl).replace(/\/+$/, ""),
outputDir: String(state.outputDir ?? c.outputDir ?? "").trim(),
timeoutMs: Number(c.timeoutMs ?? DEFAULTS.timeoutMs),
pollIntervalMs: Number(c.pollIntervalMs ?? DEFAULTS.pollIntervalMs),
unet: String(state.unet || c.unet || DEFAULTS.unet),
clip: String(state.clip || c.clip || DEFAULTS.clip),
clipType: String(state.clipType || c.clipType || DEFAULTS.clipType),
vae: String(state.vae || c.vae || DEFAULTS.vae),
};
};
/* ── HTTP ─────────────────────────────────────────────────── */
async function cget(path, timeoutMs = 30_000) {
const s = settings();
if (!s.baseUrl) throw new Error("还没有配置 ComfyUI 地址 —— 打开「设置 → ComfyUI」填一个再试");
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), timeoutMs);
try {
const resp = await fetch(`${s.baseUrl}${path}`, {
signal: ctrl.signal,
headers: { Accept: "application/json" },
});
const text = await resp.text();
let body = text;
try { body = JSON.parse(text); } catch { /* 保留文本 */ }
if (!resp.ok) {
const err = new Error(errText(resp.status, body));
err.status = resp.status;
throw err;
}
return body;
} catch (e) {
if (e?.name === "AbortError") throw new Error(`连接 ComfyUI 超时(${s.baseUrl})`);
if (e?.status) throw e;
throw new Error(`连接不上 ComfyUI(${s.baseUrl}):${e?.message || e}`);
} finally {
clearTimeout(t);
}
}
async function cpost(path, payload, timeoutMs = 60_000) {
const s = settings();
if (!s.baseUrl) throw new Error("还没有配置 ComfyUI 地址 —— 打开「设置 → ComfyUI」填一个再试");
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), timeoutMs);
try {
const resp = await fetch(`${s.baseUrl}${path}`, {
method: "POST",
signal: ctrl.signal,
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify(payload),
});
const text = await resp.text();
let body = text;
try { body = JSON.parse(text); } catch { /* 保留文本 */ }
if (!resp.ok) {
const err = new Error(errText(resp.status, body));
err.status = resp.status;
err.body = body;
throw err;
}
return body;
} catch (e) {
if (e?.name === "AbortError") throw new Error("提交任务超时");
if (e?.status) throw e;
throw new Error(`提交任务失败:${e?.message || e}`);
} finally {
clearTimeout(t);
}
}
/** 探测:拿 system_stats(最轻)。 */
async function probe() {
const s = settings();
const stats = await cget("/system_stats", 10_000);
const sys = stats?.system || {};
const devices = (stats?.devices || []).map((d) => ({
name: String(d.name || ""),
type: String(d.type || ""),
vramTotalGB: Math.round((d.vram_total || 0) / 2 ** 30 * 10) / 10,
vramFreeGB: Math.round((d.vram_free || 0) / 2 ** 30 * 10) / 10,
}));
let queue = { running: 0, pending: 0 };
try {
const q = await cget("/queue", 8_000);
queue = { running: (q.queue_running || []).length, pending: (q.queue_pending || []).length };
} catch { /* 队列查不到不算失败 */ }
return {
baseUrl: s.baseUrl,
version: String(sys.comfyui_version || ""),
os: String(sys.os || ""),
ramTotalGB: Math.round((sys.ram_total || 0) / 2 ** 30 * 10) / 10,
devices,
queue,
};
}
/* ── 提交并等待 ───────────────────────────────────────────── */
async function submit(workflow, clientId) {
const s = settings();
const body = await cpost("/prompt", {
prompt: workflow,
client_id: clientId || `dsh-${now()}`,
});
const id = String(body?.prompt_id || "");
if (!id) throw new Error("ComfyUI 没有返回 prompt_id");
return id;
}
async function waitFor(promptId, timeoutMs) {
const s = settings();
const deadline = now() + (timeoutMs ?? s.timeoutMs);
while (now() < deadline) {
const h = await cget(`/history/${encodeURIComponent(promptId)}`, 20_000);
const item = h?.[promptId];
if (item) {
const status = item.status || {};
if (status.status_str === "error" || status.completed === false && status.status_str === "error") {
const msgs = (status.messages || [])
.filter((m) => m?.[0] === "execution_error")
.map((m) => m?.[1]?.exception_message || m?.[1]?.node_type || "执行错误");
throw new Error(`工作流执行失败:${msgs.join(";") || "未知错误"}`);
}
if (status.status_str === "success" || status.completed === true) return item;
// 有的版本成功时不写 status_str,靠 outputs 判断
if (status.completed !== false && Object.keys(item.outputs || {}).length > 0) return item;
}
await new Promise((r) => setTimeout(r, s.pollIntervalMs));
}
throw new Error(`等待超时(${Math.round((timeoutMs ?? s.timeoutMs) / 1000)}s)。任务可能仍在跑:${promptId}`);
}
/** 从 history 条目里下载产物。 */
async function collectOutputs(item, nameHint) {
const s = settings();
const dir = s.outputDir || join(process.cwd(), "comfyui");
await mkdir(dir, { recursive: true });
const saved = [];
const outputs = item.outputs || {};
for (const [nodeId, out] of Object.entries(outputs)) {
const groups = [
["images", "png"],
["gifs", "webp"],
["videos", "mp4"],
["audio", "wav"],
];
for (const [key, fallbackExt] of groups) {
for (const f of out?.[key] || []) {
const filename = String(f.filename || "");
if (!filename) continue;
const sub = String(f.subfolder || "");
const type = String(f.type || "output");
const url = `${settings().baseUrl}/view?filename=${encodeURIComponent(filename)}&subfolder=${encodeURIComponent(sub)}&type=${encodeURIComponent(type)}`;
const resp = await fetch(url);
if (!resp.ok) throw new Error(`下载产物失败(${filename}):HTTP ${resp.status}`);
const buf = Buffer.from(await resp.arrayBuffer());
const ext = (filename.match(/\.([a-z0-9]+)$/i)?.[1] || fallbackExt).toLowerCase();
const file = await uniquePath(dir, `${stamp()}-${slug(nameHint || filename)}`, ext);
await writeFile(file, buf, { mode: 0o644 });
saved.push({ nodeId, kind: key, path: file, bytes: buf.length });
}
}
}
return saved;
}
/* ── 内置工作流:Z-Image Turbo 文生图 ────────────────────────
* 由官方 image_z_image_turbo.json 的子图连线还原而来,已在 .4 实测成功。 */
function buildZImageWorkflow({ prompt, width, height, steps, seed, prefix }) {
const s = settings();
return {
"30": { class_type: "CLIPLoader", inputs: { clip_name: s.clip, type: s.clipType, device: "default" } },
"29": { class_type: "VAELoader", inputs: { vae_name: s.vae } },
"28": { class_type: "UNETLoader", inputs: { unet_name: s.unet, weight_dtype: "default" } },
"27": { class_type: "CLIPTextEncode", inputs: { clip: ["30", 0], text: prompt } },
"33": { class_type: "ConditioningZeroOut", inputs: { conditioning: ["27", 0] } },
"11": { class_type: "ModelSamplingAuraFlow", inputs: { model: ["28", 0], shift: 3 } },
"13": { class_type: "EmptySD3LatentImage", inputs: { width, height, batch_size: 1 } },
"3": {
class_type: "KSampler",
inputs: {
model: ["11", 0], positive: ["27", 0], negative: ["33", 0], latent_image: ["13", 0],
seed, steps, cfg: 1, sampler_name: "res_multistep", scheduler: "simple", denoise: 1,
},
},
"8": { class_type: "VAEDecode", inputs: { samples: ["3", 0], vae: ["29", 0] } },
"9": { class_type: "SaveImage", inputs: { images: ["8", 0], filename_prefix: prefix } },
};
}
async function generateImage(args) {
const prompt = String(args?.prompt || "").trim();
if (!prompt) throw new Error("prompt 不能为空");
const round16 = (v, fallback) => {
const n = Number(v);
if (!Number.isFinite(n) || n <= 0) return fallback;
return Math.max(256, Math.min(2048, Math.round(n / 16) * 16));
};
const width = round16(args?.width, 1024);
const height = round16(args?.height, 1024);
const steps = Math.max(1, Math.min(40, Number(args?.steps) || 8));
const seed = Number.isFinite(Number(args?.seed)) ? Number(args.seed) : Math.floor(Math.random() * 1e12);
const t0 = now();
const wf = buildZImageWorkflow({ prompt, width, height, steps, seed, prefix: "dsh-comfy" });
const id = await submit(wf);
const item = await waitFor(id);
const saved = await collectOutputs(item, prompt);
if (!saved.length) throw new Error("工作流跑完了,但没有产出图片");
const first = saved[0];
return {
path: first.path,
bytes: first.bytes,
width,
height,
steps,
seed,
model: settings().unet,
elapsedMs: now() - t0,
promptId: id,
};
}
/* ── 上传本地文件到 ComfyUI 的 input 目录 ─────────────────── */
async function uploadFile(filePath, overrideName) {
const { readFile: rf } = await import("node:fs/promises");
let buf;
try {
buf = await rf(filePath);
} catch (e) {
throw new Error(`读不到文件 ${filePath}:${e?.message || e}`);
}
const nm = overrideName || basename(filePath);
const s = settings();
const form = new FormData();
form.append("image", new Blob([buf]), nm);
form.append("overwrite", "true");
const resp = await fetch(`${s.baseUrl}/upload/image`, { method: "POST", body: form });
const text = await resp.text();
let body = text;
try { body = JSON.parse(text); } catch { /* 文本 */ }
if (!resp.ok) throw new Error(`上传失败:${errText(resp.status, body)}`);
return {
name: String(body?.name || nm),
subfolder: String(body?.subfolder || ""),
type: String(body?.type || "input"),
};
}
/* ── 设置页路由 ───────────────────────────────────────────── */
const PREFIX = "/plugin/comfyui";
function respond(res, code, body) {
const text = JSON.stringify(body);
res.writeHead(code, {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-store",
"Content-Length": Buffer.byteLength(text),
});
res.end(text);
}
async function readBody(req) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > 64 * 1024) throw new Error("请求体过大");
chunks.push(chunk);
}
if (!chunks.length) return {};
try { return JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { throw new Error("请求体不是合法 JSON"); }
}
route({
kind: "exact",
path: `${PREFIX}/status`,
async handler(req, res) {
if (req.method !== "GET" && req.method !== "HEAD") return respond(res, 405, { ok: false, error: "只支持 GET" });
const s = settings();
if (!s.baseUrl) {
return respond(res, 200, { ok: true, reachable: false, baseUrl: "", error: "还没有配置 ComfyUI 地址" });
}
try {
const info = await probe();
respond(res, 200, { ok: true, reachable: true, ...info, outputDir: s.outputDir || join(process.cwd(), "comfyui"), models: { unet: s.unet, clip: s.clip, clipType: s.clipType, vae: s.vae } });
} catch (e) {
respond(res, 200, { ok: true, reachable: false, baseUrl: s.baseUrl, error: String(e?.message || e) });
}
},
});
route({
kind: "exact",
path: `${PREFIX}/config`,
async handler(req, res) {
if (req.method !== "POST") return respond(res, 405, { ok: false, error: "只支持 POST" });
try {
const body = await readBody(req);
const patch = {};
if (typeof body.baseUrl === "string") {
const url = body.baseUrl.trim().replace(/\/+$/, "");
if (url && !/^https?:\/\//i.test(url)) return respond(res, 400, { ok: false, error: "地址要以 http:// 或 https:// 开头" });
patch.baseUrl = url;
}
if (typeof body.outputDir === "string") patch.outputDir = body.outputDir.trim();
for (const k of ["unet", "clip", "clipType", "vae"]) {
if (typeof body[k] === "string" && body[k].trim()) patch[k] = body[k].trim();
}
const merged = await saveState(patch);
respond(res, 200, { ok: true, ...settings(), saved: Object.keys(patch) });
} catch (e) {
ctx.logger?.warn?.("comfyui: 保存设置失败 %s", e?.message || e);
respond(res, 500, { ok: false, error: String(e?.message || e) });
}
},
});
route({
kind: "exact",
path: `${PREFIX}/test`,
async handler(req, res) {
if (req.method !== "POST" && req.method !== "GET") return respond(res, 405, { ok: false, error: "只支持 GET / POST" });
try {
const info = await probe();
respond(res, 200, { ok: true, ...info });
} catch (e) {
respond(res, 400, { ok: false, error: String(e?.message || e) });
}
},
});
/* ── 工具 ────────────────────────────────────────────────── */
const defineTool = resolveFromDsh("@deepseek-ai/dsh-tools")?.defineTool;
const registered = [];
const registerTool = (def) => { registered.push(def.name); ctx.effect(() => { ctx.tools.register(def); }); };
if (!defineTool) {
ctx.logger?.warn?.("comfyui: 未解析到 @deepseek-ai/dsh-tools,工具不注册(设置页仍可用)");
return;
}
registerTool(defineTool({
name: "comfy_status",
description: "查看局域网 ComfyUI 的状态:是否连得上、版本、GPU 显存、队列、以及内置工作流用的模型。不消耗算力。",
parameters: {},
output: {
schema: {
type: "object",
additionalProperties: false,
properties: {
reachable: { type: "boolean" },
baseUrl: { type: "string" },
version: { type: "string" },
gpu: { type: "string", description: "第一块 GPU 的名字;空串表示没有" },
vramFreeGB: { type: "number" },
running: { type: "integer" },
pending: { type: "integer" },
unet: { type: "string" },
error: { type: "string", description: "连不上时的原因;正常时为空串" },
},
},
render: (_a, v) => [{
type: "text",
text: v.reachable
? `ComfyUI ${v.version} @ ${v.baseUrl}|${v.gpu}(空闲 ${v.vramFreeGB}GB)|队列 ${v.running} 运行 / ${v.pending} 排队|内置模型 ${v.unet}`
: `连不上 ComfyUI(${v.baseUrl}):${v.error}`,
}],
},
async execute() {
const s = settings();
if (!s.baseUrl) {
return respond(res, 200, { ok: true, reachable: false, baseUrl: "", error: "还没有配置 ComfyUI 地址" });
}
try {
const info = await probe();
const gpu = info.devices[0] || {};
return {
reachable: true, baseUrl: info.baseUrl, version: info.version,
gpu: gpu.name || "", vramFreeGB: gpu.vramFreeGB || 0,
running: info.queue.running, pending: info.queue.pending,
unet: s.unet, error: "",
};
} catch (e) {
return {
reachable: false, baseUrl: s.baseUrl, version: "", gpu: "", vramFreeGB: 0,
running: 0, pending: 0, unet: s.unet, error: String(e?.message || e),
};
}
},
}));
registerTool(defineTool({
name: "comfy_generate_image",
description: "用 .4 那台 ComfyUI 出图(内置 Z-Image Turbo 工作流,1024² / 8 步约 25 秒)。结果落盘并返回绝对路径。适合作图要快、想用本地显卡的时候。",
parameters: {
prompt: { type: "string", required: true, description: "画面描述,英文或中文都行" },
width: { type: "integer", description: "宽度,默认 1024,会自动对齐到 16 的倍数,范围 256–2048" },
height: { type: "integer", description: "高度,默认 1024,同上" },
steps: { type: "integer", description: "采样步数,默认 8(turbo 模型 8 步够用),最多 40" },
seed: { type: "integer", description: "随机种子;不给就随机" },
},
output: {
schema: {
type: "object",
additionalProperties: false,
properties: {
path: { type: "string" },
bytes: { type: "integer" },
width: { type: "integer" },
height: { type: "integer" },
steps: { type: "integer" },
seed: { type: "integer" },
model: { type: "string" },
elapsedMs: { type: "integer" },
promptId: { type: "string" },
},
},
render: (_a, v) => [{
type: "text",
text: `已生成图片:${v.path}\n${v.width}×${v.height},${(v.bytes / 1024).toFixed(0)}KB,${v.steps} 步,用时 ${(v.elapsedMs / 1000).toFixed(1)}s(${v.model})`,
}],
},
async execute(args) {
return generateImage(args || {});
},
}));
registerTool(defineTool({
name: "comfy_run_workflow",
description:
"在 ComfyUI 上跑任意工作流(必须是 API 格式:在 ComfyUI 界面里用「导出 (API)」得到的那种 {\"节点id\":{class_type,inputs}})。会等它跑完并把产物下载到本地,返回文件路径。需要本地图片做输入时,先调 comfy_upload 拿到文件名,再在 workflow 里引用。",
parameters: {
workflow: { type: "string", required: true, description: "API 格式工作流 JSON(字符串形式)" },
nameHint: { type: "string", description: "给产物文件起名用,通常填提示词摘要" },
timeoutSeconds: { type: "integer", description: "最多等多久,默认 600 秒" },
},
output: {
schema: {
type: "object",
additionalProperties: false,
properties: {
promptId: { type: "string" },
files: { type: "array", items: { type: "string" }, description: "下载到本地的产物路径" },
bytes: { type: "integer" },
elapsedMs: { type: "integer" },
count: { type: "integer" },
},
},
render: (_a, v) => [{
type: "text",
text: v.count
? `工作流跑完:${v.count} 个产物(${(v.bytes / 1024 / 1024).toFixed(1)}MB,${(v.elapsedMs / 1000).toFixed(1)}s)\n` + v.files.join("\n")
: "工作流跑完了,但没有下载到任何产物(检查 SaveImage / SaveVideo 之类节点)",
}],
},
async execute(args) {
const raw = String(args?.workflow || "").trim();
if (!raw) throw new Error("workflow 不能为空");
let wf;
try {
wf = JSON.parse(raw);
} catch (e) {
throw new Error(`workflow 不是合法 JSON:${e?.message || e}。注意要 API 格式,不是界面里的 UI 格式`);
}
if (!wf || typeof wf !== "object" || Array.isArray(wf)) {
throw new Error("workflow 必须是 {节点id: {class_type, inputs}} 形式的对象(API 格式)");
}
const firstKey = Object.keys(wf)[0];
if (firstKey && !wf[firstKey]?.class_type) {
throw new Error("这看起来是 UI 格式(有 nodes/links)。请在 ComfyUI 界面里用「导出 (API)」再导出一次");
}
const t0 = now();
const id = await submit(wf);
const item = await waitFor(id, (Number(args?.timeoutSeconds) > 0 ? Number(args.timeoutSeconds) : undefined) ? Number(args.timeoutSeconds) * 1000 : undefined);
const saved = await collectOutputs(item, String(args?.nameHint || "workflow"));
return {
promptId: id,
files: saved.map((s) => s.path),
bytes: saved.reduce((a, b) => a + b.bytes, 0),
elapsedMs: now() - t0,
count: saved.length,
};
},
}));
registerTool(defineTool({
name: "comfy_upload",
description: "把本地文件上传到 ComfyUI 的 input 目录,返回文件名;用于给图生视频 / 图片编辑这类需要本地输入的工作流。",
parameters: {
path: { type: "string", required: true, description: "本地文件绝对路径" },
name: { type: "string", description: "上传后在 ComfyUI 里的文件名;不给就用原文件名" },
},
output: {
schema: {
type: "object",
additionalProperties: false,
properties: {
name: { type: "string" },
subfolder: { type: "string" },
type: { type: "string" },
},
},
render: (_a, v) => [{ type: "text", text: `已上传为 ${v.subfolder ? v.subfolder + "/" : ""}${v.name}` }],
},
async execute(args) {
const p = String(args?.path || "").trim();
if (!p) throw new Error("path 不能为空");
return uploadFile(p, args?.name ? String(args.name) : undefined);
},
}));
// 首次启动读一次状态文件
ctx.effect(() => {
loadState().catch(() => {});
});
ctx.logger?.info?.("comfyui: 已就绪(设置页 + %d 个工具)", registered.length);
}