@pixerate/editor 0.23.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.
Files changed (155) hide show
  1. package/README.md +96 -1
  2. package/THIRD_PARTY_NOTICES.md +51 -0
  3. package/dist/agent/index.cjs +9 -8
  4. package/dist/agent/index.cjs.map +1 -1
  5. package/dist/agent/index.d.cts +4 -3
  6. package/dist/agent/index.d.ts +4 -3
  7. package/dist/agent/index.js +3 -2
  8. package/dist/agent/index.js.map +1 -1
  9. package/dist/canvas/index.cjs +1210 -17
  10. package/dist/canvas/index.cjs.map +1 -1
  11. package/dist/canvas/index.d.cts +318 -1
  12. package/dist/canvas/index.d.ts +318 -1
  13. package/dist/canvas/index.js +1199 -6
  14. package/dist/canvas/index.js.map +1 -1
  15. package/dist/{chunk-QBJ22YZR.js → chunk-3CN2WD3X.js} +1354 -206
  16. package/dist/chunk-3CN2WD3X.js.map +1 -0
  17. package/dist/{chunk-JJDLPEWL.js → chunk-3LV6RRPH.js} +2 -2
  18. package/dist/{chunk-MJZBNWG7.js → chunk-5S3Z4PPF.js} +78 -557
  19. package/dist/chunk-5S3Z4PPF.js.map +1 -0
  20. package/dist/chunk-664LQYFJ.js +115 -0
  21. package/dist/chunk-664LQYFJ.js.map +1 -0
  22. package/dist/{chunk-AA4ZEVCC.cjs → chunk-D27YFC46.cjs} +101 -580
  23. package/dist/chunk-D27YFC46.cjs.map +1 -0
  24. package/dist/chunk-D6FH2YAX.cjs +131 -0
  25. package/dist/chunk-D6FH2YAX.cjs.map +1 -0
  26. package/dist/{chunk-4SUNJZWB.cjs → chunk-FD4LPFAE.cjs} +48 -200
  27. package/dist/chunk-FD4LPFAE.cjs.map +1 -0
  28. package/dist/chunk-FODNLX5N.js +749 -0
  29. package/dist/chunk-FODNLX5N.js.map +1 -0
  30. package/dist/{chunk-OYXSKQFR.js → chunk-FPENXAEJ.js} +35 -187
  31. package/dist/chunk-FPENXAEJ.js.map +1 -0
  32. package/dist/chunk-HLIMTC6N.js +1 -0
  33. package/dist/chunk-HLIMTC6N.js.map +1 -0
  34. package/dist/{chunk-QGHGJ56O.js → chunk-ITBSKI26.js} +1483 -19
  35. package/dist/chunk-ITBSKI26.js.map +1 -0
  36. package/dist/{chunk-XDMXXC4Z.cjs → chunk-MA2F5KHF.cjs} +350 -227
  37. package/dist/chunk-MA2F5KHF.cjs.map +1 -0
  38. package/dist/{chunk-RIKBJLS2.cjs → chunk-MCSJFWAO.cjs} +1356 -208
  39. package/dist/chunk-MCSJFWAO.cjs.map +1 -0
  40. package/dist/chunk-MKA3AHLV.cjs +256 -0
  41. package/dist/chunk-MKA3AHLV.cjs.map +1 -0
  42. package/dist/chunk-OLZJXL4R.cjs +749 -0
  43. package/dist/chunk-OLZJXL4R.cjs.map +1 -0
  44. package/dist/chunk-OXSV64JX.js +689 -0
  45. package/dist/chunk-OXSV64JX.js.map +1 -0
  46. package/dist/chunk-P3RQ5UJE.cjs +689 -0
  47. package/dist/chunk-P3RQ5UJE.cjs.map +1 -0
  48. package/dist/chunk-P6ODPZ4W.js +256 -0
  49. package/dist/chunk-P6ODPZ4W.js.map +1 -0
  50. package/dist/chunk-PGNZKFQS.js +685 -0
  51. package/dist/chunk-PGNZKFQS.js.map +1 -0
  52. package/dist/chunk-PL4JB3BF.cjs +1 -0
  53. package/dist/chunk-PL4JB3BF.cjs.map +1 -0
  54. package/dist/{chunk-GVSMRPHB.cjs → chunk-SBCZ6RN5.cjs} +1568 -104
  55. package/dist/chunk-SBCZ6RN5.cjs.map +1 -0
  56. package/dist/{chunk-CL37JGFW.cjs → chunk-SML64VJG.cjs} +4 -4
  57. package/dist/{chunk-CL37JGFW.cjs.map → chunk-SML64VJG.cjs.map} +1 -1
  58. package/dist/chunk-TNNJXF46.cjs +115 -0
  59. package/dist/chunk-TNNJXF46.cjs.map +1 -0
  60. package/dist/chunk-U5HZSFCS.js +131 -0
  61. package/dist/chunk-U5HZSFCS.js.map +1 -0
  62. package/dist/{chunk-K3R5NG2D.js → chunk-U5KWZU4X.js} +251 -128
  63. package/dist/chunk-U5KWZU4X.js.map +1 -0
  64. package/dist/chunk-XNORY7M6.cjs +685 -0
  65. package/dist/chunk-XNORY7M6.cjs.map +1 -0
  66. package/dist/commands/index.d.cts +5 -353
  67. package/dist/commands/index.d.ts +5 -353
  68. package/dist/comment-store-BEMgVlAA.d.cts +135 -0
  69. package/dist/comment-store-BEMgVlAA.d.ts +135 -0
  70. package/dist/compare/index.cjs +15 -0
  71. package/dist/compare/index.cjs.map +1 -0
  72. package/dist/compare/index.d.cts +58 -0
  73. package/dist/compare/index.d.ts +58 -0
  74. package/dist/compare/index.js +15 -0
  75. package/dist/compare/index.js.map +1 -0
  76. package/dist/{controller-pePCJLT1.d.cts → controller-BhLLAoi8.d.cts} +45 -4
  77. package/dist/{controller-pePCJLT1.d.ts → controller-BhLLAoi8.d.ts} +45 -4
  78. package/dist/documents-BQjzJNe2.d.ts +76 -0
  79. package/dist/documents-KRTPhvst.d.cts +76 -0
  80. package/dist/extensions/index.cjs +53 -5
  81. package/dist/extensions/index.cjs.map +1 -1
  82. package/dist/extensions/index.d.cts +7 -3
  83. package/dist/extensions/index.d.ts +7 -3
  84. package/dist/extensions/index.js +52 -4
  85. package/dist/generation/index.cjs +1373 -0
  86. package/dist/generation/index.cjs.map +1 -0
  87. package/dist/generation/index.d.cts +554 -0
  88. package/dist/generation/index.d.ts +554 -0
  89. package/dist/generation/index.js +1373 -0
  90. package/dist/generation/index.js.map +1 -0
  91. package/dist/grammar/index.cjs +48 -3
  92. package/dist/grammar/index.cjs.map +1 -1
  93. package/dist/grammar/index.d.cts +322 -100
  94. package/dist/grammar/index.d.ts +322 -100
  95. package/dist/grammar/index.js +54 -9
  96. package/dist/image-editor/index.cjs +1831 -30
  97. package/dist/image-editor/index.cjs.map +1 -1
  98. package/dist/image-editor/index.d.cts +590 -3
  99. package/dist/image-editor/index.d.ts +590 -3
  100. package/dist/image-editor/index.js +1807 -6
  101. package/dist/image-editor/index.js.map +1 -1
  102. package/dist/{index-CCr_z9kF.d.cts → index-BhJBSm2d.d.cts} +370 -4
  103. package/dist/{index-Ck6ajwXh.d.ts → index-fJrlkJCd.d.ts} +370 -4
  104. package/dist/index.cjs +162 -25
  105. package/dist/index.cjs.map +1 -1
  106. package/dist/index.d.cts +14 -8
  107. package/dist/index.d.ts +14 -8
  108. package/dist/index.js +174 -37
  109. package/dist/index.js.map +1 -1
  110. package/dist/migrate-iTlm3a8h.d.cts +112 -0
  111. package/dist/migrate-iTlm3a8h.d.ts +112 -0
  112. package/dist/persistence/index.cjs +676 -0
  113. package/dist/persistence/index.cjs.map +1 -0
  114. package/dist/persistence/index.d.cts +347 -0
  115. package/dist/persistence/index.d.ts +347 -0
  116. package/dist/persistence/index.js +676 -0
  117. package/dist/persistence/index.js.map +1 -0
  118. package/dist/{registry-D5-R90p0.d.cts → registry-BDe-vlv3.d.ts} +2 -40
  119. package/dist/registry-D32LpIc4.d.cts +354 -0
  120. package/dist/{registry-D5-R90p0.d.ts → registry-DnzpgY27.d.cts} +2 -40
  121. package/dist/registry-evKTP4ls.d.ts +354 -0
  122. package/dist/schema-DYDGdYL9.d.cts +41 -0
  123. package/dist/schema-DYDGdYL9.d.ts +41 -0
  124. package/dist/serializers/index.cjs +4 -3
  125. package/dist/serializers/index.cjs.map +1 -1
  126. package/dist/serializers/index.d.cts +2 -1
  127. package/dist/serializers/index.d.ts +2 -1
  128. package/dist/serializers/index.js +3 -2
  129. package/dist/sourcemap-C8AH3MBQ.d.cts +91 -0
  130. package/dist/sourcemap-DA1Evhrv.d.ts +91 -0
  131. package/dist/spreadsheet/index.cjs +37 -3
  132. package/dist/spreadsheet/index.cjs.map +1 -1
  133. package/dist/spreadsheet/index.d.cts +188 -17
  134. package/dist/spreadsheet/index.d.ts +188 -17
  135. package/dist/spreadsheet/index.js +43 -9
  136. package/dist/{tokens-CyLZmIei.d.cts → tokens-D7yXvUU6.d.cts} +15 -2
  137. package/dist/{tokens-CyLZmIei.d.ts → tokens-D7yXvUU6.d.ts} +15 -2
  138. package/dist/{track-changes-BSF58RK0.d.ts → track-changes-BK5sVf4_.d.cts} +18 -136
  139. package/dist/{track-changes-BSF58RK0.d.cts → track-changes-CDjCrwKe.d.ts} +18 -136
  140. package/package.json +16 -1
  141. package/dist/chunk-4SUNJZWB.cjs.map +0 -1
  142. package/dist/chunk-AA4ZEVCC.cjs.map +0 -1
  143. package/dist/chunk-AXV2ZW34.cjs +0 -118
  144. package/dist/chunk-AXV2ZW34.cjs.map +0 -1
  145. package/dist/chunk-B2ZRLN4S.js +0 -118
  146. package/dist/chunk-B2ZRLN4S.js.map +0 -1
  147. package/dist/chunk-GVSMRPHB.cjs.map +0 -1
  148. package/dist/chunk-K3R5NG2D.js.map +0 -1
  149. package/dist/chunk-MJZBNWG7.js.map +0 -1
  150. package/dist/chunk-OYXSKQFR.js.map +0 -1
  151. package/dist/chunk-QBJ22YZR.js.map +0 -1
  152. package/dist/chunk-QGHGJ56O.js.map +0 -1
  153. package/dist/chunk-RIKBJLS2.cjs.map +0 -1
  154. package/dist/chunk-XDMXXC4Z.cjs.map +0 -1
  155. /package/dist/{chunk-JJDLPEWL.js.map → chunk-3LV6RRPH.js.map} +0 -0
@@ -0,0 +1,1373 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
2
+
3
+
4
+
5
+
6
+ var _chunkFD4LPFAEcjs = require('../chunk-FD4LPFAE.cjs');
7
+ require('../chunk-MKA3AHLV.cjs');
8
+
9
+
10
+ var _chunkCPOKFNBGcjs = require('../chunk-CPOKFNBG.cjs');
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 = _nullishCoalesce(_optionalChain([caps, 'access', _ => _.references, 'optionalAccess', _2 => _2.roles]), () => ( {}));
60
+ return REFERENCE_ROLES.filter((role) => (_nullishCoalesce(_optionalChain([roles, 'access', _3 => _3[role], 'optionalAccess', _4 => _4.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 _optionalChain([best, 'optionalAccess', _5 => _5.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 = class {
163
+ constructor(caps, request, options, strategy) {;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);
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
+
172
+
173
+
174
+
175
+ __init() {this.adjustments = []}
176
+ __init2() {this.errors = []}
177
+
178
+
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 = _nullishCoalesce(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 = _nullishCoalesce(_nullishCoalesce(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 = _optionalChain([spec, 'access', _6 => _6.options, 'optionalAccess', _7 => _7.filter, 'call', _8 => _8(
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 = _nullishCoalesce(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 = `${_nullishCoalesce(spec.min, () => ( "-\u221E"))}\u2013${_nullishCoalesce(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 = _optionalChain([this, 'access', _9 => _9.caps, 'access', _10 => _10.references, 'optionalAccess', _11 => _11.roles, 'access', _12 => _12[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 && (_nullishCoalesce(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 (_nullishCoalesce(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, (_nullishCoalesce(unsupported.get(ref.role), () => ( 0))) + 1);
372
+ continue;
373
+ }
374
+ const group = _nullishCoalesce(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 = _nullishCoalesce(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 = _optionalChain([this, 'access', _13 => _13.caps, 'access', _14 => _14.references, 'optionalAccess', _15 => _15.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 = _nullishCoalesce(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 = _nullishCoalesce(_nullishCoalesce(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 = _nullishCoalesce(this.caps.params, () => ( {}));
472
+ const next = {};
473
+ for (const [name, value] of Object.entries(_nullishCoalesce(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 = _nullishCoalesce(caps.prompt, () => ( {}));
506
+ if (promptCap.required && !(_nullishCoalesce(request.prompt, () => ( ""))).trim()) {
507
+ this.error("prompt", request.prompt, "A prompt is required.");
508
+ }
509
+ const countResolved = _nullishCoalesce(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
+ }, _class);
532
+ function planGenerationRequest(request, caps, options = {}) {
533
+ const strategy = _nullishCoalesce(options.strategy, () => ( "nearest"));
534
+ const planner = new Planner(caps, cloneRequest(_nullishCoalesce(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 = _nullishCoalesce(_nullishCoalesce(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 = _nullishCoalesce(caps.prompt, () => ( {}));
583
+ const countResolved = _nullishCoalesce(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 (_optionalChain([caps, 'access', _16 => _16.aspectRatios, 'optionalAccess', _17 => _17.options, 'access', _18 => _18.length])) properties.aspectRatio = enumSchema(caps.aspectRatios, "Aspect ratio (width:height).");
608
+ if (_optionalChain([caps, 'access', _19 => _19.resolutions, 'optionalAccess', _20 => _20.options, 'access', _21 => _21.length])) properties.resolution = enumSchema(caps.resolutions, "Output resolution, low to high.");
609
+ if (_optionalChain([caps, 'access', _22 => _22.quality, 'optionalAccess', _23 => _23.options, 'access', _24 => _24.length])) properties.quality = enumSchema(caps.quality, "Quality level, low to high.");
610
+ if (caps.count) {
611
+ const options = _optionalChain([caps, 'access', _25 => _25.count, 'access', _26 => _26.options, 'optionalAccess', _27 => _27.filter, 'call', _28 => _28((o) => o >= 1 && o <= caps.count.max)]);
612
+ properties.count = _optionalChain([options, 'optionalAccess', _29 => _29.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 = _optionalChain([d, 'access', _30 => _30.options, 'optionalAccess', _31 => _31.filter, 'call', _32 => _32((o) => (d.min === void 0 || o >= d.min) && (d.max === void 0 || o <= d.max))]);
618
+ properties.duration = _optionalChain([options, 'optionalAccess', _33 => _33.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 = _nullishCoalesce(_optionalChain([caps, 'access', _34 => _34.references, 'optionalAccess', _35 => _35.roles, 'access', _36 => _36[role]]), () => ( { max: 1 }));
644
+ const min = cap.min ? `${cap.min}\u2013` : "up to ";
645
+ return `${role} (${_nullishCoalesce(cap.label, () => ( REFERENCE_ROLE_LABELS[role]))}): ${min}${cap.max}`;
646
+ });
647
+ const perRoleTotal = roles.reduce((sum, role) => sum + (_nullishCoalesce(_optionalChain([caps, 'access', _37 => _37.references, 'optionalAccess', _38 => _38.roles, 'access', _39 => _39[role], 'optionalAccess', _40 => _40.max]), () => ( 1))), 0);
648
+ const maxItems = Math.min(_nullishCoalesce(_optionalChain([caps, 'access', _41 => _41.references, 'optionalAccess', _42 => _42.maxTotal]), () => ( Infinity)), perRoleTotal);
649
+ properties.references = {
650
+ type: "array",
651
+ description: `Reference inputs by role. Limits: ${limits.join("; ")}${_optionalChain([caps, 'access', _43 => _43.references, 'optionalAccess', _44 => _44.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) => (_nullishCoalesce(_optionalChain([caps, 'access', _45 => _45.references, 'optionalAccess', _46 => _46.roles, 'access', _47 => _47[role], 'optionalAccess', _48 => _48.min]), () => ( 0))) > 0)) required.push("references");
665
+ }
666
+ const params = Object.entries(_nullishCoalesce(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: _nullishCoalesce(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 _nullishCoalesce(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 = _nullishCoalesce(options.defaultStrategy, () => ( "nearest"));
747
+ const maxKeys = Math.max(1, _nullishCoalesce(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 = { ..._nullishCoalesce(args.request, () => ( {})), model: model.id };
757
+ return {
758
+ model,
759
+ plan: planGenerationRequest(request, model, {
760
+ strategy: _nullishCoalesce(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
+ ..._optionalChain([m, 'access', _49 => _49.badges, 'optionalAccess', _50 => _50.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 (_optionalChain([calls, 'access', _51 => _51.get, 'call', _52 => _52(key), 'optionalAccess', _53 => _53.result]) === result) calls.delete(key);
907
+ throw error;
908
+ }
909
+ }
910
+ });
911
+ return list2;
912
+ };
913
+ return {
914
+ id: _nullishCoalesce(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 _chunkFD4LPFAEcjs.tokenizePrompt.call(void 0, 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 = _chunkFD4LPFAEcjs.getTemplateBody.call(void 0, 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) : _chunkFD4LPFAEcjs.getLatestVersion.call(void 0, template);
949
+ const isVersioned = !!_optionalChain([template, 'access', _54 => _54.versions, 'optionalAccess', _55 => _55.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: _nullishCoalesce(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 = _nullishCoalesce(options.templates, () => ( []));
974
+ const maxDepth = _nullishCoalesce(options.maxDepth, () => ( 10));
975
+ const resolved = _chunkFD4LPFAEcjs.resolvePrompt.call(void 0, options.rawPrompt, templates, {
976
+ bindings: options.bindings,
977
+ values: options.values,
978
+ maxDepth
979
+ });
980
+ const pinned = pinTemplates(options.rawPrompt, templates, _nullishCoalesce(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(_nullishCoalesce(_nullishCoalesce(_optionalChain([options, 'access', _56 => _56.plan, 'optionalAccess', _57 => _57.request]), () => ( options.request)), () => ( {})));
985
+ request.model = modelId;
986
+ if (request.prompt === void 0) request.prompt = resolved.text;
987
+ const adjustments = clone(_nullishCoalesce(_nullishCoalesce(options.adjustments, () => ( _optionalChain([options, 'access', _58 => _58.plan, 'optionalAccess', _59 => _59.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: (_nullishCoalesce(request.references, () => ( []))).map(({ id, role }) => ({ id, role })),
1004
+ createdAt: toIso(_nullishCoalesce(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 (e2) {
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 = _chunkFD4LPFAEcjs.resolvePrompt.call(void 0, 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(_nullishCoalesce(options.maxBatch, () => ( 50))));
1066
+ const delayMs = Math.max(0, _nullishCoalesce(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) _optionalChain([options, 'access', _60 => _60.onError, 'optionalCall', _61 => _61(error, keys)]);
1076
+ keys.forEach((key, index) => {
1077
+ const pending = pendings[index];
1078
+ const value = _optionalChain([values, 'optionalAccess', _62 => _62.get, 'call', _63 => _63(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
+ _optionalChain([pending, 'optionalAccess', _64 => _64.resolve, 'call', _65 => _65(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, _nullishCoalesce(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(_nullishCoalesce(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 = _nullishCoalesce(_nullishCoalesce(request.count, () => ( _optionalChain([caps, 'access', _66 => _66.count, 'optionalAccess', _67 => _67.default]))), () => ( 1));
1183
+ const duration = _nullishCoalesce(_nullishCoalesce(request.duration, () => ( _optionalChain([caps, 'access', _68 => _68.duration, 'optionalAccess', _69 => _69.default]))), () => ( 0));
1184
+ const resolution = _nullishCoalesce(request.resolution, () => ( _optionalChain([caps, 'access', _70 => _70.resolutions, 'optionalAccess', _71 => _71.default])));
1185
+ const megapixels = resolution ? _nullishCoalesce(resolutionMegapixels(resolution), () => ( 0)) : 0;
1186
+ return Math.round(
1187
+ timing.baseMs + (_nullishCoalesce(timing.perItemMs, () => ( 0))) * Math.max(0, count - 1) + (_nullishCoalesce(timing.perSecondMs, () => ( 0))) * duration + (_nullishCoalesce(timing.perMegapixelMs, () => ( 0))) * megapixels
1188
+ );
1189
+ }
1190
+
1191
+ // src/generation/controls.ts
1192
+ function enumControl(key, label, cap) {
1193
+ if (!_optionalChain([cap, 'optionalAccess', _72 => _72.options, 'access', _73 => _73.length])) return null;
1194
+ return {
1195
+ key,
1196
+ label,
1197
+ kind: "select",
1198
+ valueType: "string",
1199
+ options: cap.options.map((value) => ({ value, label: _nullishCoalesce(_optionalChain([cap, 'access', _74 => _74.labels, 'optionalAccess', _75 => _75[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 = _optionalChain([caps, 'access', _76 => _76.count, 'access', _77 => _77.options, 'optionalAccess', _78 => _78.filter, 'call', _79 => _79((o) => o >= 1 && o <= caps.count.max)]);
1225
+ controls.push(
1226
+ _optionalChain([options, 'optionalAccess', _80 => _80.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: _nullishCoalesce(caps.count.default, () => ( 1)) }
1227
+ );
1228
+ }
1229
+ if (caps.duration) {
1230
+ const d = caps.duration;
1231
+ const options = _optionalChain([d, 'access', _81 => _81.options, 'optionalAccess', _82 => _82.filter, 'call', _83 => _83((o) => (d.min === void 0 || o >= d.min) && (d.max === void 0 || o <= d.max))]);
1232
+ controls.push(
1233
+ _optionalChain([options, 'optionalAccess', _84 => _84.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(_nullishCoalesce(caps.params, () => ( {})))) {
1248
+ const base = { key: `params.${name}`, label: _nullishCoalesce(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: _nullishCoalesce(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 _optionalChain([request, 'access', _85 => _85.params, 'optionalAccess', _86 => _86[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 = { ..._nullishCoalesce(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 = _nullishCoalesce(request.references, () => ( []));
1307
+ const total = refs.length;
1308
+ const maxTotal = _nullishCoalesce(_optionalChain([caps, 'access', _87 => _87.references, 'optionalAccess', _88 => _88.maxTotal]), () => ( Infinity));
1309
+ return roles.map((role) => {
1310
+ const cap = _nullishCoalesce(_optionalChain([caps, 'access', _89 => _89.references, 'optionalAccess', _90 => _90.roles, 'access', _91 => _91[role]]), () => ( { max: 1 }));
1311
+ const references = refs.filter((ref) => ref.role === role);
1312
+ return {
1313
+ role,
1314
+ label: _nullishCoalesce(cap.label, () => ( REFERENCE_ROLE_LABELS[role])),
1315
+ ...cap.description ? { description: cap.description } : {},
1316
+ min: _nullishCoalesce(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: [..._nullishCoalesce(request.references, () => ( [])), { ...reference }] };
1325
+ }
1326
+ function removeReference(request, role, id) {
1327
+ const references = (_nullishCoalesce(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
+
1333
+
1334
+
1335
+
1336
+
1337
+
1338
+
1339
+
1340
+
1341
+
1342
+
1343
+
1344
+
1345
+
1346
+
1347
+
1348
+
1349
+
1350
+
1351
+
1352
+
1353
+
1354
+
1355
+
1356
+
1357
+
1358
+
1359
+
1360
+
1361
+
1362
+
1363
+
1364
+
1365
+
1366
+
1367
+
1368
+
1369
+
1370
+
1371
+
1372
+ exports.GENERATION_REQUEST_FIELDS = GENERATION_REQUEST_FIELDS; exports.MAX_PENDING_PERCENT = MAX_PENDING_PERCENT; exports.PROVENANCE_FORMAT = PROVENANCE_FORMAT; exports.PROVENANCE_VERSION = PROVENANCE_VERSION; exports.ProvenanceParseError = ProvenanceParseError; exports.QUALITY_LADDER = QUALITY_LADDER; exports.REFERENCE_ROLES = REFERENCE_ROLES; exports.REFERENCE_ROLE_LABELS = REFERENCE_ROLE_LABELS; exports.addReference = addReference; exports.aspectRatioRank = aspectRatioRank; exports.capabilitiesToJsonSchema = capabilitiesToJsonSchema; exports.createBatchResolver = createBatchResolver; exports.createGenerationToolProvider = createGenerationToolProvider; exports.createProvenance = createProvenance; exports.estimateJobProgress = estimateJobProgress; exports.expectedDurationFor = expectedDurationFor; exports.formatRemaining = formatRemaining; exports.getGenerationControls = getGenerationControls; exports.getReferenceSlots = getReferenceSlots; exports.getRequestValue = getRequestValue; exports.mergeCapabilities = mergeCapabilities; exports.parseControlValue = parseControlValue; exports.parseProvenance = parseProvenance; exports.pinnedTemplatesToTemplates = pinnedTemplatesToTemplates; exports.planGenerationRequest = planGenerationRequest; exports.qualityRank = qualityRank; exports.recreateRequest = recreateRequest; exports.removeReference = removeReference; exports.replayProvenancePrompt = replayProvenancePrompt; exports.resolutionMegapixels = resolutionMegapixels; exports.resolutionRank = resolutionRank; exports.seedCapability = seedCapability; exports.serializeProvenance = serializeProvenance; exports.setRequestValue = setRequestValue; exports.snapToOption = snapToOption; exports.supportedModes = supportedModes; exports.supportedReferenceRoles = supportedReferenceRoles; exports.textFieldCapability = textFieldCapability; exports.validateJsonSchema = _chunkCPOKFNBGcjs.validateJsonSchema;
1373
+ //# sourceMappingURL=index.cjs.map