@pixerate/editor 0.22.0 → 0.24.0
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/README.md +175 -2
- package/THIRD_PARTY_NOTICES.md +139 -0
- package/dist/agent/index.cjs +87 -111
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +70 -211
- package/dist/agent/index.d.ts +70 -211
- package/dist/agent/index.js +78 -102
- package/dist/agent/index.js.map +1 -1
- package/dist/arrangeShortcuts-B8O3f8-P.d.cts +184 -0
- package/dist/arrangeShortcuts-sLlD2rSX.d.ts +184 -0
- package/dist/canvas/index.cjs +2075 -86
- package/dist/canvas/index.cjs.map +1 -1
- package/dist/canvas/index.d.cts +608 -186
- package/dist/canvas/index.d.ts +608 -186
- package/dist/canvas/index.js +2060 -71
- package/dist/canvas/index.js.map +1 -1
- package/dist/chunk-26BVFKHU.cjs +453 -0
- package/dist/chunk-26BVFKHU.cjs.map +1 -0
- package/dist/chunk-2H7ZHPEJ.js +762 -0
- package/dist/chunk-2H7ZHPEJ.js.map +1 -0
- package/dist/{chunk-DENSCKFC.js → chunk-3CN2WD3X.js} +1730 -189
- package/dist/chunk-3CN2WD3X.js.map +1 -0
- package/dist/{chunk-JJDLPEWL.js → chunk-3LV6RRPH.js} +2 -2
- package/dist/{chunk-MJZBNWG7.js → chunk-5S3Z4PPF.js} +78 -557
- package/dist/chunk-5S3Z4PPF.js.map +1 -0
- package/dist/chunk-664LQYFJ.js +115 -0
- package/dist/chunk-664LQYFJ.js.map +1 -0
- package/dist/chunk-7DWMJCAT.js +453 -0
- package/dist/chunk-7DWMJCAT.js.map +1 -0
- package/dist/chunk-ARRTP33I.js +101 -0
- package/dist/chunk-ARRTP33I.js.map +1 -0
- package/dist/chunk-CPOKFNBG.cjs +101 -0
- package/dist/chunk-CPOKFNBG.cjs.map +1 -0
- package/dist/{chunk-AA4ZEVCC.cjs → chunk-D27YFC46.cjs} +101 -580
- package/dist/chunk-D27YFC46.cjs.map +1 -0
- package/dist/chunk-D6FH2YAX.cjs +131 -0
- package/dist/chunk-D6FH2YAX.cjs.map +1 -0
- package/dist/{chunk-4SUNJZWB.cjs → chunk-FD4LPFAE.cjs} +48 -200
- package/dist/chunk-FD4LPFAE.cjs.map +1 -0
- package/dist/chunk-FODNLX5N.js +749 -0
- package/dist/chunk-FODNLX5N.js.map +1 -0
- package/dist/{chunk-OYXSKQFR.js → chunk-FPENXAEJ.js} +35 -187
- package/dist/chunk-FPENXAEJ.js.map +1 -0
- package/dist/chunk-G2I4QJOT.cjs +762 -0
- package/dist/chunk-G2I4QJOT.cjs.map +1 -0
- package/dist/chunk-HLIMTC6N.js +1 -0
- package/dist/chunk-HLIMTC6N.js.map +1 -0
- package/dist/{chunk-QGHGJ56O.js → chunk-ITBSKI26.js} +1483 -19
- package/dist/chunk-ITBSKI26.js.map +1 -0
- package/dist/{chunk-6M3BCTBD.cjs → chunk-MA2F5KHF.cjs} +470 -242
- package/dist/chunk-MA2F5KHF.cjs.map +1 -0
- package/dist/{chunk-SAZRENEZ.cjs → chunk-MCSJFWAO.cjs} +1733 -192
- package/dist/chunk-MCSJFWAO.cjs.map +1 -0
- package/dist/chunk-MKA3AHLV.cjs +256 -0
- package/dist/chunk-MKA3AHLV.cjs.map +1 -0
- package/dist/chunk-OLZJXL4R.cjs +749 -0
- package/dist/chunk-OLZJXL4R.cjs.map +1 -0
- package/dist/chunk-OXSV64JX.js +689 -0
- package/dist/chunk-OXSV64JX.js.map +1 -0
- package/dist/chunk-P3RQ5UJE.cjs +689 -0
- package/dist/chunk-P3RQ5UJE.cjs.map +1 -0
- package/dist/chunk-P6ODPZ4W.js +256 -0
- package/dist/chunk-P6ODPZ4W.js.map +1 -0
- package/dist/chunk-PGNZKFQS.js +685 -0
- package/dist/chunk-PGNZKFQS.js.map +1 -0
- package/dist/chunk-PL4JB3BF.cjs +1 -0
- package/dist/chunk-PL4JB3BF.cjs.map +1 -0
- package/dist/{chunk-GVSMRPHB.cjs → chunk-SBCZ6RN5.cjs} +1568 -104
- package/dist/chunk-SBCZ6RN5.cjs.map +1 -0
- package/dist/{chunk-CL37JGFW.cjs → chunk-SML64VJG.cjs} +4 -4
- package/dist/{chunk-CL37JGFW.cjs.map → chunk-SML64VJG.cjs.map} +1 -1
- package/dist/chunk-TNNJXF46.cjs +115 -0
- package/dist/chunk-TNNJXF46.cjs.map +1 -0
- package/dist/chunk-U5HZSFCS.js +131 -0
- package/dist/chunk-U5HZSFCS.js.map +1 -0
- package/dist/{chunk-RU52I7QO.js → chunk-U5KWZU4X.js} +388 -160
- package/dist/chunk-U5KWZU4X.js.map +1 -0
- package/dist/chunk-XNORY7M6.cjs +685 -0
- package/dist/chunk-XNORY7M6.cjs.map +1 -0
- package/dist/commands/index.cjs +860 -0
- package/dist/commands/index.cjs.map +1 -0
- package/dist/commands/index.d.cts +244 -0
- package/dist/commands/index.d.ts +244 -0
- package/dist/commands/index.js +860 -0
- package/dist/commands/index.js.map +1 -0
- package/dist/comment-store-BEMgVlAA.d.cts +135 -0
- package/dist/comment-store-BEMgVlAA.d.ts +135 -0
- package/dist/compare/index.cjs +15 -0
- package/dist/compare/index.cjs.map +1 -0
- package/dist/compare/index.d.cts +58 -0
- package/dist/compare/index.d.ts +58 -0
- package/dist/compare/index.js +15 -0
- package/dist/compare/index.js.map +1 -0
- package/dist/{controller-B7GIybc4.d.cts → controller-BhLLAoi8.d.cts} +119 -5
- package/dist/{controller-B7GIybc4.d.ts → controller-BhLLAoi8.d.ts} +119 -5
- package/dist/documents-BQjzJNe2.d.ts +76 -0
- package/dist/documents-KRTPhvst.d.cts +76 -0
- package/dist/extensions/index.cjs +53 -5
- package/dist/extensions/index.cjs.map +1 -1
- package/dist/extensions/index.d.cts +7 -3
- package/dist/extensions/index.d.ts +7 -3
- package/dist/extensions/index.js +52 -4
- package/dist/generation/index.cjs +1373 -0
- package/dist/generation/index.cjs.map +1 -0
- package/dist/generation/index.d.cts +554 -0
- package/dist/generation/index.d.ts +554 -0
- package/dist/generation/index.js +1373 -0
- package/dist/generation/index.js.map +1 -0
- package/dist/grammar/index.cjs +48 -3
- package/dist/grammar/index.cjs.map +1 -1
- package/dist/grammar/index.d.cts +322 -100
- package/dist/grammar/index.d.ts +322 -100
- package/dist/grammar/index.js +54 -9
- package/dist/history/index.cjs +12 -2
- package/dist/history/index.cjs.map +1 -1
- package/dist/history/index.d.cts +211 -7
- package/dist/history/index.d.ts +211 -7
- package/dist/history/index.js +13 -3
- package/dist/image-editor/index.cjs +2244 -38
- package/dist/image-editor/index.cjs.map +1 -1
- package/dist/image-editor/index.d.cts +742 -4
- package/dist/image-editor/index.d.ts +742 -4
- package/dist/image-editor/index.js +2222 -16
- package/dist/image-editor/index.js.map +1 -1
- package/dist/{index-CCr_z9kF.d.cts → index-BhJBSm2d.d.cts} +370 -4
- package/dist/{index-Ck6ajwXh.d.ts → index-fJrlkJCd.d.ts} +370 -4
- package/dist/index.cjs +193 -98
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -48
- package/dist/index.d.ts +17 -48
- package/dist/index.js +198 -103
- package/dist/index.js.map +1 -1
- package/dist/migrate-iTlm3a8h.d.cts +112 -0
- package/dist/migrate-iTlm3a8h.d.ts +112 -0
- package/dist/persistence/index.cjs +676 -0
- package/dist/persistence/index.cjs.map +1 -0
- package/dist/persistence/index.d.cts +347 -0
- package/dist/persistence/index.d.ts +347 -0
- package/dist/persistence/index.js +676 -0
- package/dist/persistence/index.js.map +1 -0
- package/dist/registry-BDe-vlv3.d.ts +171 -0
- package/dist/registry-D32LpIc4.d.cts +354 -0
- package/dist/registry-DnzpgY27.d.cts +171 -0
- package/dist/registry-evKTP4ls.d.ts +354 -0
- package/dist/schema-DYDGdYL9.d.cts +41 -0
- package/dist/schema-DYDGdYL9.d.ts +41 -0
- package/dist/serializers/index.cjs +4 -3
- package/dist/serializers/index.cjs.map +1 -1
- package/dist/serializers/index.d.cts +2 -1
- package/dist/serializers/index.d.ts +2 -1
- package/dist/serializers/index.js +3 -2
- package/dist/sourcemap-C8AH3MBQ.d.cts +91 -0
- package/dist/sourcemap-DA1Evhrv.d.ts +91 -0
- package/dist/spreadsheet/index.cjs +53 -3
- package/dist/spreadsheet/index.cjs.map +1 -1
- package/dist/spreadsheet/index.d.cts +247 -18
- package/dist/spreadsheet/index.d.ts +247 -18
- package/dist/spreadsheet/index.js +58 -8
- package/dist/{tokens-CyLZmIei.d.cts → tokens-D7yXvUU6.d.cts} +15 -2
- package/dist/{tokens-CyLZmIei.d.ts → tokens-D7yXvUU6.d.ts} +15 -2
- package/dist/{track-changes-BSF58RK0.d.cts → track-changes-BK5sVf4_.d.cts} +18 -136
- package/dist/{track-changes-BSF58RK0.d.ts → track-changes-CDjCrwKe.d.ts} +18 -136
- package/dist/{types-CJ4U-HHI.d.ts → types-DX4Mh4SL.d.cts} +1 -1
- package/dist/{types-CJ4U-HHI.d.cts → types-DX4Mh4SL.d.ts} +1 -1
- package/dist/types-GT5a5YAX.d.cts +86 -0
- package/dist/types-GT5a5YAX.d.ts +86 -0
- package/package.json +23 -2
- package/dist/chunk-2TWGLC5K.cjs +0 -262
- package/dist/chunk-2TWGLC5K.cjs.map +0 -1
- package/dist/chunk-4SUNJZWB.cjs.map +0 -1
- package/dist/chunk-6M3BCTBD.cjs.map +0 -1
- package/dist/chunk-AA4ZEVCC.cjs.map +0 -1
- package/dist/chunk-AXV2ZW34.cjs +0 -118
- package/dist/chunk-AXV2ZW34.cjs.map +0 -1
- package/dist/chunk-B2ZRLN4S.js +0 -118
- package/dist/chunk-B2ZRLN4S.js.map +0 -1
- package/dist/chunk-DENSCKFC.js.map +0 -1
- package/dist/chunk-GVSMRPHB.cjs.map +0 -1
- package/dist/chunk-KAADNAPF.js +0 -262
- package/dist/chunk-KAADNAPF.js.map +0 -1
- package/dist/chunk-MJZBNWG7.js.map +0 -1
- package/dist/chunk-OYXSKQFR.js.map +0 -1
- package/dist/chunk-QGHGJ56O.js.map +0 -1
- package/dist/chunk-RU52I7QO.js.map +0 -1
- package/dist/chunk-SAZRENEZ.cjs.map +0 -1
- package/dist/types-BZgcDsC5.d.cts +0 -42
- package/dist/types-BZgcDsC5.d.ts +0 -42
- /package/dist/{chunk-JJDLPEWL.js.map → chunk-3LV6RRPH.js.map} +0 -0
|
@@ -0,0 +1,1373 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getLatestVersion,
|
|
3
|
+
getTemplateBody,
|
|
4
|
+
resolvePrompt,
|
|
5
|
+
tokenizePrompt
|
|
6
|
+
} from "../chunk-FPENXAEJ.js";
|
|
7
|
+
import "../chunk-P6ODPZ4W.js";
|
|
8
|
+
import {
|
|
9
|
+
validateJsonSchema
|
|
10
|
+
} from "../chunk-ARRTP33I.js";
|
|
11
|
+
|
|
12
|
+
// src/generation/capabilities.ts
|
|
13
|
+
var REFERENCE_ROLES = [
|
|
14
|
+
"start_frame",
|
|
15
|
+
"end_frame",
|
|
16
|
+
"style_ref",
|
|
17
|
+
"character_ref",
|
|
18
|
+
"background_ref",
|
|
19
|
+
"mask",
|
|
20
|
+
"image_ref",
|
|
21
|
+
"video_ref",
|
|
22
|
+
"audio_ref"
|
|
23
|
+
];
|
|
24
|
+
var REFERENCE_ROLE_LABELS = {
|
|
25
|
+
start_frame: "Start frame",
|
|
26
|
+
end_frame: "End frame",
|
|
27
|
+
style_ref: "Style reference",
|
|
28
|
+
character_ref: "Character reference",
|
|
29
|
+
background_ref: "Background reference",
|
|
30
|
+
mask: "Mask",
|
|
31
|
+
image_ref: "Image reference",
|
|
32
|
+
video_ref: "Video reference",
|
|
33
|
+
audio_ref: "Audio reference"
|
|
34
|
+
};
|
|
35
|
+
var GENERATION_REQUEST_FIELDS = [
|
|
36
|
+
"model",
|
|
37
|
+
"prompt",
|
|
38
|
+
"negativePrompt",
|
|
39
|
+
"systemPrompt",
|
|
40
|
+
"aspectRatio",
|
|
41
|
+
"resolution",
|
|
42
|
+
"quality",
|
|
43
|
+
"count",
|
|
44
|
+
"duration",
|
|
45
|
+
"seed",
|
|
46
|
+
"mode",
|
|
47
|
+
"references",
|
|
48
|
+
"params"
|
|
49
|
+
];
|
|
50
|
+
function textFieldCapability(value) {
|
|
51
|
+
if (!value) return null;
|
|
52
|
+
return value === true ? {} : value;
|
|
53
|
+
}
|
|
54
|
+
function seedCapability(value) {
|
|
55
|
+
if (!value) return null;
|
|
56
|
+
return value === true ? {} : value;
|
|
57
|
+
}
|
|
58
|
+
function supportedReferenceRoles(caps) {
|
|
59
|
+
const roles = caps.references?.roles ?? {};
|
|
60
|
+
return REFERENCE_ROLES.filter((role) => (roles[role]?.max ?? 0) > 0);
|
|
61
|
+
}
|
|
62
|
+
function supportedModes(caps) {
|
|
63
|
+
const modes = ["generate"];
|
|
64
|
+
if (caps.editing) modes.push("edit");
|
|
65
|
+
if (caps.inpainting) modes.push("inpaint");
|
|
66
|
+
return modes;
|
|
67
|
+
}
|
|
68
|
+
var PRESENTATION_KEYS = ["name", "description", "badges", "icon", "group"];
|
|
69
|
+
function mergeCapabilities(remote, overlay = []) {
|
|
70
|
+
const overlayById = new Map(overlay.map((entry) => [entry.id, entry]));
|
|
71
|
+
const remoteIds = new Set(remote.map((model) => model.id));
|
|
72
|
+
const merged = remote.map((model) => {
|
|
73
|
+
const extra = overlayById.get(model.id);
|
|
74
|
+
if (!extra) return { ...model };
|
|
75
|
+
const next = { ...model };
|
|
76
|
+
for (const key of PRESENTATION_KEYS) {
|
|
77
|
+
if (extra[key] !== void 0) next[key] = extra[key];
|
|
78
|
+
}
|
|
79
|
+
return next;
|
|
80
|
+
});
|
|
81
|
+
for (const entry of overlay) {
|
|
82
|
+
if (remoteIds.has(entry.id) || !entry.media) continue;
|
|
83
|
+
remoteIds.add(entry.id);
|
|
84
|
+
merged.push({ ...entry });
|
|
85
|
+
}
|
|
86
|
+
return merged;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// src/generation/plan.ts
|
|
90
|
+
var EPSILON = 1e-9;
|
|
91
|
+
function aspectRatioRank(value) {
|
|
92
|
+
const match = /^\s*(\d+(?:\.\d+)?)\s*[:x/×]\s*(\d+(?:\.\d+)?)\s*$/i.exec(String(value));
|
|
93
|
+
if (!match) return void 0;
|
|
94
|
+
const w = Number(match[1]);
|
|
95
|
+
const h = Number(match[2]);
|
|
96
|
+
if (!(w > 0) || !(h > 0)) return void 0;
|
|
97
|
+
return Math.log(w / h);
|
|
98
|
+
}
|
|
99
|
+
function resolutionRank(value) {
|
|
100
|
+
const text = String(value).trim().toLowerCase();
|
|
101
|
+
let pixels;
|
|
102
|
+
let match = /^(\d+(?:\.\d+)?)\s*[x×*]\s*(\d+(?:\.\d+)?)$/.exec(text);
|
|
103
|
+
if (match) pixels = Number(match[1]) * Number(match[2]);
|
|
104
|
+
else if (match = /^(\d+(?:\.\d+)?)p$/.exec(text)) pixels = Number(match[1]) ** 2 * 16 / 9;
|
|
105
|
+
else if (match = /^(\d+(?:\.\d+)?)k$/.exec(text)) pixels = (Number(match[1]) * 1024) ** 2;
|
|
106
|
+
return pixels && pixels > 0 ? Math.log(pixels) : void 0;
|
|
107
|
+
}
|
|
108
|
+
function resolutionMegapixels(value) {
|
|
109
|
+
const rank = resolutionRank(value);
|
|
110
|
+
return rank === void 0 ? void 0 : Math.exp(rank) / 1e6;
|
|
111
|
+
}
|
|
112
|
+
var QUALITY_LADDER = {
|
|
113
|
+
draft: 0,
|
|
114
|
+
preview: 0,
|
|
115
|
+
low: 1,
|
|
116
|
+
fast: 1,
|
|
117
|
+
turbo: 1,
|
|
118
|
+
standard: 2,
|
|
119
|
+
normal: 2,
|
|
120
|
+
medium: 2,
|
|
121
|
+
balanced: 2,
|
|
122
|
+
high: 3,
|
|
123
|
+
hd: 3,
|
|
124
|
+
quality: 3,
|
|
125
|
+
ultra: 4,
|
|
126
|
+
max: 5,
|
|
127
|
+
best: 5
|
|
128
|
+
};
|
|
129
|
+
function qualityRank(value) {
|
|
130
|
+
return QUALITY_LADDER[String(value).trim().toLowerCase()];
|
|
131
|
+
}
|
|
132
|
+
var numberRank = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
133
|
+
function snapToOption(value, options, rank, tie) {
|
|
134
|
+
const target = rank(value);
|
|
135
|
+
if (target === void 0) return void 0;
|
|
136
|
+
let best;
|
|
137
|
+
for (const option of options) {
|
|
138
|
+
const r = rank(option);
|
|
139
|
+
if (r === void 0) continue;
|
|
140
|
+
const distance = Math.abs(r - target);
|
|
141
|
+
if (!best || distance < best.distance - EPSILON || Math.abs(distance - best.distance) <= EPSILON && (tie === "lower" ? r < best.rank : r > best.rank)) {
|
|
142
|
+
best = { option, distance, rank: r };
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return best?.option;
|
|
146
|
+
}
|
|
147
|
+
function truncateText(text, max) {
|
|
148
|
+
if (text.length <= max) return text;
|
|
149
|
+
let end = max;
|
|
150
|
+
const code = text.charCodeAt(end - 1);
|
|
151
|
+
if (end > 0 && code >= 55296 && code <= 56319) end -= 1;
|
|
152
|
+
return text.slice(0, end);
|
|
153
|
+
}
|
|
154
|
+
function cloneRequest(request) {
|
|
155
|
+
const copy = { ...request };
|
|
156
|
+
if (request.references) copy.references = request.references.map((ref) => ({ ...ref }));
|
|
157
|
+
if (request.params) copy.params = { ...request.params };
|
|
158
|
+
return copy;
|
|
159
|
+
}
|
|
160
|
+
var describe = (value) => typeof value === "string" ? `"${value}"` : JSON.stringify(value);
|
|
161
|
+
var list = (options) => options.map(describe).join(", ");
|
|
162
|
+
var Planner = class {
|
|
163
|
+
constructor(caps, request, options, strategy) {
|
|
164
|
+
this.caps = caps;
|
|
165
|
+
this.request = request;
|
|
166
|
+
this.options = options;
|
|
167
|
+
this.strategy = strategy;
|
|
168
|
+
this.tie = strategy === "downgrade" ? "lower" : "higher";
|
|
169
|
+
this.strict = strategy === "error";
|
|
170
|
+
}
|
|
171
|
+
caps;
|
|
172
|
+
request;
|
|
173
|
+
options;
|
|
174
|
+
strategy;
|
|
175
|
+
adjustments = [];
|
|
176
|
+
errors = [];
|
|
177
|
+
tie;
|
|
178
|
+
strict;
|
|
179
|
+
adjust(field, from, to, kind, reason) {
|
|
180
|
+
this.adjustments.push({ field, from, to, kind, reason });
|
|
181
|
+
}
|
|
182
|
+
error(field, value, message) {
|
|
183
|
+
this.errors.push({ field, value, message });
|
|
184
|
+
}
|
|
185
|
+
/** Removes an unsupported field (or reports it under `error`). */
|
|
186
|
+
unsupported(field, message) {
|
|
187
|
+
const value = this.request[field];
|
|
188
|
+
if (this.strict) {
|
|
189
|
+
this.error(field, value, message);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
delete this.request[field];
|
|
193
|
+
this.adjust(field, value, void 0, "dropped", message);
|
|
194
|
+
}
|
|
195
|
+
defaulted(field, value, set) {
|
|
196
|
+
if (!this.options.fillDefaults || value === void 0) return;
|
|
197
|
+
set();
|
|
198
|
+
this.adjust(field, void 0, value, "defaulted", "Filled with the model default.");
|
|
199
|
+
}
|
|
200
|
+
planText(field, maxLength, measured) {
|
|
201
|
+
const value = this.request[field];
|
|
202
|
+
if (value === void 0 || maxLength === void 0) return;
|
|
203
|
+
if (typeof value !== "string") {
|
|
204
|
+
this.error(field, value, `Expected text.`);
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
const text = measured ?? value;
|
|
208
|
+
if (text.length <= maxLength) return;
|
|
209
|
+
if (this.strict || measured !== void 0) {
|
|
210
|
+
this.error(
|
|
211
|
+
field,
|
|
212
|
+
text.length,
|
|
213
|
+
`${measured !== void 0 ? "Resolved text" : "Text"} is ${text.length} characters; the model accepts at most ${maxLength}.`
|
|
214
|
+
);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
const next = truncateText(value, maxLength);
|
|
218
|
+
this.request[field] = next;
|
|
219
|
+
this.adjust(field, value.length, next.length, "truncated", `Truncated to the model's ${maxLength}-character limit.`);
|
|
220
|
+
}
|
|
221
|
+
planEnum(field, cap, rank, label) {
|
|
222
|
+
const value = this.request[field];
|
|
223
|
+
if (value === void 0) {
|
|
224
|
+
if (cap) this.defaulted(field, cap.default, () => this.request[field] = cap.default);
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
if (!cap || cap.options.length === 0) {
|
|
228
|
+
this.unsupported(field, `The model does not take a ${label}.`);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
if (cap.options.includes(value)) return;
|
|
232
|
+
if (this.strict) {
|
|
233
|
+
this.error(field, value, `${describe(value)} is not a supported ${label}; supported: ${list(cap.options)}.`);
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
const snapped = snapToOption(value, cap.options, rank, this.tie);
|
|
237
|
+
const next = snapped ?? cap.default ?? cap.options[0];
|
|
238
|
+
this.request[field] = next;
|
|
239
|
+
this.adjust(
|
|
240
|
+
field,
|
|
241
|
+
value,
|
|
242
|
+
next,
|
|
243
|
+
"snapped",
|
|
244
|
+
snapped !== void 0 ? `${describe(value)} is not supported; using the nearest ${label}.` : `${describe(value)} is not supported; using ${cap.default !== void 0 ? "the default" : "the first option"}.`
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
/** Clamps/rounds/snaps a number. Returns the next value or `undefined` after an error. */
|
|
248
|
+
planNumber(field, value, spec, label) {
|
|
249
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
250
|
+
this.error(field, value, `Expected a number for ${label}.`);
|
|
251
|
+
return void 0;
|
|
252
|
+
}
|
|
253
|
+
const options = spec.options?.filter(
|
|
254
|
+
(o) => (spec.min === void 0 || o >= spec.min) && (spec.max === void 0 || o <= spec.max)
|
|
255
|
+
);
|
|
256
|
+
if (options && options.length > 0) {
|
|
257
|
+
if (options.includes(value)) return { value, changed: false };
|
|
258
|
+
if (this.strict) {
|
|
259
|
+
this.error(field, value, `${value} is not a supported ${label}; supported: ${list(options)}.`);
|
|
260
|
+
return void 0;
|
|
261
|
+
}
|
|
262
|
+
const next2 = snapToOption(value, options, numberRank, this.tie);
|
|
263
|
+
this.adjust(field, value, next2, "snapped", `${value} is not supported; using the nearest ${label}.`);
|
|
264
|
+
return { value: next2, changed: true };
|
|
265
|
+
}
|
|
266
|
+
let next = value;
|
|
267
|
+
if (spec.step !== void 0 && spec.step > 0) {
|
|
268
|
+
const base = spec.min ?? 0;
|
|
269
|
+
const steps = (next - base) / spec.step;
|
|
270
|
+
const rounded = Math.abs(steps - Math.trunc(steps) - 0.5) < EPSILON ? this.tie === "lower" ? Math.floor(steps) : Math.ceil(steps) : Math.round(steps);
|
|
271
|
+
next = Number((base + rounded * spec.step).toPrecision(12));
|
|
272
|
+
}
|
|
273
|
+
if (spec.integer && !Number.isInteger(next)) {
|
|
274
|
+
const frac = next - Math.floor(next);
|
|
275
|
+
next = Math.abs(frac - 0.5) < EPSILON ? this.tie === "lower" ? Math.floor(next) : Math.ceil(next) : Math.round(next);
|
|
276
|
+
}
|
|
277
|
+
let kind = "snapped";
|
|
278
|
+
if (spec.min !== void 0 && next < spec.min) {
|
|
279
|
+
next = spec.min;
|
|
280
|
+
kind = "clamped";
|
|
281
|
+
}
|
|
282
|
+
if (spec.max !== void 0 && next > spec.max) {
|
|
283
|
+
next = spec.max;
|
|
284
|
+
kind = "clamped";
|
|
285
|
+
}
|
|
286
|
+
if (next === value) return { value, changed: false };
|
|
287
|
+
const range = `${spec.min ?? "-\u221E"}\u2013${spec.max ?? "\u221E"}`;
|
|
288
|
+
if (this.strict) {
|
|
289
|
+
this.error(
|
|
290
|
+
field,
|
|
291
|
+
value,
|
|
292
|
+
kind === "clamped" ? `${label} must be within ${range}.` : `${value} is not a valid ${label} (try ${next}).`
|
|
293
|
+
);
|
|
294
|
+
return void 0;
|
|
295
|
+
}
|
|
296
|
+
this.adjust(
|
|
297
|
+
field,
|
|
298
|
+
value,
|
|
299
|
+
next,
|
|
300
|
+
kind,
|
|
301
|
+
kind === "clamped" ? `Clamped to the supported range ${range}.` : `Rounded to a supported ${label}.`
|
|
302
|
+
);
|
|
303
|
+
return { value: next, changed: true };
|
|
304
|
+
}
|
|
305
|
+
planCount() {
|
|
306
|
+
const value = this.request.count;
|
|
307
|
+
const cap = this.caps.count;
|
|
308
|
+
if (value === void 0) {
|
|
309
|
+
if (cap) this.defaulted("count", cap.default, () => this.request.count = cap.default);
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
if (!cap) {
|
|
313
|
+
if (value === 1) return;
|
|
314
|
+
this.unsupported("count", "The model produces one output per request.");
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
const result = this.planNumber("count", value, { min: 1, max: cap.max, integer: true, options: cap.options }, "output count");
|
|
318
|
+
if (result) this.request.count = result.value;
|
|
319
|
+
}
|
|
320
|
+
planDuration() {
|
|
321
|
+
const value = this.request.duration;
|
|
322
|
+
const cap = this.caps.duration;
|
|
323
|
+
if (value === void 0) {
|
|
324
|
+
if (cap) this.defaulted("duration", cap.default, () => this.request.duration = cap.default);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
if (!cap) {
|
|
328
|
+
this.unsupported("duration", "The model does not take a duration.");
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
const result = this.planNumber("duration", value, cap, "duration");
|
|
332
|
+
if (result) this.request.duration = result.value;
|
|
333
|
+
}
|
|
334
|
+
planSeed() {
|
|
335
|
+
const value = this.request.seed;
|
|
336
|
+
if (value === void 0) return;
|
|
337
|
+
const cap = seedCapability(this.caps.seed);
|
|
338
|
+
if (!cap) {
|
|
339
|
+
this.unsupported("seed", "The model does not take a seed.");
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
const result = this.planNumber("seed", value, { ...cap, integer: true }, "seed");
|
|
343
|
+
if (result) this.request.seed = result.value;
|
|
344
|
+
}
|
|
345
|
+
planMode() {
|
|
346
|
+
const mode = this.request.mode;
|
|
347
|
+
if (mode === void 0) return;
|
|
348
|
+
const modes = supportedModes(this.caps);
|
|
349
|
+
if (!modes.includes(mode)) {
|
|
350
|
+
this.error("mode", mode, `The model does not support ${describe(mode)}; supported: ${list(modes)}.`);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
roleCapability(role) {
|
|
354
|
+
const cap = this.caps.references?.roles[role];
|
|
355
|
+
if (cap && cap.max > 0) return cap;
|
|
356
|
+
if (role === "mask" && this.caps.inpainting) return { max: 1 };
|
|
357
|
+
return void 0;
|
|
358
|
+
}
|
|
359
|
+
planReferences() {
|
|
360
|
+
const refs = this.request.references;
|
|
361
|
+
const allowDrop = !this.strict && (this.options.dropUnsupportedReferences ?? (this.strategy === "nearest" || this.strategy === "downgrade"));
|
|
362
|
+
const byRole = /* @__PURE__ */ new Map();
|
|
363
|
+
const kept = [];
|
|
364
|
+
const unsupported = /* @__PURE__ */ new Map();
|
|
365
|
+
for (const [index, ref] of (refs ?? []).entries()) {
|
|
366
|
+
if (!ref || typeof ref.id !== "string" || ref.id === "" || !REFERENCE_ROLES.includes(ref.role)) {
|
|
367
|
+
this.error(`references.${index}`, ref, "Each reference needs an `id` and a known `role`.");
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
if (!this.roleCapability(ref.role)) {
|
|
371
|
+
unsupported.set(ref.role, (unsupported.get(ref.role) ?? 0) + 1);
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
const group = byRole.get(ref.role) ?? [];
|
|
375
|
+
if (group.some((other) => other.id === ref.id)) {
|
|
376
|
+
this.adjust(`references.${ref.role}`, ref.id, void 0, "dropped", `Duplicate reference "${ref.id}" removed.`);
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
group.push(ref);
|
|
380
|
+
byRole.set(ref.role, group);
|
|
381
|
+
kept.push(ref);
|
|
382
|
+
}
|
|
383
|
+
for (const [role, count] of unsupported) {
|
|
384
|
+
const message = this.caps.media === "text" || !this.caps.references ? `The ${this.caps.media} model "${this.caps.id}" does not accept reference inputs (${role}).` : `The model does not accept ${role} references.`;
|
|
385
|
+
if (allowDrop) this.adjust(`references.${role}`, count, 0, "dropped", message);
|
|
386
|
+
else this.error(`references.${role}`, count, message);
|
|
387
|
+
}
|
|
388
|
+
const removed = /* @__PURE__ */ new Set();
|
|
389
|
+
for (const role of REFERENCE_ROLES) {
|
|
390
|
+
const cap = this.roleCapability(role);
|
|
391
|
+
const group = byRole.get(role) ?? [];
|
|
392
|
+
if (!cap) continue;
|
|
393
|
+
if (group.length > cap.max) {
|
|
394
|
+
if (this.strict) {
|
|
395
|
+
this.error(`references.${role}`, group.length, `At most ${cap.max} ${role} reference(s) are supported.`);
|
|
396
|
+
} else {
|
|
397
|
+
group.slice(cap.max).forEach((ref) => removed.add(ref));
|
|
398
|
+
this.adjust(
|
|
399
|
+
`references.${role}`,
|
|
400
|
+
group.length,
|
|
401
|
+
cap.max,
|
|
402
|
+
"truncated",
|
|
403
|
+
`Kept the first ${cap.max} ${role} reference(s); the model accepts no more.`
|
|
404
|
+
);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
if (cap.min !== void 0 && group.length < cap.min) {
|
|
408
|
+
this.error(`references.${role}`, group.length, `At least ${cap.min} ${role} reference(s) are required.`);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
let next = kept.filter((ref) => !removed.has(ref));
|
|
412
|
+
const maxTotal = this.caps.references?.maxTotal;
|
|
413
|
+
if (maxTotal !== void 0 && next.length > maxTotal) {
|
|
414
|
+
if (this.strict) {
|
|
415
|
+
this.error("references", next.length, `At most ${maxTotal} references are supported in total.`);
|
|
416
|
+
} else {
|
|
417
|
+
this.adjust(
|
|
418
|
+
"references",
|
|
419
|
+
next.length,
|
|
420
|
+
maxTotal,
|
|
421
|
+
"truncated",
|
|
422
|
+
`Kept the first ${maxTotal} references; the model accepts no more in total.`
|
|
423
|
+
);
|
|
424
|
+
next = next.slice(0, maxTotal);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
if (this.request.mode === "inpaint" && !next.some((ref) => ref.role === "mask")) {
|
|
428
|
+
this.error("references.mask", 0, "Inpainting needs a `mask` reference.");
|
|
429
|
+
}
|
|
430
|
+
if (refs === void 0) return;
|
|
431
|
+
if (!this.strict) {
|
|
432
|
+
if (next.length > 0) this.request.references = next;
|
|
433
|
+
else delete this.request.references;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
planParam(name, spec, value) {
|
|
437
|
+
const field = `params.${name}`;
|
|
438
|
+
if (!spec) {
|
|
439
|
+
if (this.strict) this.error(field, value, `Unknown parameter "${name}".`);
|
|
440
|
+
else this.adjust(field, value, void 0, "dropped", `The model has no "${name}" parameter.`);
|
|
441
|
+
return void 0;
|
|
442
|
+
}
|
|
443
|
+
const label = spec.label ?? name;
|
|
444
|
+
if (spec.type === "boolean") {
|
|
445
|
+
if (typeof value !== "boolean") this.error(field, value, `Expected true or false for ${label}.`);
|
|
446
|
+
return value;
|
|
447
|
+
}
|
|
448
|
+
if (spec.type === "enum") {
|
|
449
|
+
if (spec.options.includes(value)) return value;
|
|
450
|
+
if (this.strict) {
|
|
451
|
+
this.error(field, value, `${describe(value)} is not a supported ${label}; supported: ${list(spec.options)}.`);
|
|
452
|
+
return value;
|
|
453
|
+
}
|
|
454
|
+
const numeric = spec.options.every((o) => typeof o === "number");
|
|
455
|
+
const snapped = numeric ? snapToOption(value, spec.options, numberRank, this.tie) : void 0;
|
|
456
|
+
const next = snapped ?? spec.default ?? spec.options[0];
|
|
457
|
+
this.adjust(
|
|
458
|
+
field,
|
|
459
|
+
value,
|
|
460
|
+
next,
|
|
461
|
+
"snapped",
|
|
462
|
+
snapped !== void 0 ? `Using the nearest supported ${label}.` : `${describe(value)} is not supported; using ${spec.default !== void 0 ? "the default" : "the first option"}.`
|
|
463
|
+
);
|
|
464
|
+
return next;
|
|
465
|
+
}
|
|
466
|
+
const result = this.planNumber(field, value, { ...spec, integer: spec.type === "integer" }, label);
|
|
467
|
+
return result ? result.value : value;
|
|
468
|
+
}
|
|
469
|
+
planParams() {
|
|
470
|
+
const params = this.request.params;
|
|
471
|
+
const specs = this.caps.params ?? {};
|
|
472
|
+
const next = {};
|
|
473
|
+
for (const [name, value] of Object.entries(params ?? {})) {
|
|
474
|
+
if (value === void 0) continue;
|
|
475
|
+
const planned = this.planParam(name, specs[name], value);
|
|
476
|
+
if (planned !== void 0) next[name] = planned;
|
|
477
|
+
else if (this.strict) next[name] = value;
|
|
478
|
+
}
|
|
479
|
+
if (this.options.fillDefaults) {
|
|
480
|
+
for (const [name, spec] of Object.entries(specs)) {
|
|
481
|
+
if (next[name] === void 0 && spec.default !== void 0) {
|
|
482
|
+
next[name] = spec.default;
|
|
483
|
+
this.adjust(`params.${name}`, void 0, spec.default, "defaulted", "Filled with the model default.");
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
if (Object.keys(next).length > 0) this.request.params = next;
|
|
488
|
+
else delete this.request.params;
|
|
489
|
+
}
|
|
490
|
+
run() {
|
|
491
|
+
const { caps, request } = this;
|
|
492
|
+
for (const key of Object.keys(request)) {
|
|
493
|
+
if (GENERATION_REQUEST_FIELDS.includes(key)) continue;
|
|
494
|
+
const value = request[key];
|
|
495
|
+
if (this.strict) this.error(key, value, `Unknown request field "${key}".`);
|
|
496
|
+
else {
|
|
497
|
+
delete request[key];
|
|
498
|
+
this.adjust(key, value, void 0, "dropped", `Unknown request field "${key}".`);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
if (request.model !== void 0 && request.model !== caps.id) {
|
|
502
|
+
this.error("model", request.model, `The request targets "${request.model}" but the plan is for "${caps.id}".`);
|
|
503
|
+
}
|
|
504
|
+
request.model = caps.id;
|
|
505
|
+
const promptCap = caps.prompt ?? {};
|
|
506
|
+
if (promptCap.required && !(request.prompt ?? "").trim()) {
|
|
507
|
+
this.error("prompt", request.prompt, "A prompt is required.");
|
|
508
|
+
}
|
|
509
|
+
const countResolved = promptCap.countResolved ?? true;
|
|
510
|
+
const measured = countResolved && this.options.resolvedPrompt !== void 0 && this.options.resolvedPrompt !== request.prompt ? this.options.resolvedPrompt : void 0;
|
|
511
|
+
this.planText("prompt", promptCap.maxLength, measured);
|
|
512
|
+
for (const field of ["negativePrompt", "systemPrompt"]) {
|
|
513
|
+
if (request[field] === void 0) continue;
|
|
514
|
+
const cap = textFieldCapability(caps[field]);
|
|
515
|
+
if (!cap) {
|
|
516
|
+
this.unsupported(field, `The model does not take a ${field === "negativePrompt" ? "negative" : "system"} prompt.`);
|
|
517
|
+
continue;
|
|
518
|
+
}
|
|
519
|
+
this.planText(field, cap.maxLength);
|
|
520
|
+
}
|
|
521
|
+
this.planEnum("aspectRatio", caps.aspectRatios, aspectRatioRank, "aspect ratio");
|
|
522
|
+
this.planEnum("resolution", caps.resolutions, resolutionRank, "resolution");
|
|
523
|
+
this.planEnum("quality", caps.quality, qualityRank, "quality");
|
|
524
|
+
this.planCount();
|
|
525
|
+
this.planDuration();
|
|
526
|
+
this.planSeed();
|
|
527
|
+
this.planMode();
|
|
528
|
+
this.planReferences();
|
|
529
|
+
this.planParams();
|
|
530
|
+
}
|
|
531
|
+
};
|
|
532
|
+
function planGenerationRequest(request, caps, options = {}) {
|
|
533
|
+
const strategy = options.strategy ?? "nearest";
|
|
534
|
+
const planner = new Planner(caps, cloneRequest(request ?? {}), options, strategy);
|
|
535
|
+
planner.run();
|
|
536
|
+
return {
|
|
537
|
+
ok: planner.errors.length === 0,
|
|
538
|
+
request: planner.request,
|
|
539
|
+
adjustments: planner.adjustments,
|
|
540
|
+
errors: planner.errors,
|
|
541
|
+
model: caps.id,
|
|
542
|
+
strategy
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// src/generation/schema.ts
|
|
547
|
+
function enumSchema(cap, description) {
|
|
548
|
+
return {
|
|
549
|
+
type: "string",
|
|
550
|
+
enum: [...cap.options],
|
|
551
|
+
...cap.default !== void 0 ? { default: cap.default } : {},
|
|
552
|
+
description
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
function paramSchema(name, spec) {
|
|
556
|
+
const description = spec.description ?? spec.label ?? name;
|
|
557
|
+
if (spec.type === "boolean") {
|
|
558
|
+
return { type: "boolean", description, ...spec.default !== void 0 ? { default: spec.default } : {} };
|
|
559
|
+
}
|
|
560
|
+
if (spec.type === "enum") {
|
|
561
|
+
const numeric = spec.options.every((o) => typeof o === "number");
|
|
562
|
+
return {
|
|
563
|
+
type: numeric ? "number" : "string",
|
|
564
|
+
enum: [...spec.options],
|
|
565
|
+
description,
|
|
566
|
+
...spec.default !== void 0 ? { default: spec.default } : {}
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
return {
|
|
570
|
+
type: spec.type,
|
|
571
|
+
description: spec.step !== void 0 ? `${description} (step ${spec.step})` : description,
|
|
572
|
+
...spec.min !== void 0 ? { minimum: spec.min } : {},
|
|
573
|
+
...spec.max !== void 0 ? { maximum: spec.max } : {},
|
|
574
|
+
...spec.default !== void 0 ? { default: spec.default } : {}
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
function capabilitiesToJsonSchema(caps) {
|
|
578
|
+
const properties = {
|
|
579
|
+
model: { type: "string", const: caps.id, description: "Model id." }
|
|
580
|
+
};
|
|
581
|
+
const required = [];
|
|
582
|
+
const prompt = caps.prompt ?? {};
|
|
583
|
+
const countResolved = prompt.countResolved ?? true;
|
|
584
|
+
properties.prompt = {
|
|
585
|
+
type: "string",
|
|
586
|
+
description: prompt.maxLength !== void 0 ? `Prompt text. At most ${prompt.maxLength} characters${countResolved ? " after templates and variables are resolved" : ""}.` : "Prompt text.",
|
|
587
|
+
...prompt.maxLength !== void 0 && !countResolved ? { maxLength: prompt.maxLength } : {},
|
|
588
|
+
...prompt.required ? { minLength: 1 } : {}
|
|
589
|
+
};
|
|
590
|
+
if (prompt.required) required.push("prompt");
|
|
591
|
+
const negative = textFieldCapability(caps.negativePrompt);
|
|
592
|
+
if (negative) {
|
|
593
|
+
properties.negativePrompt = {
|
|
594
|
+
type: "string",
|
|
595
|
+
description: "What to avoid in the output.",
|
|
596
|
+
...negative.maxLength !== void 0 ? { maxLength: negative.maxLength } : {}
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
const system = textFieldCapability(caps.systemPrompt);
|
|
600
|
+
if (system) {
|
|
601
|
+
properties.systemPrompt = {
|
|
602
|
+
type: "string",
|
|
603
|
+
description: "System instructions.",
|
|
604
|
+
...system.maxLength !== void 0 ? { maxLength: system.maxLength } : {}
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
if (caps.aspectRatios?.options.length) properties.aspectRatio = enumSchema(caps.aspectRatios, "Aspect ratio (width:height).");
|
|
608
|
+
if (caps.resolutions?.options.length) properties.resolution = enumSchema(caps.resolutions, "Output resolution, low to high.");
|
|
609
|
+
if (caps.quality?.options.length) properties.quality = enumSchema(caps.quality, "Quality level, low to high.");
|
|
610
|
+
if (caps.count) {
|
|
611
|
+
const options = caps.count.options?.filter((o) => o >= 1 && o <= caps.count.max);
|
|
612
|
+
properties.count = options?.length ? { type: "integer", enum: options, description: "Number of outputs." } : { type: "integer", minimum: 1, maximum: caps.count.max, description: "Number of outputs." };
|
|
613
|
+
if (caps.count.default !== void 0) properties.count.default = caps.count.default;
|
|
614
|
+
}
|
|
615
|
+
if (caps.duration) {
|
|
616
|
+
const d = caps.duration;
|
|
617
|
+
const options = d.options?.filter((o) => (d.min === void 0 || o >= d.min) && (d.max === void 0 || o <= d.max));
|
|
618
|
+
properties.duration = options?.length ? { type: "number", enum: options, description: "Duration in seconds." } : {
|
|
619
|
+
type: "number",
|
|
620
|
+
description: d.step !== void 0 ? `Duration in seconds (step ${d.step}).` : "Duration in seconds.",
|
|
621
|
+
...d.min !== void 0 ? { minimum: d.min } : {},
|
|
622
|
+
...d.max !== void 0 ? { maximum: d.max } : {}
|
|
623
|
+
};
|
|
624
|
+
if (d.default !== void 0) properties.duration.default = d.default;
|
|
625
|
+
}
|
|
626
|
+
const seed = seedCapability(caps.seed);
|
|
627
|
+
if (seed) {
|
|
628
|
+
properties.seed = {
|
|
629
|
+
type: "integer",
|
|
630
|
+
description: "Random seed for reproducible output.",
|
|
631
|
+
...seed.min !== void 0 ? { minimum: seed.min } : {},
|
|
632
|
+
...seed.max !== void 0 ? { maximum: seed.max } : {}
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
const modes = supportedModes(caps);
|
|
636
|
+
if (modes.length > 1) {
|
|
637
|
+
properties.mode = { type: "string", enum: modes, default: "generate", description: "Generate, edit a source, or inpaint with a mask." };
|
|
638
|
+
}
|
|
639
|
+
const roles = supportedReferenceRoles(caps);
|
|
640
|
+
if (caps.inpainting && !roles.includes("mask")) roles.push("mask");
|
|
641
|
+
if (roles.length > 0) {
|
|
642
|
+
const limits = roles.map((role) => {
|
|
643
|
+
const cap = caps.references?.roles[role] ?? { max: 1 };
|
|
644
|
+
const min = cap.min ? `${cap.min}\u2013` : "up to ";
|
|
645
|
+
return `${role} (${cap.label ?? REFERENCE_ROLE_LABELS[role]}): ${min}${cap.max}`;
|
|
646
|
+
});
|
|
647
|
+
const perRoleTotal = roles.reduce((sum, role) => sum + (caps.references?.roles[role]?.max ?? 1), 0);
|
|
648
|
+
const maxItems = Math.min(caps.references?.maxTotal ?? Infinity, perRoleTotal);
|
|
649
|
+
properties.references = {
|
|
650
|
+
type: "array",
|
|
651
|
+
description: `Reference inputs by role. Limits: ${limits.join("; ")}${caps.references?.maxTotal !== void 0 ? `; at most ${caps.references.maxTotal} in total` : ""}.`,
|
|
652
|
+
maxItems,
|
|
653
|
+
items: {
|
|
654
|
+
type: "object",
|
|
655
|
+
properties: {
|
|
656
|
+
id: { type: "string", minLength: 1, description: "Asset id." },
|
|
657
|
+
role: { type: "string", enum: roles },
|
|
658
|
+
url: { type: "string" }
|
|
659
|
+
},
|
|
660
|
+
required: ["id", "role"],
|
|
661
|
+
additionalProperties: false
|
|
662
|
+
}
|
|
663
|
+
};
|
|
664
|
+
if (roles.some((role) => (caps.references?.roles[role]?.min ?? 0) > 0)) required.push("references");
|
|
665
|
+
}
|
|
666
|
+
const params = Object.entries(caps.params ?? {});
|
|
667
|
+
if (params.length > 0) {
|
|
668
|
+
properties.params = {
|
|
669
|
+
type: "object",
|
|
670
|
+
description: "Model-specific parameters.",
|
|
671
|
+
properties: Object.fromEntries(params.map(([name, spec]) => [name, paramSchema(name, spec)])),
|
|
672
|
+
additionalProperties: false
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
return {
|
|
676
|
+
type: "object",
|
|
677
|
+
title: caps.name ?? caps.id,
|
|
678
|
+
description: `${caps.description ? `${caps.description} ` : ""}(${caps.media} model "${caps.id}")`,
|
|
679
|
+
properties,
|
|
680
|
+
...required.length ? { required } : {},
|
|
681
|
+
additionalProperties: false
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
// src/generation/tools.ts
|
|
686
|
+
var STRATEGIES = ["nearest", "upgrade", "downgrade", "error"];
|
|
687
|
+
var requestSchema = {
|
|
688
|
+
type: "object",
|
|
689
|
+
description: "Generation request. Call list_models for the fields each model supports; unsupported values are adjusted per `strategy`.",
|
|
690
|
+
properties: {
|
|
691
|
+
prompt: { type: "string" },
|
|
692
|
+
negativePrompt: { type: "string" },
|
|
693
|
+
systemPrompt: { type: "string" },
|
|
694
|
+
aspectRatio: { type: "string", description: 'E.g. "16:9".' },
|
|
695
|
+
resolution: { type: "string" },
|
|
696
|
+
quality: { type: "string" },
|
|
697
|
+
count: { type: "integer", minimum: 1 },
|
|
698
|
+
duration: { type: "number", minimum: 0, description: "Seconds." },
|
|
699
|
+
seed: { type: "integer" },
|
|
700
|
+
mode: { type: "string", enum: ["generate", "edit", "inpaint"] },
|
|
701
|
+
references: {
|
|
702
|
+
type: "array",
|
|
703
|
+
items: {
|
|
704
|
+
type: "object",
|
|
705
|
+
properties: {
|
|
706
|
+
id: { type: "string", minLength: 1 },
|
|
707
|
+
role: { type: "string", enum: [...REFERENCE_ROLES] },
|
|
708
|
+
url: { type: "string" }
|
|
709
|
+
},
|
|
710
|
+
required: ["id", "role"],
|
|
711
|
+
additionalProperties: false
|
|
712
|
+
}
|
|
713
|
+
},
|
|
714
|
+
params: { type: "object", additionalProperties: { type: ["string", "number", "boolean"] } }
|
|
715
|
+
},
|
|
716
|
+
additionalProperties: false
|
|
717
|
+
};
|
|
718
|
+
var strategySchema = {
|
|
719
|
+
type: "string",
|
|
720
|
+
enum: STRATEGIES,
|
|
721
|
+
description: "How to handle unsupported values: nearest (snap/clamp, ties up), downgrade (ties down), upgrade (ties up, never drops references), error (change nothing)."
|
|
722
|
+
};
|
|
723
|
+
function stableStringify(value) {
|
|
724
|
+
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
|
|
725
|
+
if (value && typeof value === "object") {
|
|
726
|
+
const entries = Object.keys(value).filter((key) => value[key] !== void 0).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`);
|
|
727
|
+
return `{${entries.join(",")}}`;
|
|
728
|
+
}
|
|
729
|
+
return JSON.stringify(value) ?? "null";
|
|
730
|
+
}
|
|
731
|
+
function planFailure(plan) {
|
|
732
|
+
return {
|
|
733
|
+
isError: true,
|
|
734
|
+
content: [
|
|
735
|
+
{
|
|
736
|
+
type: "text",
|
|
737
|
+
text: `The request cannot be sent to "${plan.model}":
|
|
738
|
+
${plan.errors.map((e) => `- ${e.field}: ${e.message}`).join("\n")}`
|
|
739
|
+
}
|
|
740
|
+
],
|
|
741
|
+
structuredContent: { error: { code: "plan_failed", message: "Request planning failed." }, plan }
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
function createGenerationToolProvider(options) {
|
|
745
|
+
const readModels = () => typeof options.models === "function" ? options.models() : options.models;
|
|
746
|
+
const defaultStrategy = options.defaultStrategy ?? "nearest";
|
|
747
|
+
const maxKeys = Math.max(1, options.maxIdempotencyKeys ?? 500);
|
|
748
|
+
const calls = /* @__PURE__ */ new Map();
|
|
749
|
+
const findModel = (id) => {
|
|
750
|
+
const model = readModels().find((m) => m.id === id);
|
|
751
|
+
if (!model) throw new Error(`Unknown model "${String(id)}". Call list_models for the available ids.`);
|
|
752
|
+
return model;
|
|
753
|
+
};
|
|
754
|
+
const plan = (args) => {
|
|
755
|
+
const model = findModel(args.model);
|
|
756
|
+
const request = { ...args.request ?? {}, model: model.id };
|
|
757
|
+
return {
|
|
758
|
+
model,
|
|
759
|
+
plan: planGenerationRequest(request, model, {
|
|
760
|
+
strategy: args.strategy ?? defaultStrategy,
|
|
761
|
+
resolvedPrompt: args.resolvedPrompt
|
|
762
|
+
})
|
|
763
|
+
};
|
|
764
|
+
};
|
|
765
|
+
const planInput = () => {
|
|
766
|
+
const ids = readModels().map((m) => m.id);
|
|
767
|
+
return {
|
|
768
|
+
type: "object",
|
|
769
|
+
properties: {
|
|
770
|
+
model: { type: "string", ...ids.length ? { enum: ids } : {}, description: "Model id from list_models." },
|
|
771
|
+
request: requestSchema,
|
|
772
|
+
strategy: strategySchema,
|
|
773
|
+
resolvedPrompt: {
|
|
774
|
+
type: "string",
|
|
775
|
+
description: "The prompt with templates and variables resolved, when `request.prompt` is a template."
|
|
776
|
+
}
|
|
777
|
+
},
|
|
778
|
+
required: ["model", "request"],
|
|
779
|
+
additionalProperties: false
|
|
780
|
+
};
|
|
781
|
+
};
|
|
782
|
+
const tools = () => {
|
|
783
|
+
const list2 = [
|
|
784
|
+
{
|
|
785
|
+
name: "list_models",
|
|
786
|
+
title: "List generation models",
|
|
787
|
+
description: "Lists the available generation models with their media kind, description and the JSON Schema of the request each accepts.",
|
|
788
|
+
inputSchema: {
|
|
789
|
+
type: "object",
|
|
790
|
+
properties: {
|
|
791
|
+
media: { type: "string", enum: ["image", "video", "audio", "text"], description: "Only models of this kind." }
|
|
792
|
+
},
|
|
793
|
+
additionalProperties: false
|
|
794
|
+
},
|
|
795
|
+
annotations: {
|
|
796
|
+
title: "List generation models",
|
|
797
|
+
readOnlyHint: true,
|
|
798
|
+
destructiveHint: false,
|
|
799
|
+
idempotentHint: true,
|
|
800
|
+
openWorldHint: false
|
|
801
|
+
},
|
|
802
|
+
handler: (args) => ({
|
|
803
|
+
models: readModels().filter((m) => !args.media || m.media === args.media).map((m) => ({
|
|
804
|
+
id: m.id,
|
|
805
|
+
media: m.media,
|
|
806
|
+
...m.name ? { name: m.name } : {},
|
|
807
|
+
...m.description ? { description: m.description } : {},
|
|
808
|
+
...m.badges?.length ? { badges: [...m.badges] } : {},
|
|
809
|
+
requestSchema: capabilitiesToJsonSchema(m)
|
|
810
|
+
}))
|
|
811
|
+
})
|
|
812
|
+
},
|
|
813
|
+
{
|
|
814
|
+
name: "plan_generation",
|
|
815
|
+
title: "Plan a generation request",
|
|
816
|
+
description: "Checks a request against a model without generating: returns the adjusted request, every adjustment (field, from, to, reason) and errors.",
|
|
817
|
+
inputSchema: planInput(),
|
|
818
|
+
annotations: {
|
|
819
|
+
title: "Plan a generation request",
|
|
820
|
+
readOnlyHint: true,
|
|
821
|
+
destructiveHint: false,
|
|
822
|
+
idempotentHint: true,
|
|
823
|
+
openWorldHint: false
|
|
824
|
+
},
|
|
825
|
+
handler: (args) => ({ plan: plan(args).plan })
|
|
826
|
+
}
|
|
827
|
+
];
|
|
828
|
+
if (options.estimate) {
|
|
829
|
+
const estimate = options.estimate;
|
|
830
|
+
list2.push({
|
|
831
|
+
name: "estimate_generation",
|
|
832
|
+
title: "Estimate a generation",
|
|
833
|
+
description: "Estimates cost and/or time of a request after planning it. Does not generate anything.",
|
|
834
|
+
inputSchema: planInput(),
|
|
835
|
+
annotations: {
|
|
836
|
+
title: "Estimate a generation",
|
|
837
|
+
readOnlyHint: true,
|
|
838
|
+
destructiveHint: false,
|
|
839
|
+
idempotentHint: true,
|
|
840
|
+
openWorldHint: true
|
|
841
|
+
},
|
|
842
|
+
handler: async (args, context) => {
|
|
843
|
+
const planned = plan(args);
|
|
844
|
+
if (!planned.plan.ok) return planFailure(planned.plan);
|
|
845
|
+
const value = await estimate(planned.plan.request, { ...planned, signal: context.signal });
|
|
846
|
+
return { plan: planned.plan, estimate: value };
|
|
847
|
+
}
|
|
848
|
+
});
|
|
849
|
+
}
|
|
850
|
+
const generateInput = planInput();
|
|
851
|
+
list2.push({
|
|
852
|
+
name: "generate",
|
|
853
|
+
title: "Generate media",
|
|
854
|
+
description: "Plans the request and starts a generation. Pass a fresh `idempotencyKey` per intended generation and reuse it when retrying, so a retry never generates twice.",
|
|
855
|
+
inputSchema: {
|
|
856
|
+
...generateInput,
|
|
857
|
+
properties: {
|
|
858
|
+
...generateInput.properties,
|
|
859
|
+
idempotencyKey: {
|
|
860
|
+
type: "string",
|
|
861
|
+
minLength: 1,
|
|
862
|
+
maxLength: 200,
|
|
863
|
+
description: "Unique per intended generation; reuse it to retry safely."
|
|
864
|
+
}
|
|
865
|
+
},
|
|
866
|
+
required: ["model", "request", "idempotencyKey"]
|
|
867
|
+
},
|
|
868
|
+
annotations: {
|
|
869
|
+
title: "Generate media",
|
|
870
|
+
readOnlyHint: false,
|
|
871
|
+
destructiveHint: true,
|
|
872
|
+
idempotentHint: true,
|
|
873
|
+
openWorldHint: true
|
|
874
|
+
},
|
|
875
|
+
handler: async (args, context) => {
|
|
876
|
+
const key = String(args.idempotencyKey);
|
|
877
|
+
const { idempotencyKey: _key, ...rest } = args;
|
|
878
|
+
const signature = stableStringify(rest);
|
|
879
|
+
const existing = calls.get(key);
|
|
880
|
+
if (existing) {
|
|
881
|
+
if (existing.signature !== signature) {
|
|
882
|
+
throw new Error(
|
|
883
|
+
`Idempotency key "${key}" was already used with different arguments. Use a new key for a new generation.`
|
|
884
|
+
);
|
|
885
|
+
}
|
|
886
|
+
return { ...await existing.result, deduplicated: true };
|
|
887
|
+
}
|
|
888
|
+
const planned = plan(args);
|
|
889
|
+
if (!planned.plan.ok) return planFailure(planned.plan);
|
|
890
|
+
const result = Promise.resolve().then(
|
|
891
|
+
() => options.generate(planned.plan.request, {
|
|
892
|
+
...planned,
|
|
893
|
+
idempotencyKey: key,
|
|
894
|
+
signal: context.signal
|
|
895
|
+
})
|
|
896
|
+
).then((value) => ({
|
|
897
|
+
result: value,
|
|
898
|
+
plan: planned.plan,
|
|
899
|
+
idempotencyKey: key
|
|
900
|
+
}));
|
|
901
|
+
calls.set(key, { signature, result });
|
|
902
|
+
while (calls.size > maxKeys) calls.delete(calls.keys().next().value);
|
|
903
|
+
try {
|
|
904
|
+
return await result;
|
|
905
|
+
} catch (error) {
|
|
906
|
+
if (calls.get(key)?.result === result) calls.delete(key);
|
|
907
|
+
throw error;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
});
|
|
911
|
+
return list2;
|
|
912
|
+
};
|
|
913
|
+
return {
|
|
914
|
+
id: options.id ?? "generation",
|
|
915
|
+
...options.namespace ? { namespace: options.namespace } : {},
|
|
916
|
+
tools,
|
|
917
|
+
...options.subscribe ? { subscribe: options.subscribe } : {},
|
|
918
|
+
clearIdempotencyKeys(key) {
|
|
919
|
+
if (key === void 0) calls.clear();
|
|
920
|
+
else calls.delete(key);
|
|
921
|
+
}
|
|
922
|
+
};
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
// src/generation/provenance.ts
|
|
926
|
+
var PROVENANCE_FORMAT = "pixerate.generation-provenance";
|
|
927
|
+
var PROVENANCE_VERSION = 1;
|
|
928
|
+
var ProvenanceParseError = class extends Error {
|
|
929
|
+
constructor(message) {
|
|
930
|
+
super(message);
|
|
931
|
+
this.name = "ProvenanceParseError";
|
|
932
|
+
}
|
|
933
|
+
};
|
|
934
|
+
var toIso = (value) => new Date(value).toISOString();
|
|
935
|
+
var clone = (value) => value === void 0 ? value : JSON.parse(JSON.stringify(value));
|
|
936
|
+
function pinTemplates(rawPrompt, templates, bindings, maxDepth) {
|
|
937
|
+
const byName = new Map(templates.map((t) => [t.name, t]));
|
|
938
|
+
const pinned = /* @__PURE__ */ new Map();
|
|
939
|
+
const visit = (text, depth) => {
|
|
940
|
+
if (depth > maxDepth) return;
|
|
941
|
+
for (const token of tokenizePrompt(text)) {
|
|
942
|
+
if (token.type !== "template" || pinned.has(token.value)) continue;
|
|
943
|
+
const template = byName.get(token.value);
|
|
944
|
+
if (!template) continue;
|
|
945
|
+
const body = getTemplateBody(template, bindings);
|
|
946
|
+
if (body === void 0) continue;
|
|
947
|
+
const bound = bindings[template.name];
|
|
948
|
+
const version = bound && template.versions ? template.versions.find((v) => v.id === bound || v.version === bound) : getLatestVersion(template);
|
|
949
|
+
const isVersioned = !!template.versions?.length && !!version;
|
|
950
|
+
pinned.set(template.name, {
|
|
951
|
+
name: template.name,
|
|
952
|
+
...template.id !== void 0 ? { templateId: template.id } : {},
|
|
953
|
+
...isVersioned ? { versionId: version.id, version: version.version } : {},
|
|
954
|
+
body
|
|
955
|
+
});
|
|
956
|
+
visit(body, depth + 1);
|
|
957
|
+
}
|
|
958
|
+
};
|
|
959
|
+
visit(rawPrompt, 0);
|
|
960
|
+
return [...pinned.values()];
|
|
961
|
+
}
|
|
962
|
+
function pinnedTemplatesToTemplates(pinned) {
|
|
963
|
+
return pinned.map(
|
|
964
|
+
(p) => p.versionId !== void 0 ? {
|
|
965
|
+
...p.templateId !== void 0 ? { id: p.templateId } : {},
|
|
966
|
+
name: p.name,
|
|
967
|
+
latestVersion: p.version,
|
|
968
|
+
versions: [{ id: p.versionId, version: p.version ?? p.versionId, body: p.body }]
|
|
969
|
+
} : { ...p.templateId !== void 0 ? { id: p.templateId } : {}, name: p.name, body: p.body }
|
|
970
|
+
);
|
|
971
|
+
}
|
|
972
|
+
function createProvenance(options) {
|
|
973
|
+
const templates = options.templates ?? [];
|
|
974
|
+
const maxDepth = options.maxDepth ?? 10;
|
|
975
|
+
const resolved = resolvePrompt(options.rawPrompt, templates, {
|
|
976
|
+
bindings: options.bindings,
|
|
977
|
+
values: options.values,
|
|
978
|
+
maxDepth
|
|
979
|
+
});
|
|
980
|
+
const pinned = pinTemplates(options.rawPrompt, templates, options.bindings ?? {}, maxDepth);
|
|
981
|
+
const bindings = {};
|
|
982
|
+
for (const p of pinned) if (p.versionId !== void 0) bindings[p.name] = p.versionId;
|
|
983
|
+
const modelId = typeof options.model === "string" ? options.model : options.model.id;
|
|
984
|
+
const request = clone(options.plan?.request ?? options.request ?? {});
|
|
985
|
+
request.model = modelId;
|
|
986
|
+
if (request.prompt === void 0) request.prompt = resolved.text;
|
|
987
|
+
const adjustments = clone(options.adjustments ?? options.plan?.adjustments ?? []);
|
|
988
|
+
return {
|
|
989
|
+
format: PROVENANCE_FORMAT,
|
|
990
|
+
version: PROVENANCE_VERSION,
|
|
991
|
+
rawPrompt: options.rawPrompt,
|
|
992
|
+
templates: pinned,
|
|
993
|
+
bindings,
|
|
994
|
+
values: options.values ? clone(options.values) : null,
|
|
995
|
+
resolvedPrompt: resolved.text,
|
|
996
|
+
sourceMap: resolved.map.map((segment) => {
|
|
997
|
+
const { locked: _locked, ...rest } = segment;
|
|
998
|
+
return rest;
|
|
999
|
+
}),
|
|
1000
|
+
modelId,
|
|
1001
|
+
request,
|
|
1002
|
+
adjustments,
|
|
1003
|
+
references: (request.references ?? []).map(({ id, role }) => ({ id, role })),
|
|
1004
|
+
createdAt: toIso(options.createdAt ?? Date.now()),
|
|
1005
|
+
...options.startedAt !== void 0 ? { startedAt: toIso(options.startedAt) } : {},
|
|
1006
|
+
...options.completedAt !== void 0 ? { completedAt: toIso(options.completedAt) } : {},
|
|
1007
|
+
...options.outputIds ? { outputIds: [...options.outputIds] } : {},
|
|
1008
|
+
...options.meta ? { meta: clone(options.meta) } : {}
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
function serializeProvenance(provenance) {
|
|
1012
|
+
return JSON.stringify(provenance);
|
|
1013
|
+
}
|
|
1014
|
+
var isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
1015
|
+
function parseProvenance(input) {
|
|
1016
|
+
let data = input;
|
|
1017
|
+
if (typeof input === "string") {
|
|
1018
|
+
try {
|
|
1019
|
+
data = JSON.parse(input);
|
|
1020
|
+
} catch {
|
|
1021
|
+
throw new ProvenanceParseError("Provenance is not valid JSON.");
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
if (!isRecord(data) || data.format !== PROVENANCE_FORMAT) {
|
|
1025
|
+
throw new ProvenanceParseError("Not a generation provenance record.");
|
|
1026
|
+
}
|
|
1027
|
+
if (typeof data.version !== "number" || data.version > PROVENANCE_VERSION) {
|
|
1028
|
+
throw new ProvenanceParseError(`Unsupported provenance version ${JSON.stringify(data.version)}.`);
|
|
1029
|
+
}
|
|
1030
|
+
const checks = [
|
|
1031
|
+
["rawPrompt", typeof data.rawPrompt === "string"],
|
|
1032
|
+
["resolvedPrompt", typeof data.resolvedPrompt === "string"],
|
|
1033
|
+
["modelId", typeof data.modelId === "string"],
|
|
1034
|
+
["createdAt", typeof data.createdAt === "string"],
|
|
1035
|
+
["request", isRecord(data.request)],
|
|
1036
|
+
["templates", Array.isArray(data.templates) && data.templates.every((t) => isRecord(t) && typeof t.name === "string" && typeof t.body === "string")],
|
|
1037
|
+
["sourceMap", Array.isArray(data.sourceMap)],
|
|
1038
|
+
["adjustments", Array.isArray(data.adjustments)],
|
|
1039
|
+
["references", Array.isArray(data.references)]
|
|
1040
|
+
];
|
|
1041
|
+
const bad = checks.find(([, ok]) => !ok);
|
|
1042
|
+
if (bad) throw new ProvenanceParseError(`Invalid provenance field "${bad[0]}".`);
|
|
1043
|
+
return {
|
|
1044
|
+
...data,
|
|
1045
|
+
bindings: isRecord(data.bindings) ? data.bindings : {},
|
|
1046
|
+
values: isRecord(data.values) ? data.values : null
|
|
1047
|
+
};
|
|
1048
|
+
}
|
|
1049
|
+
function recreateRequest(provenance) {
|
|
1050
|
+
const request = clone(provenance.request);
|
|
1051
|
+
request.model = provenance.modelId;
|
|
1052
|
+
if (request.prompt === void 0) request.prompt = provenance.resolvedPrompt;
|
|
1053
|
+
return request;
|
|
1054
|
+
}
|
|
1055
|
+
function replayProvenancePrompt(provenance) {
|
|
1056
|
+
const result = resolvePrompt(provenance.rawPrompt, pinnedTemplatesToTemplates(provenance.templates), {
|
|
1057
|
+
bindings: provenance.bindings,
|
|
1058
|
+
...provenance.values ? { values: provenance.values } : {}
|
|
1059
|
+
});
|
|
1060
|
+
return { text: result.text, map: result.map, matches: result.text === provenance.resolvedPrompt };
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
// src/generation/batch.ts
|
|
1064
|
+
function createBatchResolver(options) {
|
|
1065
|
+
const maxBatch = Math.max(1, Math.floor(options.maxBatch ?? 50));
|
|
1066
|
+
const delayMs = Math.max(0, options.delayMs ?? 0);
|
|
1067
|
+
const settled = /* @__PURE__ */ new Map();
|
|
1068
|
+
const failures = /* @__PURE__ */ new Set();
|
|
1069
|
+
const inFlight = /* @__PURE__ */ new Map();
|
|
1070
|
+
let queue = [];
|
|
1071
|
+
let timer = null;
|
|
1072
|
+
const run = (keys) => {
|
|
1073
|
+
const pendings = keys.map((key) => inFlight.get(key));
|
|
1074
|
+
const finish = (values, error) => {
|
|
1075
|
+
if (values === null) options.onError?.(error, keys);
|
|
1076
|
+
keys.forEach((key, index) => {
|
|
1077
|
+
const pending = pendings[index];
|
|
1078
|
+
const value = values?.get(key);
|
|
1079
|
+
if (pending && inFlight.get(key) === pending) {
|
|
1080
|
+
inFlight.delete(key);
|
|
1081
|
+
settled.set(key, value);
|
|
1082
|
+
if (values === null) failures.add(key);
|
|
1083
|
+
}
|
|
1084
|
+
pending?.resolve(value);
|
|
1085
|
+
});
|
|
1086
|
+
};
|
|
1087
|
+
let promise;
|
|
1088
|
+
try {
|
|
1089
|
+
promise = Promise.resolve(options.fetch(keys));
|
|
1090
|
+
} catch (error) {
|
|
1091
|
+
promise = Promise.reject(error);
|
|
1092
|
+
}
|
|
1093
|
+
promise.then(
|
|
1094
|
+
(values) => finish(values instanceof Map ? values : /* @__PURE__ */ new Map()),
|
|
1095
|
+
(error) => finish(null, error ?? new Error("Batch fetch failed."))
|
|
1096
|
+
);
|
|
1097
|
+
};
|
|
1098
|
+
const flush = () => {
|
|
1099
|
+
if (timer !== null) clearTimeout(timer);
|
|
1100
|
+
timer = null;
|
|
1101
|
+
const keys = queue;
|
|
1102
|
+
queue = [];
|
|
1103
|
+
for (let i = 0; i < keys.length; i += maxBatch) run(keys.slice(i, i + maxBatch));
|
|
1104
|
+
};
|
|
1105
|
+
const load = (key) => {
|
|
1106
|
+
if (settled.has(key)) return Promise.resolve(settled.get(key));
|
|
1107
|
+
const existing = inFlight.get(key);
|
|
1108
|
+
if (existing) return existing.promise;
|
|
1109
|
+
let resolve;
|
|
1110
|
+
const promise = new Promise((r) => resolve = r);
|
|
1111
|
+
inFlight.set(key, { promise, resolve });
|
|
1112
|
+
queue.push(key);
|
|
1113
|
+
if (queue.length >= maxBatch) flush();
|
|
1114
|
+
else if (timer === null) timer = setTimeout(flush, delayMs);
|
|
1115
|
+
return promise;
|
|
1116
|
+
};
|
|
1117
|
+
return {
|
|
1118
|
+
load,
|
|
1119
|
+
loadMany: (keys) => Promise.all(keys.map(load)),
|
|
1120
|
+
peek: (key) => settled.get(key),
|
|
1121
|
+
has: (key) => settled.has(key),
|
|
1122
|
+
failed: (key) => failures.has(key),
|
|
1123
|
+
prime(key, value) {
|
|
1124
|
+
settled.set(key, value);
|
|
1125
|
+
failures.delete(key);
|
|
1126
|
+
},
|
|
1127
|
+
clear(key) {
|
|
1128
|
+
if (key === void 0) {
|
|
1129
|
+
settled.clear();
|
|
1130
|
+
failures.clear();
|
|
1131
|
+
for (const k of [...inFlight.keys()]) if (!queue.includes(k)) inFlight.delete(k);
|
|
1132
|
+
return;
|
|
1133
|
+
}
|
|
1134
|
+
settled.delete(key);
|
|
1135
|
+
failures.delete(key);
|
|
1136
|
+
if (!queue.includes(key)) inFlight.delete(key);
|
|
1137
|
+
},
|
|
1138
|
+
flush
|
|
1139
|
+
};
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
// src/generation/progress.ts
|
|
1143
|
+
var MAX_PENDING_PERCENT = 95;
|
|
1144
|
+
var ALMOST_DONE_MS = 5e3;
|
|
1145
|
+
var UNKNOWN_DURATION_TAU_MS = 3e4;
|
|
1146
|
+
var toMs = (value) => typeof value === "number" ? value : new Date(value).getTime();
|
|
1147
|
+
function formatRemaining(ms) {
|
|
1148
|
+
const seconds = Math.ceil(ms / 1e3);
|
|
1149
|
+
if (seconds < 60) return `~${Math.max(1, seconds)}s left`;
|
|
1150
|
+
const minutes = Math.ceil(ms / 6e4);
|
|
1151
|
+
if (minutes < 60) return `~${minutes}m left`;
|
|
1152
|
+
const hours = Math.floor(minutes / 60);
|
|
1153
|
+
const rest = minutes % 60;
|
|
1154
|
+
return rest ? `~${hours}h ${rest}m left` : `~${hours}h left`;
|
|
1155
|
+
}
|
|
1156
|
+
function estimateJobProgress(input) {
|
|
1157
|
+
const started = toMs(input.startedAt);
|
|
1158
|
+
const now = toMs(input.now ?? Date.now());
|
|
1159
|
+
const elapsedMs = Math.max(0, now - started);
|
|
1160
|
+
if (input.done) return { percent: 100, label: "Done", elapsedMs, remainingMs: 0, overdue: false };
|
|
1161
|
+
if (!Number.isFinite(started) || now <= started) {
|
|
1162
|
+
return { percent: 0, label: "Starting\u2026", elapsedMs: 0, ...input.expectedMs ? { remainingMs: input.expectedMs } : {}, overdue: false };
|
|
1163
|
+
}
|
|
1164
|
+
const expected = input.expectedMs;
|
|
1165
|
+
if (!expected || !(expected > 0)) {
|
|
1166
|
+
const percent2 = MAX_PENDING_PERCENT * (1 - Math.exp(-elapsedMs / UNKNOWN_DURATION_TAU_MS));
|
|
1167
|
+
return { percent: Math.floor(percent2), label: "Working\u2026", elapsedMs, overdue: false };
|
|
1168
|
+
}
|
|
1169
|
+
const remainingMs = Math.max(0, expected - elapsedMs);
|
|
1170
|
+
const percent = Math.min(MAX_PENDING_PERCENT, Math.floor(elapsedMs / expected * 100));
|
|
1171
|
+
return {
|
|
1172
|
+
percent,
|
|
1173
|
+
label: remainingMs <= ALMOST_DONE_MS ? "Almost done\u2026" : formatRemaining(remainingMs),
|
|
1174
|
+
elapsedMs,
|
|
1175
|
+
remainingMs,
|
|
1176
|
+
overdue: elapsedMs > expected
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
function expectedDurationFor(caps, request = {}) {
|
|
1180
|
+
const timing = caps.timing;
|
|
1181
|
+
if (!timing) return void 0;
|
|
1182
|
+
const count = request.count ?? caps.count?.default ?? 1;
|
|
1183
|
+
const duration = request.duration ?? caps.duration?.default ?? 0;
|
|
1184
|
+
const resolution = request.resolution ?? caps.resolutions?.default;
|
|
1185
|
+
const megapixels = resolution ? resolutionMegapixels(resolution) ?? 0 : 0;
|
|
1186
|
+
return Math.round(
|
|
1187
|
+
timing.baseMs + (timing.perItemMs ?? 0) * Math.max(0, count - 1) + (timing.perSecondMs ?? 0) * duration + (timing.perMegapixelMs ?? 0) * megapixels
|
|
1188
|
+
);
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
// src/generation/controls.ts
|
|
1192
|
+
function enumControl(key, label, cap) {
|
|
1193
|
+
if (!cap?.options.length) return null;
|
|
1194
|
+
return {
|
|
1195
|
+
key,
|
|
1196
|
+
label,
|
|
1197
|
+
kind: "select",
|
|
1198
|
+
valueType: "string",
|
|
1199
|
+
options: cap.options.map((value) => ({ value, label: cap.labels?.[value] ?? value })),
|
|
1200
|
+
...cap.default !== void 0 ? { defaultValue: cap.default } : {}
|
|
1201
|
+
};
|
|
1202
|
+
}
|
|
1203
|
+
function getGenerationControls(caps) {
|
|
1204
|
+
const controls = [];
|
|
1205
|
+
const modes = supportedModes(caps);
|
|
1206
|
+
if (modes.length > 1) {
|
|
1207
|
+
controls.push({
|
|
1208
|
+
key: "mode",
|
|
1209
|
+
label: "Mode",
|
|
1210
|
+
kind: "select",
|
|
1211
|
+
valueType: "string",
|
|
1212
|
+
options: modes.map((m) => ({ value: m, label: m[0].toUpperCase() + m.slice(1) })),
|
|
1213
|
+
defaultValue: "generate"
|
|
1214
|
+
});
|
|
1215
|
+
}
|
|
1216
|
+
const negative = textFieldCapability(caps.negativePrompt);
|
|
1217
|
+
if (negative) controls.push({ key: "negativePrompt", label: "Negative prompt", kind: "textarea", valueType: "string", maxLength: negative.maxLength });
|
|
1218
|
+
const system = textFieldCapability(caps.systemPrompt);
|
|
1219
|
+
if (system) controls.push({ key: "systemPrompt", label: "System prompt", kind: "textarea", valueType: "string", maxLength: system.maxLength });
|
|
1220
|
+
controls.push(enumControl("aspectRatio", "Aspect ratio", caps.aspectRatios));
|
|
1221
|
+
controls.push(enumControl("resolution", "Resolution", caps.resolutions));
|
|
1222
|
+
controls.push(enumControl("quality", "Quality", caps.quality));
|
|
1223
|
+
if (caps.count) {
|
|
1224
|
+
const options = caps.count.options?.filter((o) => o >= 1 && o <= caps.count.max);
|
|
1225
|
+
controls.push(
|
|
1226
|
+
options?.length ? { key: "count", label: "Outputs", kind: "select", valueType: "number", options: options.map((o) => ({ value: o, label: String(o) })), defaultValue: caps.count.default } : { key: "count", label: "Outputs", kind: "range", valueType: "number", min: 1, max: caps.count.max, step: 1, defaultValue: caps.count.default ?? 1 }
|
|
1227
|
+
);
|
|
1228
|
+
}
|
|
1229
|
+
if (caps.duration) {
|
|
1230
|
+
const d = caps.duration;
|
|
1231
|
+
const options = d.options?.filter((o) => (d.min === void 0 || o >= d.min) && (d.max === void 0 || o <= d.max));
|
|
1232
|
+
controls.push(
|
|
1233
|
+
options?.length ? { key: "duration", label: "Duration (s)", kind: "select", valueType: "number", options: options.map((o) => ({ value: o, label: `${o}s` })), defaultValue: d.default } : {
|
|
1234
|
+
key: "duration",
|
|
1235
|
+
label: "Duration (s)",
|
|
1236
|
+
kind: d.min !== void 0 && d.max !== void 0 ? "range" : "number",
|
|
1237
|
+
valueType: "number",
|
|
1238
|
+
min: d.min,
|
|
1239
|
+
max: d.max,
|
|
1240
|
+
step: d.step,
|
|
1241
|
+
defaultValue: d.default
|
|
1242
|
+
}
|
|
1243
|
+
);
|
|
1244
|
+
}
|
|
1245
|
+
const seed = seedCapability(caps.seed);
|
|
1246
|
+
if (seed) controls.push({ key: "seed", label: "Seed", kind: "number", valueType: "number", min: seed.min, max: seed.max, step: 1 });
|
|
1247
|
+
for (const [name, spec] of Object.entries(caps.params ?? {})) {
|
|
1248
|
+
const base = { key: `params.${name}`, label: spec.label ?? name, ...spec.description ? { description: spec.description } : {} };
|
|
1249
|
+
if (spec.type === "boolean") {
|
|
1250
|
+
controls.push({ ...base, kind: "checkbox", valueType: "boolean", defaultValue: spec.default });
|
|
1251
|
+
} else if (spec.type === "enum") {
|
|
1252
|
+
const numeric = spec.options.every((o) => typeof o === "number");
|
|
1253
|
+
controls.push({
|
|
1254
|
+
...base,
|
|
1255
|
+
kind: "select",
|
|
1256
|
+
valueType: numeric ? "number" : "string",
|
|
1257
|
+
options: spec.options.map((value) => ({ value, label: String(value) })),
|
|
1258
|
+
defaultValue: spec.default
|
|
1259
|
+
});
|
|
1260
|
+
} else {
|
|
1261
|
+
controls.push({
|
|
1262
|
+
...base,
|
|
1263
|
+
kind: spec.min !== void 0 && spec.max !== void 0 ? "range" : "number",
|
|
1264
|
+
valueType: "number",
|
|
1265
|
+
min: spec.min,
|
|
1266
|
+
max: spec.max,
|
|
1267
|
+
step: spec.step ?? (spec.type === "integer" ? 1 : void 0),
|
|
1268
|
+
defaultValue: spec.default
|
|
1269
|
+
});
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
return controls.filter((c) => c !== null);
|
|
1273
|
+
}
|
|
1274
|
+
function getRequestValue(request, key) {
|
|
1275
|
+
if (key.startsWith("params.")) return request.params?.[key.slice(7)];
|
|
1276
|
+
return request[key];
|
|
1277
|
+
}
|
|
1278
|
+
function setRequestValue(request, key, value) {
|
|
1279
|
+
const remove = value === void 0 || value === "" || typeof value === "number" && Number.isNaN(value);
|
|
1280
|
+
if (key.startsWith("params.")) {
|
|
1281
|
+
const name = key.slice(7);
|
|
1282
|
+
const params = { ...request.params ?? {} };
|
|
1283
|
+
if (remove) delete params[name];
|
|
1284
|
+
else params[name] = value;
|
|
1285
|
+
const next2 = { ...request, params };
|
|
1286
|
+
if (Object.keys(params).length === 0) delete next2.params;
|
|
1287
|
+
return next2;
|
|
1288
|
+
}
|
|
1289
|
+
const next = { ...request };
|
|
1290
|
+
if (remove) delete next[key];
|
|
1291
|
+
else next[key] = value;
|
|
1292
|
+
return next;
|
|
1293
|
+
}
|
|
1294
|
+
function parseControlValue(control, raw) {
|
|
1295
|
+
if (control.valueType === "boolean") return Boolean(raw);
|
|
1296
|
+
if (raw === "" || raw === void 0) return void 0;
|
|
1297
|
+
if (control.valueType === "number") {
|
|
1298
|
+
const n = Number(raw);
|
|
1299
|
+
return Number.isFinite(n) ? n : void 0;
|
|
1300
|
+
}
|
|
1301
|
+
return String(raw);
|
|
1302
|
+
}
|
|
1303
|
+
function getReferenceSlots(caps, request = {}) {
|
|
1304
|
+
const roles = supportedReferenceRoles(caps);
|
|
1305
|
+
if (caps.inpainting && !roles.includes("mask")) roles.push("mask");
|
|
1306
|
+
const refs = request.references ?? [];
|
|
1307
|
+
const total = refs.length;
|
|
1308
|
+
const maxTotal = caps.references?.maxTotal ?? Infinity;
|
|
1309
|
+
return roles.map((role) => {
|
|
1310
|
+
const cap = caps.references?.roles[role] ?? { max: 1 };
|
|
1311
|
+
const references = refs.filter((ref) => ref.role === role);
|
|
1312
|
+
return {
|
|
1313
|
+
role,
|
|
1314
|
+
label: cap.label ?? REFERENCE_ROLE_LABELS[role],
|
|
1315
|
+
...cap.description ? { description: cap.description } : {},
|
|
1316
|
+
min: cap.min ?? 0,
|
|
1317
|
+
max: cap.max,
|
|
1318
|
+
references,
|
|
1319
|
+
canAdd: references.length < cap.max && total < maxTotal
|
|
1320
|
+
};
|
|
1321
|
+
});
|
|
1322
|
+
}
|
|
1323
|
+
function addReference(request, reference) {
|
|
1324
|
+
return { ...request, references: [...request.references ?? [], { ...reference }] };
|
|
1325
|
+
}
|
|
1326
|
+
function removeReference(request, role, id) {
|
|
1327
|
+
const references = (request.references ?? []).filter((ref) => !(ref.role === role && ref.id === id));
|
|
1328
|
+
const next = { ...request, references };
|
|
1329
|
+
if (references.length === 0) delete next.references;
|
|
1330
|
+
return next;
|
|
1331
|
+
}
|
|
1332
|
+
export {
|
|
1333
|
+
GENERATION_REQUEST_FIELDS,
|
|
1334
|
+
MAX_PENDING_PERCENT,
|
|
1335
|
+
PROVENANCE_FORMAT,
|
|
1336
|
+
PROVENANCE_VERSION,
|
|
1337
|
+
ProvenanceParseError,
|
|
1338
|
+
QUALITY_LADDER,
|
|
1339
|
+
REFERENCE_ROLES,
|
|
1340
|
+
REFERENCE_ROLE_LABELS,
|
|
1341
|
+
addReference,
|
|
1342
|
+
aspectRatioRank,
|
|
1343
|
+
capabilitiesToJsonSchema,
|
|
1344
|
+
createBatchResolver,
|
|
1345
|
+
createGenerationToolProvider,
|
|
1346
|
+
createProvenance,
|
|
1347
|
+
estimateJobProgress,
|
|
1348
|
+
expectedDurationFor,
|
|
1349
|
+
formatRemaining,
|
|
1350
|
+
getGenerationControls,
|
|
1351
|
+
getReferenceSlots,
|
|
1352
|
+
getRequestValue,
|
|
1353
|
+
mergeCapabilities,
|
|
1354
|
+
parseControlValue,
|
|
1355
|
+
parseProvenance,
|
|
1356
|
+
pinnedTemplatesToTemplates,
|
|
1357
|
+
planGenerationRequest,
|
|
1358
|
+
qualityRank,
|
|
1359
|
+
recreateRequest,
|
|
1360
|
+
removeReference,
|
|
1361
|
+
replayProvenancePrompt,
|
|
1362
|
+
resolutionMegapixels,
|
|
1363
|
+
resolutionRank,
|
|
1364
|
+
seedCapability,
|
|
1365
|
+
serializeProvenance,
|
|
1366
|
+
setRequestValue,
|
|
1367
|
+
snapToOption,
|
|
1368
|
+
supportedModes,
|
|
1369
|
+
supportedReferenceRoles,
|
|
1370
|
+
textFieldCapability,
|
|
1371
|
+
validateJsonSchema
|
|
1372
|
+
};
|
|
1373
|
+
//# sourceMappingURL=index.js.map
|