dsh-novel-image 0.0.0 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +116 -0
- package/README.md +137 -6
- package/client.js +1059 -0
- package/docs/DETAIL.md +113 -0
- package/icon.svg +8 -0
- package/index.js +875 -11
- package/lib/assets/store.mjs +173 -0
- package/lib/canon/extract.mjs +333 -0
- package/lib/canon/merge.mjs +44 -0
- package/lib/canon/store.mjs +188 -0
- package/lib/core/errors.mjs +22 -0
- package/lib/core/ids.mjs +9 -0
- package/lib/core/storage.mjs +113 -0
- package/lib/cover/plan.mjs +64 -0
- package/lib/critique/parse.mjs +112 -0
- package/lib/critique/prompt.mjs +78 -0
- package/lib/critique/revision.mjs +96 -0
- package/lib/generate/comfyui.mjs +95 -0
- package/lib/generate/incremental.mjs +36 -0
- package/lib/generate/limits.mjs +43 -0
- package/lib/generate/mock.mjs +29 -0
- package/lib/generate/openai.mjs +138 -0
- package/lib/generate/state.mjs +29 -0
- package/lib/generate/store.mjs +186 -0
- package/lib/generate/workflow.mjs +76 -0
- package/lib/generate/workflows.mjs +59 -0
- package/lib/prompt/compile.mjs +390 -0
- package/lib/prompt/platforms.mjs +102 -0
- package/lib/prompt/profiles.mjs +109 -0
- package/lib/remote-contract.js +81 -0
- package/lib/remote.js +403 -0
- package/lib/schema.mjs +213 -0
- package/lib/service.mjs +1180 -0
- package/lib/source/import.mjs +191 -0
- package/lib/styles/prompt.mjs +54 -0
- package/lib/styles/store.mjs +79 -0
- package/lib/typert-bind.js +28 -0
- package/locale/en.json +1 -0
- package/locale/zh-CN.json +1 -0
- package/package.json +82 -11
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { newId } from "../core/ids.mjs";
|
|
2
|
+
import { asArray, asString } from "../schema.mjs";
|
|
3
|
+
|
|
4
|
+
/** @param {string[]} list */
|
|
5
|
+
function uniq(list) {
|
|
6
|
+
return [...new Set(list.map((item) => String(item ?? "").trim()).filter(Boolean))];
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Turn a critique into two usable revision prompts: edit (keep composition)
|
|
11
|
+
* and regenerate (re-roll). Pure function.
|
|
12
|
+
* @param {{ critique: any; pack: any; mode?: "edit" | "regenerate" }} input
|
|
13
|
+
*/
|
|
14
|
+
export function buildRevision(input) {
|
|
15
|
+
const { critique, pack } = input;
|
|
16
|
+
const checks = asArray(critique.anchorChecks);
|
|
17
|
+
const keep = [];
|
|
18
|
+
const fix = [];
|
|
19
|
+
const add = [];
|
|
20
|
+
const lockedKeep = [];
|
|
21
|
+
for (const check of checks) {
|
|
22
|
+
const label = `${check.character}的${check.kind}`;
|
|
23
|
+
if (check.status === "matched") {
|
|
24
|
+
keep.push(`${label}(${check.expected})保持不变`);
|
|
25
|
+
if (check.locked) lockedKeep.push(`${label}=${check.expected}`);
|
|
26
|
+
} else if (check.status === "missing") {
|
|
27
|
+
add.push(`补上${label}:${check.expected}`);
|
|
28
|
+
} else if (check.status === "wrong") {
|
|
29
|
+
fix.push(`把${label}改成:${check.expected}`);
|
|
30
|
+
} else if (check.status === "partial") {
|
|
31
|
+
fix.push(`修正${label},向“${check.expected}”靠拢`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
for (const item of asArray(critique.keep)) keep.push(item);
|
|
35
|
+
for (const item of asArray(critique.fix)) fix.push(item);
|
|
36
|
+
for (const item of asArray(critique.add)) add.push(item);
|
|
37
|
+
const negatives = [];
|
|
38
|
+
for (const check of asArray(critique.styleChecks)) {
|
|
39
|
+
if (check.status === "bad" || check.status === "warn") negatives.push(check.note || check.kind);
|
|
40
|
+
}
|
|
41
|
+
for (const check of asArray(critique.compositionChecks)) {
|
|
42
|
+
if (check.status === "bad" || check.status === "warn") negatives.push(check.note || check.kind);
|
|
43
|
+
}
|
|
44
|
+
if (critique.overall === "unusable") negatives.push("整体不可用,建议换构图或换模型重抽");
|
|
45
|
+
const keepList = uniq(keep);
|
|
46
|
+
const fixList = uniq(fix);
|
|
47
|
+
const addList = uniq(add);
|
|
48
|
+
const negativeAdditions = uniq(negatives);
|
|
49
|
+
const delta = [
|
|
50
|
+
keepList.length ? `保留:${keepList.join(";")}` : "",
|
|
51
|
+
fixList.length ? `修改:${fixList.join(";")}` : "",
|
|
52
|
+
addList.length ? `新增:${addList.join(";")}` : "",
|
|
53
|
+
lockedKeep.length ? `不要动:${lockedKeep.join(";")}` : "",
|
|
54
|
+
]
|
|
55
|
+
.filter(Boolean)
|
|
56
|
+
.join("\n");
|
|
57
|
+
const isCover = pack.task === "cover";
|
|
58
|
+
const editPrompt = [
|
|
59
|
+
isCover ? "在保留原构图、主体位置和标题安全区的前提下修改:" : "在保留原构图和人物位置的前提下修改:",
|
|
60
|
+
delta || "只做小幅修正,不要重画整张。",
|
|
61
|
+
negativeAdditions.length ? `避免:${negativeAdditions.join(";")}` : "",
|
|
62
|
+
]
|
|
63
|
+
.filter(Boolean)
|
|
64
|
+
.join("\n");
|
|
65
|
+
const regeneratePrompt = [
|
|
66
|
+
pack.output.positive,
|
|
67
|
+
"",
|
|
68
|
+
delta ? `修正要求:\n${delta}` : "",
|
|
69
|
+
negativeAdditions.length ? `避免:${negativeAdditions.join(";")}` : "",
|
|
70
|
+
]
|
|
71
|
+
.filter(Boolean)
|
|
72
|
+
.join("\n");
|
|
73
|
+
const warnings = [];
|
|
74
|
+
if (critique.warnings?.length) warnings.push(...critique.warnings);
|
|
75
|
+
if (asArray(critique.unclear).length) warnings.push(`有看不清的项:${asArray(critique.unclear).join(";")};不要当成确定结论`);
|
|
76
|
+
if (pack.task === "cover" && asArray(critique.compositionChecks).some((check) => check.kind === "title-safe-area" && check.status !== "ok")) {
|
|
77
|
+
warnings.push("封面标题安全区有问题:优先 edit,不要直接 regenerate 把构图换掉");
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
schemaVersion: 1,
|
|
81
|
+
revisionId: newId("rev"),
|
|
82
|
+
critiqueId: critique.critiqueId ?? "",
|
|
83
|
+
packId: pack.packId,
|
|
84
|
+
mode: input.mode === "regenerate" ? "regenerate" : "edit",
|
|
85
|
+
delta,
|
|
86
|
+
editPrompt,
|
|
87
|
+
regeneratePrompt,
|
|
88
|
+
negativeAdditions,
|
|
89
|
+
keep: keepList,
|
|
90
|
+
fix: fixList,
|
|
91
|
+
add: addList,
|
|
92
|
+
target: pack.target,
|
|
93
|
+
warnings,
|
|
94
|
+
createdAt: new Date().toISOString(),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { assertImageBytes, readLimited } from "./limits.mjs";
|
|
2
|
+
import { assertComfyEndpoint, bindWorkflow, validateWorkflow } from "./workflow.mjs";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* ComfyUI HTTP adapter (0.3b skeleton). It performs real requests only when
|
|
6
|
+
* called; tests inject a fetch implementation. No workflow is bundled here.
|
|
7
|
+
*/
|
|
8
|
+
export class ComfyUIAdapter {
|
|
9
|
+
/**
|
|
10
|
+
* @param {{ endpoint: string; fetchImpl?: typeof fetch; clientId?: string }} input
|
|
11
|
+
*/
|
|
12
|
+
constructor(input) {
|
|
13
|
+
this.endpoint = assertComfyEndpoint(input.endpoint);
|
|
14
|
+
this.fetchImpl = input.fetchImpl ?? fetch;
|
|
15
|
+
this.clientId = input.clientId ?? `dsh-novel-image-${Date.now().toString(36)}`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {{ workflow: any; bindings: Record<string, any> }} input
|
|
20
|
+
*/
|
|
21
|
+
async submit(input) {
|
|
22
|
+
const workflow = validateWorkflow(bindWorkflow(input.workflow, input.bindings));
|
|
23
|
+
const response = await this.fetchImpl(`${this.endpoint}/prompt`, {
|
|
24
|
+
method: "POST",
|
|
25
|
+
headers: { "content-type": "application/json" },
|
|
26
|
+
body: JSON.stringify({ prompt: workflow, client_id: this.clientId }),
|
|
27
|
+
});
|
|
28
|
+
if (!response.ok) throw Object.assign(new Error(`ComfyUI /prompt 失败:HTTP ${response.status}`), { statusCode: response.status });
|
|
29
|
+
const data = await response.json();
|
|
30
|
+
if (!data?.prompt_id) throw new Error("ComfyUI /prompt 没有返回 prompt_id");
|
|
31
|
+
return { remoteId: String(data.prompt_id), status: "running" };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @param {string} promptId */
|
|
35
|
+
async status(promptId) {
|
|
36
|
+
const response = await this.fetchImpl(`${this.endpoint}/history/${encodeURIComponent(promptId)}`);
|
|
37
|
+
if (!response.ok) throw new Error(`ComfyUI /history 失败:HTTP ${response.status}`);
|
|
38
|
+
const data = await response.json();
|
|
39
|
+
const history = data?.[promptId];
|
|
40
|
+
if (!history) return { status: "running" };
|
|
41
|
+
const remoteStatus = String(history.status?.status_str ?? "").toLowerCase();
|
|
42
|
+
if (remoteStatus === "error" || remoteStatus === "failed") {
|
|
43
|
+
const message = JSON.stringify(history.status?.messages ?? "").slice(0, 500);
|
|
44
|
+
return { status: "failed", error: `ComfyUI 执行失败:${message}` };
|
|
45
|
+
}
|
|
46
|
+
const images = [];
|
|
47
|
+
for (const output of Object.values(history.outputs ?? {})) {
|
|
48
|
+
for (const image of output?.images ?? []) images.push(image);
|
|
49
|
+
}
|
|
50
|
+
if (!images.length) return { status: history.status?.completed === true ? "failed" : "running" };
|
|
51
|
+
return { status: "succeeded", images };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** @param {any} image {filename, subfolder, type} */
|
|
55
|
+
async download(image) {
|
|
56
|
+
const params = new URLSearchParams({
|
|
57
|
+
filename: String(image.filename ?? ""),
|
|
58
|
+
subfolder: String(image.subfolder ?? ""),
|
|
59
|
+
type: String(image.type ?? "output"),
|
|
60
|
+
});
|
|
61
|
+
const response = await this.fetchImpl(`${this.endpoint}/view?${params.toString()}`);
|
|
62
|
+
if (!response.ok) throw new Error(`ComfyUI /view 失败:HTTP ${response.status}`);
|
|
63
|
+
const contentType = response.headers.get("content-type") ?? "image/png";
|
|
64
|
+
const mime = contentType.split(";")[0];
|
|
65
|
+
if (!mime.startsWith("image/")) throw new Error(`ComfyUI /view 返回非图片类型:${mime}`);
|
|
66
|
+
const buffer = await readLimited(response);
|
|
67
|
+
assertImageBytes(buffer, mime);
|
|
68
|
+
return { mime, data: buffer };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Upload a reference image and return the filename ComfyUI expects in LoadImage. */
|
|
72
|
+
async uploadImage(input) {
|
|
73
|
+
const form = new FormData();
|
|
74
|
+
form.append("image", new Blob([input.data], { type: input.mime || "image/png" }), input.filename || "reference.png");
|
|
75
|
+
form.append("overwrite", "true");
|
|
76
|
+
const response = await this.fetchImpl(`${this.endpoint}/upload/image`, { method: "POST", body: form });
|
|
77
|
+
if (!response.ok) throw new Error(`ComfyUI /upload/image 失败:HTTP ${response.status}`);
|
|
78
|
+
const data = await response.json();
|
|
79
|
+
if (!data?.name) throw new Error("ComfyUI /upload/image 没有返回 name");
|
|
80
|
+
return String(data.name);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async test() {
|
|
84
|
+
const response = await this.fetchImpl(`${this.endpoint}/system_stats`);
|
|
85
|
+
return {
|
|
86
|
+
ok: response.ok,
|
|
87
|
+
statusCode: response.status,
|
|
88
|
+
detail: response.ok ? "system_stats 可访问" : `HTTP ${response.status}`,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async cancel() {
|
|
93
|
+
return { cancelled: false };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compare a persisted work's chapter hashes with a new manuscript.
|
|
3
|
+
* Pure function; no filesystem.
|
|
4
|
+
* @param {{ chapters: any[] }} work
|
|
5
|
+
* @param {any[]} nextChapters
|
|
6
|
+
*/
|
|
7
|
+
export function planIncremental(work, nextChapters) {
|
|
8
|
+
const before = new Map((work.chapters ?? []).map((chapter) => [chapter.index, chapter]));
|
|
9
|
+
const after = new Map((nextChapters ?? []).map((chapter) => [chapter.index, chapter]));
|
|
10
|
+
const added = [];
|
|
11
|
+
const modified = [];
|
|
12
|
+
const removed = [];
|
|
13
|
+
for (const [index, chapter] of after) {
|
|
14
|
+
const previous = before.get(index);
|
|
15
|
+
if (!previous) added.push({ chapterId: chapter.chapterId, index, hash: chapter.hash });
|
|
16
|
+
else if (previous.hash !== chapter.hash) {
|
|
17
|
+
modified.push({
|
|
18
|
+
chapterId: chapter.chapterId,
|
|
19
|
+
index,
|
|
20
|
+
oldHash: previous.hash,
|
|
21
|
+
newHash: chapter.hash,
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
for (const [index, chapter] of before) {
|
|
26
|
+
if (!after.has(index)) removed.push({ chapterId: chapter.chapterId, index, hash: chapter.hash });
|
|
27
|
+
}
|
|
28
|
+
return {
|
|
29
|
+
changed: [...added, ...modified, ...removed],
|
|
30
|
+
added,
|
|
31
|
+
modified,
|
|
32
|
+
removed,
|
|
33
|
+
changedCount: added.length + modified.length + removed.length,
|
|
34
|
+
staleCanon: added.length + modified.length + removed.length > 0,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
const MAX_IMAGE_BYTES = 20 * 1024 * 1024;
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Read a response body with a hard byte cap. Checks Content-Length first, then
|
|
5
|
+
* streams when available; falls back to arrayBuffer for simple/mock responses.
|
|
6
|
+
* @param {Response} response
|
|
7
|
+
* @param {number} max
|
|
8
|
+
*/
|
|
9
|
+
export async function readLimited(response, max = MAX_IMAGE_BYTES) {
|
|
10
|
+
const declared = Number(response.headers?.get?.("content-length") ?? 0);
|
|
11
|
+
if (declared > max) throw new Error(`图片响应超过 ${max} 字节上限`);
|
|
12
|
+
if (response.body?.getReader) {
|
|
13
|
+
const reader = response.body.getReader();
|
|
14
|
+
const chunks = [];
|
|
15
|
+
let total = 0;
|
|
16
|
+
while (true) {
|
|
17
|
+
const { done, value } = await reader.read();
|
|
18
|
+
if (done) break;
|
|
19
|
+
total += value.byteLength;
|
|
20
|
+
if (total > max) {
|
|
21
|
+
await reader.cancel().catch(() => {});
|
|
22
|
+
throw new Error(`图片响应超过 ${max} 字节上限`);
|
|
23
|
+
}
|
|
24
|
+
chunks.push(Buffer.from(value));
|
|
25
|
+
}
|
|
26
|
+
return Buffer.concat(chunks);
|
|
27
|
+
}
|
|
28
|
+
const buffer = Buffer.from(await response.arrayBuffer());
|
|
29
|
+
if (buffer.byteLength > max) throw new Error(`图片响应超过 ${max} 字节上限`);
|
|
30
|
+
return buffer;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** @param {Buffer} buffer @param {string} mime */
|
|
34
|
+
export function assertImageBytes(buffer, mime) {
|
|
35
|
+
const png = buffer.length >= 8 && buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47;
|
|
36
|
+
const jpeg = buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff;
|
|
37
|
+
const gif = buffer.length >= 4 && buffer.subarray(0, 4).toString("ascii") === "GIF8";
|
|
38
|
+
const webp = buffer.length >= 12 && buffer.subarray(0, 4).toString("ascii") === "RIFF" && buffer.subarray(8, 12).toString("ascii") === "WEBP";
|
|
39
|
+
if (!png && !jpeg && !gif && !webp) throw new Error(`图片内容不是 PNG/JPEG/GIF/WebP(声明 ${mime || "unknown"})`);
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export { MAX_IMAGE_BYTES };
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const MOCK_PNG = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAFZSURBVHhe7dIxDsMwDEPR3qhHyN77j71G5hYZAnT4sKVYcoyKw1sINKKJPp6v7VOZBqCwEg1AYSUagMJKNACFlWgACivRABRWMnWAfX+b0e8zpA9Aj/Oi70ZJG4AeMorujEoZgMpHoXsjQgegwlno/hVhA1DJbNTDK2QAKjcL9fHQABR6UKnZqJfV0ABU5i7Uz0IDUGhBJe5GPXs0AIUWVOBu1LPn0gB0fBXUt0UDUNhDh1dBfVs0AIU9dHgV1LfFPQAdXQl1btE/gMIeOrwK6tuiASjsocOroL4tGoBCCzq+Aura8lcDUM8eDUChFZW4C/Wz0AAUelCZ2aiX1fAAByo1C/Xx0AAUXkHlslEPr7ABDlQyC92/InSAExWOQvdGpAxwoPKj6M6otAFO9BAv+m6U9AF+0eNa6BvRpg6wIg1AYSUagMJKNACFlWgACivRABRWUnyA7fMF5Cpl/LHpTtgAAAAASUVORK5CYII=";
|
|
2
|
+
|
|
3
|
+
export class MockAdapter {
|
|
4
|
+
id = "mock";
|
|
5
|
+
kind = "mock";
|
|
6
|
+
|
|
7
|
+
async submit() {
|
|
8
|
+
return {
|
|
9
|
+
remoteId: `mock-${Date.now().toString(36)}`,
|
|
10
|
+
mime: "image/png",
|
|
11
|
+
data: Buffer.from(MOCK_PNG, "base64"),
|
|
12
|
+
note: "0.3a mock:没有网络、没有真实模型",
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async cancel() {
|
|
17
|
+
return { cancelled: true };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async test() {
|
|
21
|
+
return { ok: true, statusCode: 0, detail: "mock 无需网络" };
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function createMockAdapter() {
|
|
26
|
+
return new MockAdapter();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export { MOCK_PNG };
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { assertImageBytes, readLimited } from "./limits.mjs";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* API-returned image URLs must be public https. This blocks the obvious SSRF
|
|
5
|
+
* cases; it is not a substitute for a full network egress policy.
|
|
6
|
+
* @param {string} raw
|
|
7
|
+
*/
|
|
8
|
+
function safeImageUrl(raw) {
|
|
9
|
+
const url = new URL(String(raw));
|
|
10
|
+
if (url.protocol !== "https:") throw new Error("图像 URL 只允许 https");
|
|
11
|
+
const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
|
12
|
+
if (host === "localhost" || host.endsWith(".local") || host === "0.0.0.0" || host === "::1" || host === "0:0:0:0:0:0:0:1") {
|
|
13
|
+
throw new Error("图像 URL 不能指向本机/局域网");
|
|
14
|
+
}
|
|
15
|
+
if (/^(10\.|127\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(host)) {
|
|
16
|
+
throw new Error("图像 URL 不能指向私网");
|
|
17
|
+
}
|
|
18
|
+
const mapped = host.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
|
|
19
|
+
if (mapped && /^(10\.|127\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(mapped[1])) {
|
|
20
|
+
throw new Error("图像 URL 不能指向私网");
|
|
21
|
+
}
|
|
22
|
+
if (host.startsWith("fe80:") || host.startsWith("fc") || host.startsWith("fd")) {
|
|
23
|
+
throw new Error("图像 URL 不能指向链路本地/唯一本地地址");
|
|
24
|
+
}
|
|
25
|
+
return url.toString();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* OpenAI-compatible image adapter (0.4: generation + edits). The API key is
|
|
30
|
+
* supplied at call time and must never be persisted by this module.
|
|
31
|
+
*/
|
|
32
|
+
export class OpenAICompatibleAdapter {
|
|
33
|
+
/**
|
|
34
|
+
* @param {{ endpoint: string; model: string; fetchImpl?: typeof fetch }} input
|
|
35
|
+
*/
|
|
36
|
+
constructor(input) {
|
|
37
|
+
this.endpoint = String(input.endpoint).replace(/\/+$/, "");
|
|
38
|
+
if (!/^https:\/\//.test(this.endpoint) && !/^http:\/\/(127\.0\.0\.1|localhost)(:|\/|$)/.test(this.endpoint)) {
|
|
39
|
+
throw new Error("OpenAI 兼容 endpoint 必须是 https,或显式 localhost");
|
|
40
|
+
}
|
|
41
|
+
this.model = String(input.model ?? "");
|
|
42
|
+
this.fetchImpl = input.fetchImpl ?? fetch;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async decode(data) {
|
|
46
|
+
const item = data?.data?.[0];
|
|
47
|
+
if (!item) throw new Error("图像 API 没有返回 data[0]");
|
|
48
|
+
if (item.b64_json) {
|
|
49
|
+
const buffer = Buffer.from(item.b64_json, "base64");
|
|
50
|
+
if (buffer.byteLength > 20 * 1024 * 1024) throw new Error("API base64 图片超过 20MB");
|
|
51
|
+
assertImageBytes(buffer, "image/png");
|
|
52
|
+
return { remoteId: "", mime: "image/png", data: buffer };
|
|
53
|
+
}
|
|
54
|
+
if (item.url) {
|
|
55
|
+
const image = await this.fetchPublicImage(item.url);
|
|
56
|
+
if (!image.ok) throw new Error(`图像下载失败:HTTP ${image.status}`);
|
|
57
|
+
const mime = (image.headers.get("content-type") ?? "image/png").split(";")[0];
|
|
58
|
+
if (!mime.startsWith("image/")) throw new Error(`图像下载返回非图片类型:${mime}`);
|
|
59
|
+
const buffer = await readLimited(image);
|
|
60
|
+
assertImageBytes(buffer, mime);
|
|
61
|
+
return { remoteId: "", mime, data: buffer };
|
|
62
|
+
}
|
|
63
|
+
throw new Error("图像 API 返回既没有 b64_json 也没有 url");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Follow redirects manually so every hop is checked by safeImageUrl.
|
|
68
|
+
* @param {string} raw
|
|
69
|
+
*/
|
|
70
|
+
async fetchPublicImage(raw) {
|
|
71
|
+
let url = safeImageUrl(raw);
|
|
72
|
+
for (let hop = 0; hop < 3; hop += 1) {
|
|
73
|
+
const response = await this.fetchImpl(url, { redirect: "manual" });
|
|
74
|
+
if (response.status >= 300 && response.status < 400) {
|
|
75
|
+
const location = response.headers?.get?.("location");
|
|
76
|
+
if (!location) throw new Error("图像下载重定向缺少 Location");
|
|
77
|
+
url = safeImageUrl(new URL(location, url).toString());
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
return response;
|
|
81
|
+
}
|
|
82
|
+
throw new Error("图像下载重定向次数过多");
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* @param {{ prompt: string; size?: string; n?: number; apiKey: string }} input
|
|
87
|
+
*/
|
|
88
|
+
async submit(input) {
|
|
89
|
+
if (!input.apiKey) throw new Error("缺少 API Key");
|
|
90
|
+
const response = await this.fetchImpl(`${this.endpoint}/v1/images/generations`, {
|
|
91
|
+
method: "POST",
|
|
92
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${input.apiKey}` },
|
|
93
|
+
body: JSON.stringify({
|
|
94
|
+
model: this.model,
|
|
95
|
+
prompt: input.prompt,
|
|
96
|
+
size: input.size ?? "1024x1024",
|
|
97
|
+
n: Math.max(1, Math.min(4, Number(input.n ?? 1))),
|
|
98
|
+
response_format: "b64_json",
|
|
99
|
+
}),
|
|
100
|
+
});
|
|
101
|
+
if (!response.ok) throw Object.assign(new Error(`图像 API 失败:HTTP ${response.status}`), { statusCode: response.status });
|
|
102
|
+
return this.decode(await response.json());
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Image edit / reference-guided generation (multipart /v1/images/edits).
|
|
107
|
+
* @param {{ prompt: string; image: { data: Buffer; mime: string; filename?: string }; size?: string; n?: number; apiKey: string }} input
|
|
108
|
+
*/
|
|
109
|
+
async edit(input) {
|
|
110
|
+
if (!input.apiKey) throw new Error("缺少 API Key");
|
|
111
|
+
const form = new FormData();
|
|
112
|
+
form.append("model", this.model);
|
|
113
|
+
form.append("prompt", input.prompt);
|
|
114
|
+
form.append("image", new Blob([input.image.data], { type: input.image.mime || "image/png" }), input.image.filename || "reference.png");
|
|
115
|
+
form.append("size", input.size ?? "1024x1024");
|
|
116
|
+
form.append("n", String(Math.max(1, Math.min(4, Number(input.n ?? 1)))));
|
|
117
|
+
form.append("response_format", "b64_json");
|
|
118
|
+
const response = await this.fetchImpl(`${this.endpoint}/v1/images/edits`, {
|
|
119
|
+
method: "POST",
|
|
120
|
+
headers: { authorization: `Bearer ${input.apiKey}` },
|
|
121
|
+
body: form,
|
|
122
|
+
});
|
|
123
|
+
if (!response.ok) throw Object.assign(new Error(`图像编辑 API 失败:HTTP ${response.status}`), { statusCode: response.status });
|
|
124
|
+
return this.decode(await response.json());
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async test(apiKey) {
|
|
128
|
+
if (!apiKey) throw new Error("缺少 API Key");
|
|
129
|
+
const response = await this.fetchImpl(`${this.endpoint}/v1/models`, {
|
|
130
|
+
headers: { authorization: `Bearer ${apiKey}` },
|
|
131
|
+
});
|
|
132
|
+
return { ok: response.ok, statusCode: response.status, detail: response.ok ? "models 可访问" : `HTTP ${response.status}` };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async cancel() {
|
|
136
|
+
return { cancelled: false };
|
|
137
|
+
}
|
|
138
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const TRANSITIONS = Object.freeze({
|
|
2
|
+
queued: ["submitting", "cancelled"],
|
|
3
|
+
submitting: ["running", "failed", "unknown", "cancelled"],
|
|
4
|
+
running: ["succeeded", "failed", "cancelled", "cancel-requested"],
|
|
5
|
+
"cancel-requested": ["cancelled", "stopped-local", "failed"],
|
|
6
|
+
unknown: ["reconciling", "failed"],
|
|
7
|
+
reconciling: ["running", "failed", "unknown"],
|
|
8
|
+
succeeded: [],
|
|
9
|
+
failed: [],
|
|
10
|
+
cancelled: [],
|
|
11
|
+
"stopped-local": [],
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
/** @param {string} from @param {string} to */
|
|
15
|
+
export function canTransition(from, to) {
|
|
16
|
+
return (TRANSITIONS[from] ?? []).includes(to);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** @param {string} from @param {string} to */
|
|
20
|
+
export function assertTransition(from, to) {
|
|
21
|
+
if (!canTransition(from, to)) throw new Error(`非法任务状态转换:${from} → ${to}`);
|
|
22
|
+
return to;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function isTerminal(status) {
|
|
26
|
+
return ["succeeded", "failed", "cancelled", "stopped-local"].includes(status);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export { TRANSITIONS };
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import { fail } from "../core/errors.mjs";
|
|
3
|
+
import { newId } from "../core/ids.mjs";
|
|
4
|
+
import { ensureDir, readJson, resolveInside, writeJsonAtomic } from "../core/storage.mjs";
|
|
5
|
+
import { assertTransition } from "./state.mjs";
|
|
6
|
+
|
|
7
|
+
/** @param {string} root */
|
|
8
|
+
function providersDir(root) {
|
|
9
|
+
return resolveInside(root, "profiles", "providers");
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** @param {string} root @param {string} providerId */
|
|
13
|
+
function providerFile(root, providerId) {
|
|
14
|
+
return resolveInside(providersDir(root), `${providerId}.json`);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** @param {string} root @param {string} workId */
|
|
18
|
+
function jobsDir(root, workId) {
|
|
19
|
+
return resolveInside(root, "works", workId, "jobs");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** @param {string} root @param {string} workId @param {string} jobId */
|
|
23
|
+
function jobFile(root, workId, jobId) {
|
|
24
|
+
return resolveInside(jobsDir(root, workId), `${jobId}.json`);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** @param {string} root */
|
|
28
|
+
export async function listProviders(root) {
|
|
29
|
+
const dir = providersDir(root);
|
|
30
|
+
let files = [];
|
|
31
|
+
try {
|
|
32
|
+
files = await fs.readdir(dir);
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (error?.code === "ENOENT") return [];
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
const providers = [];
|
|
38
|
+
for (const name of files) {
|
|
39
|
+
if (!name.endsWith(".json")) continue;
|
|
40
|
+
const record = await readJson(resolveInside(dir, name), null);
|
|
41
|
+
if (record) providers.push(record);
|
|
42
|
+
}
|
|
43
|
+
return providers;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** @param {string} root @param {string} providerId */
|
|
47
|
+
export async function getProvider(root, providerId) {
|
|
48
|
+
if (providerId === "mock") {
|
|
49
|
+
return {
|
|
50
|
+
profileId: "mock",
|
|
51
|
+
label: "Mock(0.3a 测试,无网络)",
|
|
52
|
+
kind: "mock",
|
|
53
|
+
endpoint: "",
|
|
54
|
+
model: "mock",
|
|
55
|
+
capabilities: { negative: true, referenceImages: 0, seed: true, widthHeight: true, edit: false },
|
|
56
|
+
maxAttempts: 1,
|
|
57
|
+
retryDelayMs: 0,
|
|
58
|
+
minIntervalMs: 0,
|
|
59
|
+
status: "verified",
|
|
60
|
+
lastVerified: "2026-11-28",
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
const record = await readJson(providerFile(root, providerId), null);
|
|
64
|
+
if (!record) fail("provider-not-found", `生图 provider 不存在:${providerId}`);
|
|
65
|
+
return record;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** @param {string} root @param {any} input */
|
|
69
|
+
export async function saveProvider(root, input) {
|
|
70
|
+
const providerId = String(input.profileId ?? "").trim() || newId("prov");
|
|
71
|
+
if (!["mock", "comfyui", "openai-compatible", "manual"].includes(input.kind)) fail("bad-provider", "provider kind 不合法");
|
|
72
|
+
const record = {
|
|
73
|
+
schemaVersion: 1,
|
|
74
|
+
profileId: providerId,
|
|
75
|
+
label: String(input.label ?? providerId).slice(0, 80),
|
|
76
|
+
kind: input.kind,
|
|
77
|
+
endpoint: String(input.endpoint ?? "").slice(0, 500),
|
|
78
|
+
credentialRef: String(input.credentialRef ?? "").slice(0, 200),
|
|
79
|
+
model: String(input.model ?? "").slice(0, 120),
|
|
80
|
+
workflowId: String(input.workflowId ?? "").slice(0, 120),
|
|
81
|
+
capabilities: {
|
|
82
|
+
negative: input.capabilities?.negative !== false,
|
|
83
|
+
referenceImages: Math.max(0, Math.min(8, Number(input.capabilities?.referenceImages ?? 0))),
|
|
84
|
+
seed: input.capabilities?.seed !== false,
|
|
85
|
+
widthHeight: input.capabilities?.widthHeight !== false,
|
|
86
|
+
edit: input.capabilities?.edit === true,
|
|
87
|
+
},
|
|
88
|
+
maxAttempts: Math.max(1, Math.min(5, Number(input.maxAttempts ?? 1))),
|
|
89
|
+
retryDelayMs: Math.max(0, Math.min(30000, Number(input.retryDelayMs ?? 800))),
|
|
90
|
+
minIntervalMs: Math.max(0, Math.min(60000, Number(input.minIntervalMs ?? 0))),
|
|
91
|
+
status: "unverified",
|
|
92
|
+
lastVerified: "",
|
|
93
|
+
createdAt: String(input.createdAt ?? new Date().toISOString()),
|
|
94
|
+
};
|
|
95
|
+
await ensureDir(providersDir(root));
|
|
96
|
+
await writeJsonAtomic(providerFile(root, providerId), record);
|
|
97
|
+
return record;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** @param {string} root @param {string} workId @param {string} packId @param {string} providerId */
|
|
101
|
+
export async function findJobByKey(root, workId, idempotencyKey) {
|
|
102
|
+
const jobs = await listJobs(root, workId);
|
|
103
|
+
return jobs.find(
|
|
104
|
+
(job) => job.idempotencyKey === idempotencyKey && !["failed", "cancelled", "stopped-local"].includes(job.status),
|
|
105
|
+
) ?? null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** @param {string} root @param {any} job */
|
|
109
|
+
export async function createJob(root, job) {
|
|
110
|
+
const dir = jobsDir(root, job.workId);
|
|
111
|
+
await ensureDir(dir);
|
|
112
|
+
const record = {
|
|
113
|
+
schemaVersion: 1,
|
|
114
|
+
jobId: newId("job"),
|
|
115
|
+
status: "queued",
|
|
116
|
+
events: [],
|
|
117
|
+
attempts: 1,
|
|
118
|
+
createdAt: new Date().toISOString(),
|
|
119
|
+
updatedAt: new Date().toISOString(),
|
|
120
|
+
...job,
|
|
121
|
+
};
|
|
122
|
+
await writeJsonAtomic(jobFile(root, job.workId, record.jobId), record);
|
|
123
|
+
return record;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** @param {string} root @param {string} workId @param {string} jobId */
|
|
127
|
+
export async function getJob(root, workId, jobId) {
|
|
128
|
+
const record = await readJson(jobFile(root, workId, jobId), null);
|
|
129
|
+
if (!record) fail("job-not-found", `任务不存在:${jobId}`);
|
|
130
|
+
return record;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** @param {string} root @param {string} workId */
|
|
134
|
+
export async function listJobs(root, workId) {
|
|
135
|
+
const dir = jobsDir(root, workId);
|
|
136
|
+
let files = [];
|
|
137
|
+
try {
|
|
138
|
+
files = await fs.readdir(dir);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
if (error?.code === "ENOENT") return [];
|
|
141
|
+
throw error;
|
|
142
|
+
}
|
|
143
|
+
const jobs = [];
|
|
144
|
+
for (const name of files) {
|
|
145
|
+
if (!name.endsWith(".json")) continue;
|
|
146
|
+
const record = await readJson(resolveInside(dir, name), null);
|
|
147
|
+
if (record) jobs.push(record);
|
|
148
|
+
}
|
|
149
|
+
return jobs.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** @param {string} root @param {string} workId @param {string} jobId @param {string} status @param {any} patch */
|
|
153
|
+
export async function updateJob(root, workId, jobId, status, patch = {}) {
|
|
154
|
+
const current = await getJob(root, workId, jobId);
|
|
155
|
+
assertTransition(current.status, status);
|
|
156
|
+
const now = new Date().toISOString();
|
|
157
|
+
const next = {
|
|
158
|
+
...current,
|
|
159
|
+
...patch,
|
|
160
|
+
status,
|
|
161
|
+
updatedAt: now,
|
|
162
|
+
...(status === "succeeded" || status === "failed" || status === "cancelled" || status === "stopped-local" ? { finishedAt: now } : {}),
|
|
163
|
+
events: [
|
|
164
|
+
...(current.events ?? []),
|
|
165
|
+
{ at: now, status, ...(patch.errorCode ? { errorCode: patch.errorCode } : {}), ...(patch.note ? { note: patch.note } : {}) },
|
|
166
|
+
],
|
|
167
|
+
};
|
|
168
|
+
await writeJsonAtomic(jobFile(root, workId, jobId), next);
|
|
169
|
+
return next;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Append an audit event without changing the job status (e.g. retry). */
|
|
173
|
+
export async function appendJobEvent(root, workId, jobId, event, patch = {}) {
|
|
174
|
+
const current = await getJob(root, workId, jobId);
|
|
175
|
+
const now = new Date().toISOString();
|
|
176
|
+
const next = {
|
|
177
|
+
...current,
|
|
178
|
+
...patch,
|
|
179
|
+
updatedAt: now,
|
|
180
|
+
events: [...(current.events ?? []), { at: now, ...event }],
|
|
181
|
+
};
|
|
182
|
+
await writeJsonAtomic(jobFile(root, workId, jobId), next);
|
|
183
|
+
return next;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export { jobFile };
|