Forked from ceveyne/user-docs
Forked from ceveyne/user-docs
src / core-bundle.mjs
src / core-bundle.mjs
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
var __commonJS = (cb, mod) => function __require2() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target2) => (target2 = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target2, "default", { value: mod, enumerable: true }) : target2,
mod
));
// node_modules/flatbuffers/js/constants.js
var require_constants = __commonJS({
"node_modules/flatbuffers/js/constants.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SIZE_PREFIX_LENGTH = exports.FILE_IDENTIFIER_LENGTH = exports.SIZEOF_INT = exports.SIZEOF_SHORT = void 0;
exports.SIZEOF_SHORT = 2;
exports.SIZEOF_INT = 4;
exports.FILE_IDENTIFIER_LENGTH = 4;
exports.SIZE_PREFIX_LENGTH = 4;
}
});
// node_modules/flatbuffers/js/utils.js
var require_utils = __commonJS({
"node_modules/flatbuffers/js/utils.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isLittleEndian = exports.float64 = exports.float32 = exports.int32 = void 0;
exports.int32 = new Int32Array(2);
exports.float32 = new Float32Array(exports.int32.buffer);
exports.float64 = new Float64Array(exports.int32.buffer);
exports.isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1;
}
});
// node_modules/flatbuffers/js/encoding.js
var require_encoding = __commonJS({
"node_modules/flatbuffers/js/encoding.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Encoding = void 0;
var Encoding;
(function(Encoding2) {
Encoding2[Encoding2["UTF8_BYTES"] = 1] = "UTF8_BYTES";
Encoding2[Encoding2["UTF16_STRING"] = 2] = "UTF16_STRING";
})(Encoding || (exports.Encoding = Encoding = {}));
}
});
// node_modules/flatbuffers/js/byte-buffer.js
var require_byte_buffer = __commonJS({
"node_modules/flatbuffers/js/byte-buffer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ByteBuffer = void 0;
var constants_js_1 = require_constants();
var encoding_js_1 = require_encoding();
var utils_js_1 = require_utils();
var ByteBuffer3 = class _ByteBuffer {
/**
* Create a new ByteBuffer with a given array of bytes (`Uint8Array`)
*/
constructor(bytes_) {
this.bytes_ = bytes_;
this.position_ = 0;
this.text_decoder_ = new TextDecoder();
}
/**
* Create and allocate a new ByteBuffer with a given size.
*/
static allocate(byte_size) {
return new _ByteBuffer(new Uint8Array(byte_size));
}
clear() {
this.position_ = 0;
}
/**
* Get the underlying `Uint8Array`.
*/
bytes() {
return this.bytes_;
}
/**
* Get the buffer's position.
*/
position() {
return this.position_;
}
/**
* Set the buffer's position.
*/
setPosition(position) {
this.position_ = position;
}
/**
* Get the buffer's capacity.
*/
capacity() {
return this.bytes_.length;
}
readInt8(offset) {
return this.readUint8(offset) << 24 >> 24;
}
readUint8(offset) {
return this.bytes_[offset];
}
readInt16(offset) {
return this.readUint16(offset) << 16 >> 16;
}
readUint16(offset) {
return this.bytes_[offset] | this.bytes_[offset + 1] << 8;
}
readInt32(offset) {
return this.bytes_[offset] | this.bytes_[offset + 1] << 8 | this.bytes_[offset + 2] << 16 | this.bytes_[offset + 3] << 24;
}
readUint32(offset) {
return this.readInt32(offset) >>> 0;
}
readInt64(offset) {
return BigInt.asIntN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32)));
}
readUint64(offset) {
return BigInt.asUintN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32)));
}
readFloat32(offset) {
utils_js_1.int32[0] = this.readInt32(offset);
return utils_js_1.float32[0];
}
readFloat64(offset) {
utils_js_1.int32[utils_js_1.isLittleEndian ? 0 : 1] = this.readInt32(offset);
utils_js_1.int32[utils_js_1.isLittleEndian ? 1 : 0] = this.readInt32(offset + 4);
return utils_js_1.float64[0];
}
writeInt8(offset, value) {
this.bytes_[offset] = value;
}
writeUint8(offset, value) {
this.bytes_[offset] = value;
}
writeInt16(offset, value) {
this.bytes_[offset] = value;
this.bytes_[offset + 1] = value >> 8;
}
writeUint16(offset, value) {
this.bytes_[offset] = value;
this.bytes_[offset + 1] = value >> 8;
}
writeInt32(offset, value) {
this.bytes_[offset] = value;
this.bytes_[offset + 1] = value >> 8;
this.bytes_[offset + 2] = value >> 16;
this.bytes_[offset + 3] = value >> 24;
}
writeUint32(offset, value) {
this.bytes_[offset] = value;
this.bytes_[offset + 1] = value >> 8;
this.bytes_[offset + 2] = value >> 16;
this.bytes_[offset + 3] = value >> 24;
}
writeInt64(offset, value) {
this.writeInt32(offset, Number(BigInt.asIntN(32, value)));
this.writeInt32(offset + 4, Number(BigInt.asIntN(32, value >> BigInt(32))));
}
writeUint64(offset, value) {
this.writeUint32(offset, Number(BigInt.asUintN(32, value)));
this.writeUint32(offset + 4, Number(BigInt.asUintN(32, value >> BigInt(32))));
}
writeFloat32(offset, value) {
utils_js_1.float32[0] = value;
this.writeInt32(offset, utils_js_1.int32[0]);
}
writeFloat64(offset, value) {
utils_js_1.float64[0] = value;
this.writeInt32(offset, utils_js_1.int32[utils_js_1.isLittleEndian ? 0 : 1]);
this.writeInt32(offset + 4, utils_js_1.int32[utils_js_1.isLittleEndian ? 1 : 0]);
}
/**
* Return the file identifier. Behavior is undefined for FlatBuffers whose
* schema does not include a file_identifier (likely points at padding or the
* start of a the root vtable).
*/
getBufferIdentifier() {
if (this.bytes_.length < this.position_ + constants_js_1.SIZEOF_INT + constants_js_1.FILE_IDENTIFIER_LENGTH) {
throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");
}
let result = "";
for (let i = 0; i < constants_js_1.FILE_IDENTIFIER_LENGTH; i++) {
result += String.fromCharCode(this.readInt8(this.position_ + constants_js_1.SIZEOF_INT + i));
}
return result;
}
/**
* Look up a field in the vtable, return an offset into the object, or 0 if the
* field is not present.
*/
__offset(bb_pos, vtable_offset) {
const vtable = bb_pos - this.readInt32(bb_pos);
return vtable_offset < this.readInt16(vtable) ? this.readInt16(vtable + vtable_offset) : 0;
}
/**
* Initialize any Table-derived type to point to the union at the given offset.
*/
__union(t, offset) {
t.bb_pos = offset + this.readInt32(offset);
t.bb = this;
return t;
}
/**
* Create a JavaScript string from UTF-8 data stored inside the FlatBuffer.
* This allocates a new string and converts to wide chars upon each access.
*
* To avoid the conversion to string, pass Encoding.UTF8_BYTES as the
* "optionalEncoding" argument. This is useful for avoiding conversion when
* the data will just be packaged back up in another FlatBuffer later on.
*
* @param offset
* @param opt_encoding Defaults to UTF16_STRING
*/
__string(offset, opt_encoding) {
offset += this.readInt32(offset);
const length = this.readInt32(offset);
offset += constants_js_1.SIZEOF_INT;
const utf8bytes = this.bytes_.subarray(offset, offset + length);
if (opt_encoding === encoding_js_1.Encoding.UTF8_BYTES)
return utf8bytes;
else
return this.text_decoder_.decode(utf8bytes);
}
/**
* Handle unions that can contain string as its member, if a Table-derived type then initialize it,
* if a string then return a new one
*
* WARNING: strings are immutable in JS so we can't change the string that the user gave us, this
* makes the behaviour of __union_with_string different compared to __union
*/
__union_with_string(o, offset) {
if (typeof o === "string") {
return this.__string(offset);
}
return this.__union(o, offset);
}
/**
* Retrieve the relative offset stored at "offset"
*/
__indirect(offset) {
return offset + this.readInt32(offset);
}
/**
* Get the start of data of a vector whose offset is stored at "offset" in this object.
*/
__vector(offset) {
return offset + this.readInt32(offset) + constants_js_1.SIZEOF_INT;
}
/**
* Get the length of a vector whose offset is stored at "offset" in this object.
*/
__vector_len(offset) {
return this.readInt32(offset + this.readInt32(offset));
}
__has_identifier(ident) {
if (ident.length != constants_js_1.FILE_IDENTIFIER_LENGTH) {
throw new Error("FlatBuffers: file identifier must be length " + constants_js_1.FILE_IDENTIFIER_LENGTH);
}
for (let i = 0; i < constants_js_1.FILE_IDENTIFIER_LENGTH; i++) {
if (ident.charCodeAt(i) != this.readInt8(this.position() + constants_js_1.SIZEOF_INT + i)) {
return false;
}
}
return true;
}
/**
* A helper function for generating list for obj api
*/
createScalarList(listAccessor, listLength) {
const ret = [];
for (let i = 0; i < listLength; ++i) {
const val = listAccessor(i);
if (val !== null) {
ret.push(val);
}
}
return ret;
}
/**
* A helper function for generating list for obj api
* @param listAccessor function that accepts an index and return data at that index
* @param listLength listLength
* @param res result list
*/
createObjList(listAccessor, listLength) {
const ret = [];
for (let i = 0; i < listLength; ++i) {
const val = listAccessor(i);
if (val !== null) {
ret.push(val.unpack());
}
}
return ret;
}
};
exports.ByteBuffer = ByteBuffer3;
}
});
// node_modules/flatbuffers/js/builder.js
var require_builder = __commonJS({
"node_modules/flatbuffers/js/builder.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Builder = void 0;
var byte_buffer_js_1 = require_byte_buffer();
var constants_js_1 = require_constants();
var Builder2 = class _Builder {
/**
* Create a FlatBufferBuilder.
*/
constructor(opt_initial_size) {
this.minalign = 1;
this.vtable = null;
this.vtable_in_use = 0;
this.isNested = false;
this.object_start = 0;
this.vtables = [];
this.vector_num_elems = 0;
this.force_defaults = false;
this.string_maps = null;
this.text_encoder = new TextEncoder();
let initial_size;
if (!opt_initial_size) {
initial_size = 1024;
} else {
initial_size = opt_initial_size;
}
this.bb = byte_buffer_js_1.ByteBuffer.allocate(initial_size);
this.space = initial_size;
}
clear() {
this.bb.clear();
this.space = this.bb.capacity();
this.minalign = 1;
this.vtable = null;
this.vtable_in_use = 0;
this.isNested = false;
this.object_start = 0;
this.vtables = [];
this.vector_num_elems = 0;
this.force_defaults = false;
this.string_maps = null;
}
/**
* In order to save space, fields that are set to their default value
* don't get serialized into the buffer. Forcing defaults provides a
* way to manually disable this optimization.
*
* @param forceDefaults true always serializes default values
*/
forceDefaults(forceDefaults) {
this.force_defaults = forceDefaults;
}
/**
* Get the ByteBuffer representing the FlatBuffer. Only call this after you've
* called finish(). The actual data starts at the ByteBuffer's current position,
* not necessarily at 0.
*/
dataBuffer() {
return this.bb;
}
/**
* Get the bytes representing the FlatBuffer. Only call this after you've
* called finish().
*/
asUint8Array() {
return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset());
}
/**
* Prepare to write an element of `size` after `additional_bytes` have been
* written, e.g. if you write a string, you need to align such the int length
* field is aligned to 4 bytes, and the string data follows it directly. If all
* you need to do is alignment, `additional_bytes` will be 0.
*
* @param size This is the of the new element to write
* @param additional_bytes The padding size
*/
prep(size, additional_bytes) {
if (size > this.minalign) {
this.minalign = size;
}
const align_size = ~(this.bb.capacity() - this.space + additional_bytes) + 1 & size - 1;
while (this.space < align_size + size + additional_bytes) {
const old_buf_size = this.bb.capacity();
this.bb = _Builder.growByteBuffer(this.bb);
this.space += this.bb.capacity() - old_buf_size;
}
this.pad(align_size);
}
pad(byte_size) {
for (let i = 0; i < byte_size; i++) {
this.bb.writeInt8(--this.space, 0);
}
}
writeInt8(value) {
this.bb.writeInt8(this.space -= 1, value);
}
writeInt16(value) {
this.bb.writeInt16(this.space -= 2, value);
}
writeInt32(value) {
this.bb.writeInt32(this.space -= 4, value);
}
writeInt64(value) {
this.bb.writeInt64(this.space -= 8, value);
}
writeFloat32(value) {
this.bb.writeFloat32(this.space -= 4, value);
}
writeFloat64(value) {
this.bb.writeFloat64(this.space -= 8, value);
}
/**
* Add an `int8` to the buffer, properly aligned, and grows the buffer (if necessary).
* @param value The `int8` to add the buffer.
*/
addInt8(value) {
this.prep(1, 0);
this.writeInt8(value);
}
/**
* Add an `int16` to the buffer, properly aligned, and grows the buffer (if necessary).
* @param value The `int16` to add the buffer.
*/
addInt16(value) {
this.prep(2, 0);
this.writeInt16(value);
}
/**
* Add an `int32` to the buffer, properly aligned, and grows the buffer (if necessary).
* @param value The `int32` to add the buffer.
*/
addInt32(value) {
this.prep(4, 0);
this.writeInt32(value);
}
/**
* Add an `int64` to the buffer, properly aligned, and grows the buffer (if necessary).
* @param value The `int64` to add the buffer.
*/
addInt64(value) {
this.prep(8, 0);
this.writeInt64(value);
}
/**
* Add a `float32` to the buffer, properly aligned, and grows the buffer (if necessary).
* @param value The `float32` to add the buffer.
*/
addFloat32(value) {
this.prep(4, 0);
this.writeFloat32(value);
}
/**
* Add a `float64` to the buffer, properly aligned, and grows the buffer (if necessary).
* @param value The `float64` to add the buffer.
*/
addFloat64(value) {
this.prep(8, 0);
this.writeFloat64(value);
}
addFieldInt8(voffset, value, defaultValue) {
if (this.force_defaults || value != defaultValue) {
this.addInt8(value);
this.slot(voffset);
}
}
addFieldInt16(voffset, value, defaultValue) {
if (this.force_defaults || value != defaultValue) {
this.addInt16(value);
this.slot(voffset);
}
}
addFieldInt32(voffset, value, defaultValue) {
if (this.force_defaults || value != defaultValue) {
this.addInt32(value);
this.slot(voffset);
}
}
addFieldInt64(voffset, value, defaultValue) {
if (this.force_defaults || value !== defaultValue) {
this.addInt64(value);
this.slot(voffset);
}
}
addFieldFloat32(voffset, value, defaultValue) {
if (this.force_defaults || value != defaultValue) {
this.addFloat32(value);
this.slot(voffset);
}
}
addFieldFloat64(voffset, value, defaultValue) {
if (this.force_defaults || value != defaultValue) {
this.addFloat64(value);
this.slot(voffset);
}
}
addFieldOffset(voffset, value, defaultValue) {
if (this.force_defaults || value != defaultValue) {
this.addOffset(value);
this.slot(voffset);
}
}
/**
* Structs are stored inline, so nothing additional is being added. `d` is always 0.
*/
addFieldStruct(voffset, value, defaultValue) {
if (value != defaultValue) {
this.nested(value);
this.slot(voffset);
}
}
/**
* Structures are always stored inline, they need to be created right
* where they're used. You'll get this assertion failure if you
* created it elsewhere.
*/
nested(obj) {
if (obj != this.offset()) {
throw new TypeError("FlatBuffers: struct must be serialized inline.");
}
}
/**
* Should not be creating any other object, string or vector
* while an object is being constructed
*/
notNested() {
if (this.isNested) {
throw new TypeError("FlatBuffers: object serialization must not be nested.");
}
}
/**
* Set the current vtable at `voffset` to the current location in the buffer.
*/
slot(voffset) {
if (this.vtable !== null)
this.vtable[voffset] = this.offset();
}
/**
* @returns Offset relative to the end of the buffer.
*/
offset() {
return this.bb.capacity() - this.space;
}
/**
* Doubles the size of the backing ByteBuffer and copies the old data towards
* the end of the new buffer (since we build the buffer backwards).
*
* @param bb The current buffer with the existing data
* @returns A new byte buffer with the old data copied
* to it. The data is located at the end of the buffer.
*
* uint8Array.set() formally takes {Array<number>|ArrayBufferView}, so to pass
* it a uint8Array we need to suppress the type check:
* @suppress {checkTypes}
*/
static growByteBuffer(bb) {
const old_buf_size = bb.capacity();
if (old_buf_size & 3221225472) {
throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");
}
const new_buf_size = old_buf_size << 1;
const nbb = byte_buffer_js_1.ByteBuffer.allocate(new_buf_size);
nbb.setPosition(new_buf_size - old_buf_size);
nbb.bytes().set(bb.bytes(), new_buf_size - old_buf_size);
return nbb;
}
/**
* Adds on offset, relative to where it will be written.
*
* @param offset The offset to add.
*/
addOffset(offset) {
this.prep(constants_js_1.SIZEOF_INT, 0);
this.writeInt32(this.offset() - offset + constants_js_1.SIZEOF_INT);
}
/**
* Start encoding a new object in the buffer. Users will not usually need to
* call this directly. The FlatBuffers compiler will generate helper methods
* that call this method internally.
*/
startObject(numfields) {
this.notNested();
if (this.vtable == null) {
this.vtable = [];
}
this.vtable_in_use = numfields;
for (let i = 0; i < numfields; i++) {
this.vtable[i] = 0;
}
this.isNested = true;
this.object_start = this.offset();
}
/**
* Finish off writing the object that is under construction.
*
* @returns The offset to the object inside `dataBuffer`
*/
endObject() {
if (this.vtable == null || !this.isNested) {
throw new Error("FlatBuffers: endObject called without startObject");
}
this.addInt32(0);
const vtableloc = this.offset();
let i = this.vtable_in_use - 1;
for (; i >= 0 && this.vtable[i] == 0; i--) {
}
const trimmed_size = i + 1;
for (; i >= 0; i--) {
this.addInt16(this.vtable[i] != 0 ? vtableloc - this.vtable[i] : 0);
}
const standard_fields = 2;
this.addInt16(vtableloc - this.object_start);
const len = (trimmed_size + standard_fields) * constants_js_1.SIZEOF_SHORT;
this.addInt16(len);
let existing_vtable = 0;
const vt1 = this.space;
outer_loop: for (i = 0; i < this.vtables.length; i++) {
const vt2 = this.bb.capacity() - this.vtables[i];
if (len == this.bb.readInt16(vt2)) {
for (let j = constants_js_1.SIZEOF_SHORT; j < len; j += constants_js_1.SIZEOF_SHORT) {
if (this.bb.readInt16(vt1 + j) != this.bb.readInt16(vt2 + j)) {
continue outer_loop;
}
}
existing_vtable = this.vtables[i];
break;
}
}
if (existing_vtable) {
this.space = this.bb.capacity() - vtableloc;
this.bb.writeInt32(this.space, existing_vtable - vtableloc);
} else {
this.vtables.push(this.offset());
this.bb.writeInt32(this.bb.capacity() - vtableloc, this.offset() - vtableloc);
}
this.isNested = false;
return vtableloc;
}
/**
* Finalize a buffer, poiting to the given `root_table`.
*/
finish(root_table, opt_file_identifier, opt_size_prefix) {
const size_prefix = opt_size_prefix ? constants_js_1.SIZE_PREFIX_LENGTH : 0;
if (opt_file_identifier) {
const file_identifier = opt_file_identifier;
this.prep(this.minalign, constants_js_1.SIZEOF_INT + constants_js_1.FILE_IDENTIFIER_LENGTH + size_prefix);
if (file_identifier.length != constants_js_1.FILE_IDENTIFIER_LENGTH) {
throw new TypeError("FlatBuffers: file identifier must be length " + constants_js_1.FILE_IDENTIFIER_LENGTH);
}
for (let i = constants_js_1.FILE_IDENTIFIER_LENGTH - 1; i >= 0; i--) {
this.writeInt8(file_identifier.charCodeAt(i));
}
}
this.prep(this.minalign, constants_js_1.SIZEOF_INT + size_prefix);
this.addOffset(root_table);
if (size_prefix) {
this.addInt32(this.bb.capacity() - this.space);
}
this.bb.setPosition(this.space);
}
/**
* Finalize a size prefixed buffer, pointing to the given `root_table`.
*/
finishSizePrefixed(root_table, opt_file_identifier) {
this.finish(root_table, opt_file_identifier, true);
}
/**
* This checks a required field has been set in a given table that has
* just been constructed.
*/
requiredField(table, field) {
const table_start = this.bb.capacity() - table;
const vtable_start = table_start - this.bb.readInt32(table_start);
const ok = field < this.bb.readInt16(vtable_start) && this.bb.readInt16(vtable_start + field) != 0;
if (!ok) {
throw new TypeError("FlatBuffers: field " + field + " must be set");
}
}
/**
* Start a new array/vector of objects. Users usually will not call
* this directly. The FlatBuffers compiler will create a start/end
* method for vector types in generated code.
*
* @param elem_size The size of each element in the array
* @param num_elems The number of elements in the array
* @param alignment The alignment of the array
*/
startVector(elem_size, num_elems, alignment) {
this.notNested();
this.vector_num_elems = num_elems;
this.prep(constants_js_1.SIZEOF_INT, elem_size * num_elems);
this.prep(alignment, elem_size * num_elems);
}
/**
* Finish off the creation of an array and all its elements. The array must be
* created with `startVector`.
*
* @returns The offset at which the newly created array
* starts.
*/
endVector() {
this.writeInt32(this.vector_num_elems);
return this.offset();
}
/**
* Encode the string `s` in the buffer using UTF-8. If the string passed has
* already been seen, we return the offset of the already written string
*
* @param s The string to encode
* @return The offset in the buffer where the encoded string starts
*/
createSharedString(s) {
if (!s) {
return 0;
}
if (!this.string_maps) {
this.string_maps = /* @__PURE__ */ new Map();
}
if (this.string_maps.has(s)) {
return this.string_maps.get(s);
}
const offset = this.createString(s);
this.string_maps.set(s, offset);
return offset;
}
/**
* Encode the string `s` in the buffer using UTF-8. If a Uint8Array is passed
* instead of a string, it is assumed to contain valid UTF-8 encoded data.
*
* @param s The string to encode
* @return The offset in the buffer where the encoded string starts
*/
createString(s) {
if (s === null || s === void 0) {
return 0;
}
let utf8;
if (s instanceof Uint8Array) {
utf8 = s;
} else {
utf8 = this.text_encoder.encode(s);
}
this.addInt8(0);
this.startVector(1, utf8.length, 1);
this.bb.setPosition(this.space -= utf8.length);
this.bb.bytes().set(utf8, this.space);
return this.endVector();
}
/**
* Create a byte vector.
*
* @param v The bytes to add
* @returns The offset in the buffer where the byte vector starts
*/
createByteVector(v) {
if (v === null || v === void 0) {
return 0;
}
this.startVector(1, v.length, 1);
this.bb.setPosition(this.space -= v.length);
this.bb.bytes().set(v, this.space);
return this.endVector();
}
/**
* A helper function to pack an object
*
* @returns offset of obj
*/
createObjectOffset(obj) {
if (obj === null) {
return 0;
}
if (typeof obj === "string") {
return this.createString(obj);
} else {
return obj.pack(this);
}
}
/**
* A helper function to pack a list of object
*
* @returns list of offsets of each non null object
*/
createObjectOffsetList(list) {
const ret = [];
for (let i = 0; i < list.length; ++i) {
const val = list[i];
if (val !== null) {
ret.push(this.createObjectOffset(val));
} else {
throw new TypeError("FlatBuffers: Argument for createObjectOffsetList cannot contain null.");
}
}
return ret;
}
createStructOffsetList(list, startFunc) {
startFunc(this, list.length);
this.createObjectOffsetList(list.slice().reverse());
return this.endVector();
}
};
exports.Builder = Builder2;
}
});
// node_modules/flatbuffers/js/flatbuffers.js
var require_flatbuffers = __commonJS({
"node_modules/flatbuffers/js/flatbuffers.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Encoding = exports.ByteBuffer = exports.Builder = exports.isLittleEndian = exports.int32 = exports.float64 = exports.float32 = exports.SIZE_PREFIX_LENGTH = exports.SIZEOF_SHORT = exports.SIZEOF_INT = exports.FILE_IDENTIFIER_LENGTH = void 0;
var constants_js_1 = require_constants();
Object.defineProperty(exports, "FILE_IDENTIFIER_LENGTH", { enumerable: true, get: function() {
return constants_js_1.FILE_IDENTIFIER_LENGTH;
} });
Object.defineProperty(exports, "SIZEOF_INT", { enumerable: true, get: function() {
return constants_js_1.SIZEOF_INT;
} });
Object.defineProperty(exports, "SIZEOF_SHORT", { enumerable: true, get: function() {
return constants_js_1.SIZEOF_SHORT;
} });
Object.defineProperty(exports, "SIZE_PREFIX_LENGTH", { enumerable: true, get: function() {
return constants_js_1.SIZE_PREFIX_LENGTH;
} });
var utils_js_1 = require_utils();
Object.defineProperty(exports, "float32", { enumerable: true, get: function() {
return utils_js_1.float32;
} });
Object.defineProperty(exports, "float64", { enumerable: true, get: function() {
return utils_js_1.float64;
} });
Object.defineProperty(exports, "int32", { enumerable: true, get: function() {
return utils_js_1.int32;
} });
Object.defineProperty(exports, "isLittleEndian", { enumerable: true, get: function() {
return utils_js_1.isLittleEndian;
} });
var builder_js_1 = require_builder();
Object.defineProperty(exports, "Builder", { enumerable: true, get: function() {
return builder_js_1.Builder;
} });
var byte_buffer_js_1 = require_byte_buffer();
Object.defineProperty(exports, "ByteBuffer", { enumerable: true, get: function() {
return byte_buffer_js_1.ByteBuffer;
} });
var encoding_js_1 = require_encoding();
Object.defineProperty(exports, "Encoding", { enumerable: true, get: function() {
return encoding_js_1.Encoding;
} });
}
});
// node_modules/exifr/dist/full.umd.js
var require_full_umd = __commonJS({
"node_modules/exifr/dist/full.umd.js"(exports, module) {
!(function(e, t) {
"object" == typeof exports && "undefined" != typeof module ? t(exports) : "function" == typeof define && define.amd ? define("exifr", ["exports"], t) : t((e = "undefined" != typeof globalThis ? globalThis : e || self).exifr = {});
})(exports, (function(e) {
"use strict";
var t = "undefined" != typeof self ? self : global;
const i = "undefined" != typeof navigator, n = i && "undefined" == typeof HTMLImageElement, s = !("undefined" == typeof global || "undefined" == typeof process || !process.versions || !process.versions.node), r = t.Buffer, a = t.BigInt, o = !!r, l = (e2) => e2;
function h(e2, t2 = l) {
if (s) try {
return "function" == typeof __require ? Promise.resolve(t2(__require(e2))) : import(
/* webpackIgnore: true */
e2
).then(t2);
} catch (t3) {
console.warn(`Couldn't load ${e2}`);
}
}
let u = t.fetch;
const c = (e2) => u = e2;
if (!t.fetch) {
const e2 = h("http", ((e3) => e3)), t2 = h("https", ((e3) => e3)), i2 = (n2, { headers: s2 } = {}) => new Promise((async (r2, a2) => {
let { port: o2, hostname: l2, pathname: h2, protocol: u2, search: c2 } = new URL(n2);
const f2 = { method: "GET", hostname: l2, path: encodeURI(h2) + c2, headers: s2 };
"" !== o2 && (f2.port = Number(o2));
const d2 = ("https:" === u2 ? await t2 : await e2).request(f2, ((e3) => {
if (301 === e3.statusCode || 302 === e3.statusCode) {
let t3 = new URL(e3.headers.location, n2).toString();
return i2(t3, { headers: s2 }).then(r2).catch(a2);
}
r2({ status: e3.statusCode, arrayBuffer: () => new Promise(((t3) => {
let i3 = [];
e3.on("data", ((e4) => i3.push(e4))), e3.on("end", (() => t3(Buffer.concat(i3))));
})) });
}));
d2.on("error", a2), d2.end();
}));
c(i2);
}
function f(e2, t2, i2) {
return t2 in e2 ? Object.defineProperty(e2, t2, { value: i2, enumerable: true, configurable: true, writable: true }) : e2[t2] = i2, e2;
}
const d = (e2) => g(e2) ? void 0 : e2, p = (e2) => void 0 !== e2;
function g(e2) {
return void 0 === e2 || (e2 instanceof Map ? 0 === e2.size : 0 === Object.values(e2).filter(p).length);
}
function m(e2) {
let t2 = new Error(e2);
throw delete t2.stack, t2;
}
function S(e2) {
return "" === (e2 = (function(e3) {
for (; e3.endsWith("\0"); ) e3 = e3.slice(0, -1);
return e3;
})(e2).trim()) ? void 0 : e2;
}
function C(e2) {
let t2 = (function(e3) {
let t3 = 0;
return e3.ifd0.enabled && (t3 += 1024), e3.exif.enabled && (t3 += 2048), e3.makerNote && (t3 += 2048), e3.userComment && (t3 += 1024), e3.gps.enabled && (t3 += 512), e3.interop.enabled && (t3 += 100), e3.ifd1.enabled && (t3 += 1024), t3 + 2048;
})(e2);
return e2.jfif.enabled && (t2 += 50), e2.xmp.enabled && (t2 += 2e4), e2.iptc.enabled && (t2 += 14e3), e2.icc.enabled && (t2 += 6e3), t2;
}
const y = (e2) => String.fromCharCode.apply(null, e2), b = "undefined" != typeof TextDecoder ? new TextDecoder("utf-8") : void 0;
function P(e2) {
return b ? b.decode(e2) : o ? Buffer.from(e2).toString("utf8") : decodeURIComponent(escape(y(e2)));
}
class I {
static from(e2, t2) {
return e2 instanceof this && e2.le === t2 ? e2 : new I(e2, void 0, void 0, t2);
}
constructor(e2, t2 = 0, i2, n2) {
if ("boolean" == typeof n2 && (this.le = n2), Array.isArray(e2) && (e2 = new Uint8Array(e2)), 0 === e2) this.byteOffset = 0, this.byteLength = 0;
else if (e2 instanceof ArrayBuffer) {
void 0 === i2 && (i2 = e2.byteLength - t2);
let n3 = new DataView(e2, t2, i2);
this._swapDataView(n3);
} else if (e2 instanceof Uint8Array || e2 instanceof DataView || e2 instanceof I) {
void 0 === i2 && (i2 = e2.byteLength - t2), (t2 += e2.byteOffset) + i2 > e2.byteOffset + e2.byteLength && m("Creating view outside of available memory in ArrayBuffer");
let n3 = new DataView(e2.buffer, t2, i2);
this._swapDataView(n3);
} else if ("number" == typeof e2) {
let t3 = new DataView(new ArrayBuffer(e2));
this._swapDataView(t3);
} else m("Invalid input argument for BufferView: " + e2);
}
_swapArrayBuffer(e2) {
this._swapDataView(new DataView(e2));
}
_swapBuffer(e2) {
this._swapDataView(new DataView(e2.buffer, e2.byteOffset, e2.byteLength));
}
_swapDataView(e2) {
this.dataView = e2, this.buffer = e2.buffer, this.byteOffset = e2.byteOffset, this.byteLength = e2.byteLength;
}
_lengthToEnd(e2) {
return this.byteLength - e2;
}
set(e2, t2, i2 = I) {
return e2 instanceof DataView || e2 instanceof I ? e2 = new Uint8Array(e2.buffer, e2.byteOffset, e2.byteLength) : e2 instanceof ArrayBuffer && (e2 = new Uint8Array(e2)), e2 instanceof Uint8Array || m("BufferView.set(): Invalid data argument."), this.toUint8().set(e2, t2), new i2(this, t2, e2.byteLength);
}
subarray(e2, t2) {
return t2 = t2 || this._lengthToEnd(e2), new I(this, e2, t2);
}
toUint8() {
return new Uint8Array(this.buffer, this.byteOffset, this.byteLength);
}
getUint8Array(e2, t2) {
return new Uint8Array(this.buffer, this.byteOffset + e2, t2);
}
getString(e2 = 0, t2 = this.byteLength) {
return P(this.getUint8Array(e2, t2));
}
getLatin1String(e2 = 0, t2 = this.byteLength) {
let i2 = this.getUint8Array(e2, t2);
return y(i2);
}
getUnicodeString(e2 = 0, t2 = this.byteLength) {
const i2 = [];
for (let n2 = 0; n2 < t2 && e2 + n2 < this.byteLength; n2 += 2) i2.push(this.getUint16(e2 + n2));
return y(i2);
}
getInt8(e2) {
return this.dataView.getInt8(e2);
}
getUint8(e2) {
return this.dataView.getUint8(e2);
}
getInt16(e2, t2 = this.le) {
return this.dataView.getInt16(e2, t2);
}
getInt32(e2, t2 = this.le) {
return this.dataView.getInt32(e2, t2);
}
getUint16(e2, t2 = this.le) {
return this.dataView.getUint16(e2, t2);
}
getUint32(e2, t2 = this.le) {
return this.dataView.getUint32(e2, t2);
}
getFloat32(e2, t2 = this.le) {
return this.dataView.getFloat32(e2, t2);
}
getFloat64(e2, t2 = this.le) {
return this.dataView.getFloat64(e2, t2);
}
getFloat(e2, t2 = this.le) {
return this.dataView.getFloat32(e2, t2);
}
getDouble(e2, t2 = this.le) {
return this.dataView.getFloat64(e2, t2);
}
getUintBytes(e2, t2, i2) {
switch (t2) {
case 1:
return this.getUint8(e2, i2);
case 2:
return this.getUint16(e2, i2);
case 4:
return this.getUint32(e2, i2);
case 8:
return this.getUint64 && this.getUint64(e2, i2);
}
}
getUint(e2, t2, i2) {
switch (t2) {
case 8:
return this.getUint8(e2, i2);
case 16:
return this.getUint16(e2, i2);
case 32:
return this.getUint32(e2, i2);
case 64:
return this.getUint64 && this.getUint64(e2, i2);
}
}
toString(e2) {
return this.dataView.toString(e2, this.constructor.name);
}
ensureChunk() {
}
}
function k(e2, t2) {
m(`${e2} '${t2}' was not loaded, try using full build of exifr.`);
}
class w extends Map {
constructor(e2) {
super(), this.kind = e2;
}
get(e2, t2) {
return this.has(e2) || k(this.kind, e2), t2 && (e2 in t2 || (function(e3, t3) {
m(`Unknown ${e3} '${t3}'.`);
})(this.kind, e2), t2[e2].enabled || k(this.kind, e2)), super.get(e2);
}
keyList() {
return Array.from(this.keys());
}
}
var T = new w("file parser"), A = new w("segment parser"), D = new w("file reader");
const O = "Invalid input argument";
function x(e2, t2) {
return "string" == typeof e2 ? v(e2, t2) : i && !n && e2 instanceof HTMLImageElement ? v(e2.src, t2) : e2 instanceof Uint8Array || e2 instanceof ArrayBuffer || e2 instanceof DataView ? new I(e2) : i && e2 instanceof Blob ? M(e2, t2, "blob", U) : void m(O);
}
function v(e2, t2) {
return (n2 = e2).startsWith("data:") || n2.length > 1e4 ? R(e2, t2, "base64") : s && e2.includes("://") ? M(e2, t2, "url", L) : s ? R(e2, t2, "fs") : i ? M(e2, t2, "url", L) : void m(O);
var n2;
}
async function M(e2, t2, i2, n2) {
return D.has(i2) ? R(e2, t2, i2) : n2 ? (async function(e3, t3) {
let i3 = await t3(e3);
return new I(i3);
})(e2, n2) : void m(`Parser ${i2} is not loaded`);
}
async function R(e2, t2, i2) {
let n2 = new (D.get(i2))(e2, t2);
return await n2.read(), n2;
}
const L = (e2) => u(e2).then(((e3) => e3.arrayBuffer())), U = (e2) => new Promise(((t2, i2) => {
let n2 = new FileReader();
n2.onloadend = () => t2(n2.result || new ArrayBuffer()), n2.onerror = i2, n2.readAsArrayBuffer(e2);
}));
class F extends Map {
get tagKeys() {
return this.allKeys || (this.allKeys = Array.from(this.keys())), this.allKeys;
}
get tagValues() {
return this.allValues || (this.allValues = Array.from(this.values())), this.allValues;
}
}
function B(e2, t2, i2) {
let n2 = new F();
for (let [e3, t3] of i2) n2.set(e3, t3);
if (Array.isArray(t2)) for (let i3 of t2) e2.set(i3, n2);
else e2.set(t2, n2);
return n2;
}
function E(e2, t2, i2) {
let n2, s2 = e2.get(t2);
for (n2 of i2) s2.set(n2[0], n2[1]);
}
const N = /* @__PURE__ */ new Map(), G = /* @__PURE__ */ new Map(), V = /* @__PURE__ */ new Map(), z4 = 37500, H = 37510, j = 700, W = 33723, K = 34675, X = 34665, _ = 34853, Y = 40965, $ = ["chunked", "firstChunkSize", "firstChunkSizeNode", "firstChunkSizeBrowser", "chunkSize", "chunkLimit"], J = ["jfif", "xmp", "icc", "iptc", "ihdr"], q = ["tiff", ...J], Q = ["ifd0", "ifd1", "exif", "gps", "interop"], Z = [...q, ...Q], ee = ["makerNote", "userComment"], te = ["translateKeys", "translateValues", "reviveValues", "multiSegment"], ie = [...te, "sanitize", "mergeOutput", "silentErrors"];
class ne {
get translate() {
return this.translateKeys || this.translateValues || this.reviveValues;
}
}
class se extends ne {
get needed() {
return this.enabled || this.deps.size > 0;
}
constructor(e2, t2, i2, n2) {
if (super(), f(this, "enabled", false), f(this, "skip", /* @__PURE__ */ new Set()), f(this, "pick", /* @__PURE__ */ new Set()), f(this, "deps", /* @__PURE__ */ new Set()), f(this, "translateKeys", false), f(this, "translateValues", false), f(this, "reviveValues", false), this.key = e2, this.enabled = t2, this.parse = this.enabled, this.applyInheritables(n2), this.canBeFiltered = Q.includes(e2), this.canBeFiltered && (this.dict = N.get(e2)), void 0 !== i2) if (Array.isArray(i2)) this.parse = this.enabled = true, this.canBeFiltered && i2.length > 0 && this.translateTagSet(i2, this.pick);
else if ("object" == typeof i2) {
if (this.enabled = true, this.parse = false !== i2.parse, this.canBeFiltered) {
let { pick: e3, skip: t3 } = i2;
e3 && e3.length > 0 && this.translateTagSet(e3, this.pick), t3 && t3.length > 0 && this.translateTagSet(t3, this.skip);
}
this.applyInheritables(i2);
} else true === i2 || false === i2 ? this.parse = this.enabled = i2 : m(`Invalid options argument: ${i2}`);
}
applyInheritables(e2) {
let t2, i2;
for (t2 of te) i2 = e2[t2], void 0 !== i2 && (this[t2] = i2);
}
translateTagSet(e2, t2) {
if (this.dict) {
let i2, n2, { tagKeys: s2, tagValues: r2 } = this.dict;
for (i2 of e2) "string" == typeof i2 ? (n2 = r2.indexOf(i2), -1 === n2 && (n2 = s2.indexOf(Number(i2))), -1 !== n2 && t2.add(Number(s2[n2]))) : t2.add(i2);
} else for (let i2 of e2) t2.add(i2);
}
finalizeFilters() {
!this.enabled && this.deps.size > 0 ? (this.enabled = true, ue(this.pick, this.deps)) : this.enabled && this.pick.size > 0 && ue(this.pick, this.deps);
}
}
var re = { jfif: false, tiff: true, xmp: false, icc: false, iptc: false, ifd0: true, ifd1: false, exif: true, gps: true, interop: false, ihdr: void 0, makerNote: false, userComment: false, multiSegment: false, skip: [], pick: [], translateKeys: true, translateValues: true, reviveValues: true, sanitize: true, mergeOutput: true, silentErrors: true, chunked: true, firstChunkSize: void 0, firstChunkSizeNode: 512, firstChunkSizeBrowser: 65536, chunkSize: 65536, chunkLimit: 5 }, ae = /* @__PURE__ */ new Map();
class oe extends ne {
static useCached(e2) {
let t2 = ae.get(e2);
return void 0 !== t2 || (t2 = new this(e2), ae.set(e2, t2)), t2;
}
constructor(e2) {
super(), true === e2 ? this.setupFromTrue() : void 0 === e2 ? this.setupFromUndefined() : Array.isArray(e2) ? this.setupFromArray(e2) : "object" == typeof e2 ? this.setupFromObject(e2) : m(`Invalid options argument ${e2}`), void 0 === this.firstChunkSize && (this.firstChunkSize = i ? this.firstChunkSizeBrowser : this.firstChunkSizeNode), this.mergeOutput && (this.ifd1.enabled = false), this.filterNestedSegmentTags(), this.traverseTiffDependencyTree(), this.checkLoadedPlugins();
}
setupFromUndefined() {
let e2;
for (e2 of $) this[e2] = re[e2];
for (e2 of ie) this[e2] = re[e2];
for (e2 of ee) this[e2] = re[e2];
for (e2 of Z) this[e2] = new se(e2, re[e2], void 0, this);
}
setupFromTrue() {
let e2;
for (e2 of $) this[e2] = re[e2];
for (e2 of ie) this[e2] = re[e2];
for (e2 of ee) this[e2] = true;
for (e2 of Z) this[e2] = new se(e2, true, void 0, this);
}
setupFromArray(e2) {
let t2;
for (t2 of $) this[t2] = re[t2];
for (t2 of ie) this[t2] = re[t2];
for (t2 of ee) this[t2] = re[t2];
for (t2 of Z) this[t2] = new se(t2, false, void 0, this);
this.setupGlobalFilters(e2, void 0, Q);
}
setupFromObject(e2) {
let t2;
for (t2 of (Q.ifd0 = Q.ifd0 || Q.image, Q.ifd1 = Q.ifd1 || Q.thumbnail, Object.assign(this, e2), $)) this[t2] = he(e2[t2], re[t2]);
for (t2 of ie) this[t2] = he(e2[t2], re[t2]);
for (t2 of ee) this[t2] = he(e2[t2], re[t2]);
for (t2 of q) this[t2] = new se(t2, re[t2], e2[t2], this);
for (t2 of Q) this[t2] = new se(t2, re[t2], e2[t2], this.tiff);
this.setupGlobalFilters(e2.pick, e2.skip, Q, Z), true === e2.tiff ? this.batchEnableWithBool(Q, true) : false === e2.tiff ? this.batchEnableWithUserValue(Q, e2) : Array.isArray(e2.tiff) ? this.setupGlobalFilters(e2.tiff, void 0, Q) : "object" == typeof e2.tiff && this.setupGlobalFilters(e2.tiff.pick, e2.tiff.skip, Q);
}
batchEnableWithBool(e2, t2) {
for (let i2 of e2) this[i2].enabled = t2;
}
batchEnableWithUserValue(e2, t2) {
for (let i2 of e2) {
let e3 = t2[i2];
this[i2].enabled = false !== e3 && void 0 !== e3;
}
}
setupGlobalFilters(e2, t2, i2, n2 = i2) {
if (e2 && e2.length) {
for (let e3 of n2) this[e3].enabled = false;
let t3 = le(e2, i2);
for (let [e3, i3] of t3) ue(this[e3].pick, i3), this[e3].enabled = true;
} else if (t2 && t2.length) {
let e3 = le(t2, i2);
for (let [t3, i3] of e3) ue(this[t3].skip, i3);
}
}
filterNestedSegmentTags() {
let { ifd0: e2, exif: t2, xmp: i2, iptc: n2, icc: s2 } = this;
this.makerNote ? t2.deps.add(z4) : t2.skip.add(z4), this.userComment ? t2.deps.add(H) : t2.skip.add(H), i2.enabled || e2.skip.add(j), n2.enabled || e2.skip.add(W), s2.enabled || e2.skip.add(K);
}
traverseTiffDependencyTree() {
let { ifd0: e2, exif: t2, gps: i2, interop: n2 } = this;
n2.needed && (t2.deps.add(Y), e2.deps.add(Y)), t2.needed && e2.deps.add(X), i2.needed && e2.deps.add(_), this.tiff.enabled = Q.some(((e3) => true === this[e3].enabled)) || this.makerNote || this.userComment;
for (let e3 of Q) this[e3].finalizeFilters();
}
get onlyTiff() {
return !J.map(((e2) => this[e2].enabled)).some(((e2) => true === e2)) && this.tiff.enabled;
}
checkLoadedPlugins() {
for (let e2 of q) this[e2].enabled && !A.has(e2) && k("segment parser", e2);
}
}
function le(e2, t2) {
let i2, n2, s2, r2, a2 = [];
for (s2 of t2) {
for (r2 of (i2 = N.get(s2), n2 = [], i2)) (e2.includes(r2[0]) || e2.includes(r2[1])) && n2.push(r2[0]);
n2.length && a2.push([s2, n2]);
}
return a2;
}
function he(e2, t2) {
return void 0 !== e2 ? e2 : void 0 !== t2 ? t2 : void 0;
}
function ue(e2, t2) {
for (let i2 of t2) e2.add(i2);
}
f(oe, "default", re);
class ce {
constructor(e2) {
f(this, "parsers", {}), f(this, "output", {}), f(this, "errors", []), f(this, "pushToErrors", ((e3) => this.errors.push(e3))), this.options = oe.useCached(e2);
}
async read(e2) {
this.file = await x(e2, this.options);
}
setup() {
if (this.fileParser) return;
let { file: e2 } = this, t2 = e2.getUint16(0);
for (let [i2, n2] of T) if (n2.canHandle(e2, t2)) return this.fileParser = new n2(this.options, this.file, this.parsers), e2[i2] = true;
this.file.close && this.file.close(), m("Unknown file format");
}
async parse() {
let { output: e2, errors: t2 } = this;
return this.setup(), this.options.silentErrors ? (await this.executeParsers().catch(this.pushToErrors), t2.push(...this.fileParser.errors)) : await this.executeParsers(), this.file.close && this.file.close(), this.options.silentErrors && t2.length > 0 && (e2.errors = t2), d(e2);
}
async executeParsers() {
let { output: e2 } = this;
await this.fileParser.parse();
let t2 = Object.values(this.parsers).map((async (t3) => {
let i2 = await t3.parse();
t3.assignToOutput(e2, i2);
}));
this.options.silentErrors && (t2 = t2.map(((e3) => e3.catch(this.pushToErrors)))), await Promise.all(t2);
}
async extractThumbnail() {
this.setup();
let { options: e2, file: t2 } = this, i2 = A.get("tiff", e2);
var n2;
if (t2.tiff ? n2 = { start: 0, type: "tiff" } : t2.jpeg && (n2 = await this.fileParser.getOrFindSegment("tiff")), void 0 === n2) return;
let s2 = await this.fileParser.ensureSegmentChunk(n2), r2 = this.parsers.tiff = new i2(s2, e2, t2), a2 = await r2.extractThumbnail();
return t2.close && t2.close(), a2;
}
}
async function fe(e2, t2) {
let i2 = new ce(t2);
return await i2.read(e2), i2.parse();
}
var de = Object.freeze({ __proto__: null, parse: fe, Exifr: ce, fileParsers: T, segmentParsers: A, fileReaders: D, tagKeys: N, tagValues: G, tagRevivers: V, createDictionary: B, extendDictionary: E, fetchUrlAsArrayBuffer: L, readBlobAsArrayBuffer: U, chunkedProps: $, otherSegments: J, segments: q, tiffBlocks: Q, segmentsAndBlocks: Z, tiffExtractables: ee, inheritables: te, allFormatters: ie, Options: oe });
class pe {
constructor(e2, t2, i2) {
f(this, "errors", []), f(this, "ensureSegmentChunk", (async (e3) => {
let t3 = e3.start, i3 = e3.size || 65536;
if (this.file.chunked) if (this.file.available(t3, i3)) e3.chunk = this.file.subarray(t3, i3);
else try {
e3.chunk = await this.file.readChunk(t3, i3);
} catch (t4) {
m(`Couldn't read segment: ${JSON.stringify(e3)}. ${t4.message}`);
}
else this.file.byteLength > t3 + i3 ? e3.chunk = this.file.subarray(t3, i3) : void 0 === e3.size ? e3.chunk = this.file.subarray(t3) : m("Segment unreachable: " + JSON.stringify(e3));
return e3.chunk;
})), this.extendOptions && this.extendOptions(e2), this.options = e2, this.file = t2, this.parsers = i2;
}
injectSegment(e2, t2) {
this.options[e2].enabled && this.createParser(e2, t2);
}
createParser(e2, t2) {
let i2 = new (A.get(e2))(t2, this.options, this.file);
return this.parsers[e2] = i2;
}
createParsers(e2) {
for (let t2 of e2) {
let { type: e3, chunk: i2 } = t2, n2 = this.options[e3];
if (n2 && n2.enabled) {
let t3 = this.parsers[e3];
t3 && t3.append || t3 || this.createParser(e3, i2);
}
}
}
async readSegments(e2) {
let t2 = e2.map(this.ensureSegmentChunk);
await Promise.all(t2);
}
}
class ge {
static findPosition(e2, t2) {
let i2 = e2.getUint16(t2 + 2) + 2, n2 = "function" == typeof this.headerLength ? this.headerLength(e2, t2, i2) : this.headerLength, s2 = t2 + n2, r2 = i2 - n2;
return { offset: t2, length: i2, headerLength: n2, start: s2, size: r2, end: s2 + r2 };
}
static parse(e2, t2 = {}) {
return new this(e2, new oe({ [this.type]: t2 }), e2).parse();
}
normalizeInput(e2) {
return e2 instanceof I ? e2 : new I(e2);
}
constructor(e2, t2 = {}, i2) {
f(this, "errors", []), f(this, "raw", /* @__PURE__ */ new Map()), f(this, "handleError", ((e3) => {
if (!this.options.silentErrors) throw e3;
this.errors.push(e3.message);
})), this.chunk = this.normalizeInput(e2), this.file = i2, this.type = this.constructor.type, this.globalOptions = this.options = t2, this.localOptions = t2[this.type], this.canTranslate = this.localOptions && this.localOptions.translate;
}
translate() {
this.canTranslate && (this.translated = this.translateBlock(this.raw, this.type));
}
get output() {
return this.translated ? this.translated : this.raw ? Object.fromEntries(this.raw) : void 0;
}
translateBlock(e2, t2) {
let i2 = V.get(t2), n2 = G.get(t2), s2 = N.get(t2), r2 = this.options[t2], a2 = r2.reviveValues && !!i2, o2 = r2.translateValues && !!n2, l2 = r2.translateKeys && !!s2, h2 = {};
for (let [t3, r3] of e2) a2 && i2.has(t3) ? r3 = i2.get(t3)(r3) : o2 && n2.has(t3) && (r3 = this.translateValue(r3, n2.get(t3))), l2 && s2.has(t3) && (t3 = s2.get(t3) || t3), h2[t3] = r3;
return h2;
}
translateValue(e2, t2) {
return t2[e2] || t2.DEFAULT || e2;
}
assignToOutput(e2, t2) {
this.assignObjectToOutput(e2, this.constructor.type, t2);
}
assignObjectToOutput(e2, t2, i2) {
if (this.globalOptions.mergeOutput) return Object.assign(e2, i2);
e2[t2] ? Object.assign(e2[t2], i2) : e2[t2] = i2;
}
}
f(ge, "headerLength", 4), f(ge, "type", void 0), f(ge, "multiSegment", false), f(ge, "canHandle", (() => false));
function me(e2) {
return 192 === e2 || 194 === e2 || 196 === e2 || 219 === e2 || 221 === e2 || 218 === e2 || 254 === e2;
}
function Se(e2) {
return e2 >= 224 && e2 <= 239;
}
function Ce(e2, t2, i2) {
for (let [n2, s2] of A) if (s2.canHandle(e2, t2, i2)) return n2;
}
class ye extends pe {
constructor(...e2) {
super(...e2), f(this, "appSegments", []), f(this, "jpegSegments", []), f(this, "unknownSegments", []);
}
static canHandle(e2, t2) {
return 65496 === t2;
}
async parse() {
await this.findAppSegments(), await this.readSegments(this.appSegments), this.mergeMultiSegments(), this.createParsers(this.mergedAppSegments || this.appSegments);
}
setupSegmentFinderArgs(e2) {
true === e2 ? (this.findAll = true, this.wanted = new Set(A.keyList())) : (e2 = void 0 === e2 ? A.keyList().filter(((e3) => this.options[e3].enabled)) : e2.filter(((e3) => this.options[e3].enabled && A.has(e3))), this.findAll = false, this.remaining = new Set(e2), this.wanted = new Set(e2)), this.unfinishedMultiSegment = false;
}
async findAppSegments(e2 = 0, t2) {
this.setupSegmentFinderArgs(t2);
let { file: i2, findAll: n2, wanted: s2, remaining: r2 } = this;
if (!n2 && this.file.chunked && (n2 = Array.from(s2).some(((e3) => {
let t3 = A.get(e3), i3 = this.options[e3];
return t3.multiSegment && i3.multiSegment;
})), n2 && await this.file.readWhole()), e2 = this.findAppSegmentsInRange(e2, i2.byteLength), !this.options.onlyTiff && i2.chunked) {
let t3 = false;
for (; r2.size > 0 && !t3 && (i2.canReadNextChunk || this.unfinishedMultiSegment); ) {
let { nextChunkOffset: n3 } = i2, s3 = this.appSegments.some(((e3) => !this.file.available(e3.offset || e3.start, e3.length || e3.size)));
if (t3 = e2 > n3 && !s3 ? !await i2.readNextChunk(e2) : !await i2.readNextChunk(n3), void 0 === (e2 = this.findAppSegmentsInRange(e2, i2.byteLength))) return;
}
}
}
findAppSegmentsInRange(e2, t2) {
t2 -= 2;
let i2, n2, s2, r2, a2, o2, { file: l2, findAll: h2, wanted: u2, remaining: c2, options: f2 } = this;
for (; e2 < t2; e2++) if (255 === l2.getUint8(e2)) {
if (i2 = l2.getUint8(e2 + 1), Se(i2)) {
if (n2 = l2.getUint16(e2 + 2), s2 = Ce(l2, e2, n2), s2 && u2.has(s2) && (r2 = A.get(s2), a2 = r2.findPosition(l2, e2), o2 = f2[s2], a2.type = s2, this.appSegments.push(a2), !h2 && (r2.multiSegment && o2.multiSegment ? (this.unfinishedMultiSegment = a2.chunkNumber < a2.chunkCount, this.unfinishedMultiSegment || c2.delete(s2)) : c2.delete(s2), 0 === c2.size))) break;
f2.recordUnknownSegments && (a2 = ge.findPosition(l2, e2), a2.marker = i2, this.unknownSegments.push(a2)), e2 += n2 + 1;
} else if (me(i2)) {
if (n2 = l2.getUint16(e2 + 2), 218 === i2 && false !== f2.stopAfterSos) return;
f2.recordJpegSegments && this.jpegSegments.push({ offset: e2, length: n2, marker: i2 }), e2 += n2 + 1;
}
}
return e2;
}
mergeMultiSegments() {
if (!this.appSegments.some(((e3) => e3.multiSegment))) return;
let e2 = (function(e3, t2) {
let i2, n2, s2, r2 = /* @__PURE__ */ new Map();
for (let a2 = 0; a2 < e3.length; a2++) i2 = e3[a2], n2 = i2[t2], r2.has(n2) ? s2 = r2.get(n2) : r2.set(n2, s2 = []), s2.push(i2);
return Array.from(r2);
})(this.appSegments, "type");
this.mergedAppSegments = e2.map((([e3, t2]) => {
let i2 = A.get(e3, this.options);
if (i2.handleMultiSegments) {
return { type: e3, chunk: i2.handleMultiSegments(t2) };
}
return t2[0];
}));
}
getSegment(e2) {
return this.appSegments.find(((t2) => t2.type === e2));
}
async getOrFindSegment(e2) {
let t2 = this.getSegment(e2);
return void 0 === t2 && (await this.findAppSegments(0, [e2]), t2 = this.getSegment(e2)), t2;
}
}
f(ye, "type", "jpeg"), T.set("jpeg", ye);
const be = [void 0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4];
class Pe extends ge {
parseHeader() {
var e2 = this.chunk.getUint16();
18761 === e2 ? this.le = true : 19789 === e2 && (this.le = false), this.chunk.le = this.le, this.headerParsed = true;
}
parseTags(e2, t2, i2 = /* @__PURE__ */ new Map()) {
let { pick: n2, skip: s2 } = this.options[t2];
n2 = new Set(n2);
let r2 = n2.size > 0, a2 = 0 === s2.size, o2 = this.chunk.getUint16(e2);
e2 += 2;
for (let l2 = 0; l2 < o2; l2++) {
let o3 = this.chunk.getUint16(e2);
if (r2) {
if (n2.has(o3) && (i2.set(o3, this.parseTag(e2, o3, t2)), n2.delete(o3), 0 === n2.size)) break;
} else !a2 && s2.has(o3) || i2.set(o3, this.parseTag(e2, o3, t2));
e2 += 12;
}
return i2;
}
parseTag(e2, t2, i2) {
let { chunk: n2 } = this, s2 = n2.getUint16(e2 + 2), r2 = n2.getUint32(e2 + 4), a2 = be[s2];
if (a2 * r2 <= 4 ? e2 += 8 : e2 = n2.getUint32(e2 + 8), (s2 < 1 || s2 > 13) && m(`Invalid TIFF value type. block: ${i2.toUpperCase()}, tag: ${t2.toString(16)}, type: ${s2}, offset ${e2}`), e2 > n2.byteLength && m(`Invalid TIFF value offset. block: ${i2.toUpperCase()}, tag: ${t2.toString(16)}, type: ${s2}, offset ${e2} is outside of chunk size ${n2.byteLength}`), 1 === s2) return n2.getUint8Array(e2, r2);
if (2 === s2) return S(n2.getString(e2, r2));
if (7 === s2) return n2.getUint8Array(e2, r2);
if (1 === r2) return this.parseTagValue(s2, e2);
{
let t3 = new ((function(e3) {
switch (e3) {
case 1:
return Uint8Array;
case 3:
return Uint16Array;
case 4:
return Uint32Array;
case 5:
return Array;
case 6:
return Int8Array;
case 8:
return Int16Array;
case 9:
return Int32Array;
case 10:
return Array;
case 11:
return Float32Array;
case 12:
return Float64Array;
default:
return Array;
}
})(s2))(r2), i3 = a2;
for (let n3 = 0; n3 < r2; n3++) t3[n3] = this.parseTagValue(s2, e2), e2 += i3;
return t3;
}
}
parseTagValue(e2, t2) {
let { chunk: i2 } = this;
switch (e2) {
case 1:
return i2.getUint8(t2);
case 3:
return i2.getUint16(t2);
case 4:
return i2.getUint32(t2);
case 5:
return i2.getUint32(t2) / i2.getUint32(t2 + 4);
case 6:
return i2.getInt8(t2);
case 8:
return i2.getInt16(t2);
case 9:
return i2.getInt32(t2);
case 10:
return i2.getInt32(t2) / i2.getInt32(t2 + 4);
case 11:
return i2.getFloat(t2);
case 12:
return i2.getDouble(t2);
case 13:
return i2.getUint32(t2);
default:
m(`Invalid tiff type ${e2}`);
}
}
}
class Ie extends Pe {
static canHandle(e2, t2) {
return 225 === e2.getUint8(t2 + 1) && 1165519206 === e2.getUint32(t2 + 4) && 0 === e2.getUint16(t2 + 8);
}
async parse() {
this.parseHeader();
let { options: e2 } = this;
return e2.ifd0.enabled && await this.parseIfd0Block(), e2.exif.enabled && await this.safeParse("parseExifBlock"), e2.gps.enabled && await this.safeParse("parseGpsBlock"), e2.interop.enabled && await this.safeParse("parseInteropBlock"), e2.ifd1.enabled && await this.safeParse("parseThumbnailBlock"), this.createOutput();
}
safeParse(e2) {
let t2 = this[e2]();
return void 0 !== t2.catch && (t2 = t2.catch(this.handleError)), t2;
}
findIfd0Offset() {
void 0 === this.ifd0Offset && (this.ifd0Offset = this.chunk.getUint32(4));
}
findIfd1Offset() {
if (void 0 === this.ifd1Offset) {
this.findIfd0Offset();
let e2 = this.chunk.getUint16(this.ifd0Offset), t2 = this.ifd0Offset + 2 + 12 * e2;
this.ifd1Offset = this.chunk.getUint32(t2);
}
}
parseBlock(e2, t2) {
let i2 = /* @__PURE__ */ new Map();
return this[t2] = i2, this.parseTags(e2, t2, i2), i2;
}
async parseIfd0Block() {
if (this.ifd0) return;
let { file: e2 } = this;
this.findIfd0Offset(), this.ifd0Offset < 8 && m("Malformed EXIF data"), !e2.chunked && this.ifd0Offset > e2.byteLength && m(`IFD0 offset points to outside of file.
this.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${e2.byteLength}`), e2.tiff && await e2.ensureChunk(this.ifd0Offset, C(this.options));
let t2 = this.parseBlock(this.ifd0Offset, "ifd0");
return 0 !== t2.size ? (this.exifOffset = t2.get(X), this.interopOffset = t2.get(Y), this.gpsOffset = t2.get(_), this.xmp = t2.get(j), this.iptc = t2.get(W), this.icc = t2.get(K), this.options.sanitize && (t2.delete(X), t2.delete(Y), t2.delete(_), t2.delete(j), t2.delete(W), t2.delete(K)), t2) : void 0;
}
async parseExifBlock() {
if (this.exif) return;
if (this.ifd0 || await this.parseIfd0Block(), void 0 === this.exifOffset) return;
this.file.tiff && await this.file.ensureChunk(this.exifOffset, C(this.options));
let e2 = this.parseBlock(this.exifOffset, "exif");
return this.interopOffset || (this.interopOffset = e2.get(Y)), this.makerNote = e2.get(z4), this.userComment = e2.get(H), this.options.sanitize && (e2.delete(Y), e2.delete(z4), e2.delete(H)), this.unpack(e2, 41728), this.unpack(e2, 41729), e2;
}
unpack(e2, t2) {
let i2 = e2.get(t2);
i2 && 1 === i2.length && e2.set(t2, i2[0]);
}
async parseGpsBlock() {
if (this.gps) return;
if (this.ifd0 || await this.parseIfd0Block(), void 0 === this.gpsOffset) return;
let e2 = this.parseBlock(this.gpsOffset, "gps");
return e2 && e2.has(2) && e2.has(4) && (e2.set("latitude", ke(...e2.get(2), e2.get(1))), e2.set("longitude", ke(...e2.get(4), e2.get(3)))), e2;
}
async parseInteropBlock() {
if (!this.interop && (this.ifd0 || await this.parseIfd0Block(), void 0 !== this.interopOffset || this.exif || await this.parseExifBlock(), void 0 !== this.interopOffset)) return this.parseBlock(this.interopOffset, "interop");
}
async parseThumbnailBlock(e2 = false) {
if (!this.ifd1 && !this.ifd1Parsed && (!this.options.mergeOutput || e2)) return this.findIfd1Offset(), this.ifd1Offset > 0 && (this.parseBlock(this.ifd1Offset, "ifd1"), this.ifd1Parsed = true), this.ifd1;
}
async extractThumbnail() {
if (this.headerParsed || this.parseHeader(), this.ifd1Parsed || await this.parseThumbnailBlock(true), void 0 === this.ifd1) return;
let e2 = this.ifd1.get(513), t2 = this.ifd1.get(514);
return this.chunk.getUint8Array(e2, t2);
}
get image() {
return this.ifd0;
}
get thumbnail() {
return this.ifd1;
}
createOutput() {
let e2, t2, i2, n2 = {};
for (t2 of Q) if (e2 = this[t2], !g(e2)) if (i2 = this.canTranslate ? this.translateBlock(e2, t2) : Object.fromEntries(e2), this.options.mergeOutput) {
if ("ifd1" === t2) continue;
Object.assign(n2, i2);
} else n2[t2] = i2;
return this.makerNote && (n2.makerNote = this.makerNote), this.userComment && (n2.userComment = this.userComment), n2;
}
assignToOutput(e2, t2) {
if (this.globalOptions.mergeOutput) Object.assign(e2, t2);
else for (let [i2, n2] of Object.entries(t2)) this.assignObjectToOutput(e2, i2, n2);
}
}
function ke(e2, t2, i2, n2) {
var s2 = e2 + t2 / 60 + i2 / 3600;
return "S" !== n2 && "W" !== n2 || (s2 *= -1), s2;
}
f(Ie, "type", "tiff"), f(Ie, "headerLength", 10), A.set("tiff", Ie);
var we = Object.freeze({ __proto__: null, default: de, Exifr: ce, fileParsers: T, segmentParsers: A, fileReaders: D, tagKeys: N, tagValues: G, tagRevivers: V, createDictionary: B, extendDictionary: E, fetchUrlAsArrayBuffer: L, readBlobAsArrayBuffer: U, chunkedProps: $, otherSegments: J, segments: q, tiffBlocks: Q, segmentsAndBlocks: Z, tiffExtractables: ee, inheritables: te, allFormatters: ie, Options: oe, parse: fe });
const Te = { ifd0: false, ifd1: false, exif: false, gps: false, interop: false, sanitize: false, reviveValues: true, translateKeys: false, translateValues: false, mergeOutput: false }, Ae = Object.assign({}, Te, { firstChunkSize: 4e4, gps: [1, 2, 3, 4] });
async function De(e2) {
let t2 = new ce(Ae);
await t2.read(e2);
let i2 = await t2.parse();
if (i2 && i2.gps) {
let { latitude: e3, longitude: t3 } = i2.gps;
return { latitude: e3, longitude: t3 };
}
}
const Oe = Object.assign({}, Te, { tiff: false, ifd1: true, mergeOutput: false });
async function xe(e2) {
let t2 = new ce(Oe);
await t2.read(e2);
let i2 = await t2.extractThumbnail();
return i2 && o ? r.from(i2) : i2;
}
async function ve(e2) {
let t2 = await this.thumbnail(e2);
if (void 0 !== t2) {
let e3 = new Blob([t2]);
return URL.createObjectURL(e3);
}
}
const Me = Object.assign({}, Te, { firstChunkSize: 4e4, ifd0: [274] });
async function Re(e2) {
let t2 = new ce(Me);
await t2.read(e2);
let i2 = await t2.parse();
if (i2 && i2.ifd0) return i2.ifd0[274];
}
const Le = Object.freeze({ 1: { dimensionSwapped: false, scaleX: 1, scaleY: 1, deg: 0, rad: 0 }, 2: { dimensionSwapped: false, scaleX: -1, scaleY: 1, deg: 0, rad: 0 }, 3: { dimensionSwapped: false, scaleX: 1, scaleY: 1, deg: 180, rad: 180 * Math.PI / 180 }, 4: { dimensionSwapped: false, scaleX: -1, scaleY: 1, deg: 180, rad: 180 * Math.PI / 180 }, 5: { dimensionSwapped: true, scaleX: 1, scaleY: -1, deg: 90, rad: 90 * Math.PI / 180 }, 6: { dimensionSwapped: true, scaleX: 1, scaleY: 1, deg: 90, rad: 90 * Math.PI / 180 }, 7: { dimensionSwapped: true, scaleX: 1, scaleY: -1, deg: 270, rad: 270 * Math.PI / 180 }, 8: { dimensionSwapped: true, scaleX: 1, scaleY: 1, deg: 270, rad: 270 * Math.PI / 180 } });
if (e.rotateCanvas = true, e.rotateCss = true, "object" == typeof navigator) {
let t2 = navigator.userAgent;
if (t2.includes("iPad") || t2.includes("iPhone")) {
let i2 = t2.match(/OS (\d+)_(\d+)/);
if (i2) {
let [, t3, n2] = i2, s2 = Number(t3) + 0.1 * Number(n2);
e.rotateCanvas = s2 < 13.4, e.rotateCss = false;
}
} else if (t2.includes("OS X 10")) {
let [, i2] = t2.match(/OS X 10[_.](\d+)/);
e.rotateCanvas = e.rotateCss = Number(i2) < 15;
}
if (t2.includes("Chrome/")) {
let [, i2] = t2.match(/Chrome\/(\d+)/);
e.rotateCanvas = e.rotateCss = Number(i2) < 81;
} else if (t2.includes("Firefox/")) {
let [, i2] = t2.match(/Firefox\/(\d+)/);
e.rotateCanvas = e.rotateCss = Number(i2) < 77;
}
}
async function Ue(t2) {
let i2 = await Re(t2);
return Object.assign({ canvas: e.rotateCanvas, css: e.rotateCss }, Le[i2]);
}
class Fe extends I {
constructor(...e2) {
super(...e2), f(this, "ranges", new Be()), 0 !== this.byteLength && this.ranges.add(0, this.byteLength);
}
_tryExtend(e2, t2, i2) {
if (0 === e2 && 0 === this.byteLength && i2) {
let e3 = new DataView(i2.buffer || i2, i2.byteOffset, i2.byteLength);
this._swapDataView(e3);
} else {
let i3 = e2 + t2;
if (i3 > this.byteLength) {
let { dataView: e3 } = this._extend(i3);
this._swapDataView(e3);
}
}
}
_extend(e2) {
let t2;
t2 = o ? r.allocUnsafe(e2) : new Uint8Array(e2);
let i2 = new DataView(t2.buffer, t2.byteOffset, t2.byteLength);
return t2.set(new Uint8Array(this.buffer, this.byteOffset, this.byteLength), 0), { uintView: t2, dataView: i2 };
}
subarray(e2, t2, i2 = false) {
return t2 = t2 || this._lengthToEnd(e2), i2 && this._tryExtend(e2, t2), this.ranges.add(e2, t2), super.subarray(e2, t2);
}
set(e2, t2, i2 = false) {
i2 && this._tryExtend(t2, e2.byteLength, e2);
let n2 = super.set(e2, t2);
return this.ranges.add(t2, n2.byteLength), n2;
}
async ensureChunk(e2, t2) {
this.chunked && (this.ranges.available(e2, t2) || await this.readChunk(e2, t2));
}
available(e2, t2) {
return this.ranges.available(e2, t2);
}
}
class Be {
constructor() {
f(this, "list", []);
}
get length() {
return this.list.length;
}
add(e2, t2, i2 = 0) {
let n2 = e2 + t2, s2 = this.list.filter(((t3) => Ee(e2, t3.offset, n2) || Ee(e2, t3.end, n2)));
if (s2.length > 0) {
e2 = Math.min(e2, ...s2.map(((e3) => e3.offset))), n2 = Math.max(n2, ...s2.map(((e3) => e3.end))), t2 = n2 - e2;
let i3 = s2.shift();
i3.offset = e2, i3.length = t2, i3.end = n2, this.list = this.list.filter(((e3) => !s2.includes(e3)));
} else this.list.push({ offset: e2, length: t2, end: n2 });
}
available(e2, t2) {
let i2 = e2 + t2;
return this.list.some(((t3) => t3.offset <= e2 && i2 <= t3.end));
}
}
function Ee(e2, t2, i2) {
return e2 <= t2 && t2 <= i2;
}
class Ne extends Fe {
constructor(e2, t2) {
super(0), f(this, "chunksRead", 0), this.input = e2, this.options = t2;
}
async readWhole() {
this.chunked = false, await this.readChunk(this.nextChunkOffset);
}
async readChunked() {
this.chunked = true, await this.readChunk(0, this.options.firstChunkSize);
}
async readNextChunk(e2 = this.nextChunkOffset) {
if (this.fullyRead) return this.chunksRead++, false;
let t2 = this.options.chunkSize, i2 = await this.readChunk(e2, t2);
return !!i2 && i2.byteLength === t2;
}
async readChunk(e2, t2) {
if (this.chunksRead++, 0 !== (t2 = this.safeWrapAddress(e2, t2))) return this._readChunk(e2, t2);
}
safeWrapAddress(e2, t2) {
return void 0 !== this.size && e2 + t2 > this.size ? Math.max(0, this.size - e2) : t2;
}
get nextChunkOffset() {
if (0 !== this.ranges.list.length) return this.ranges.list[0].length;
}
get canReadNextChunk() {
return this.chunksRead < this.options.chunkLimit;
}
get fullyRead() {
return void 0 !== this.size && this.nextChunkOffset === this.size;
}
read() {
return this.options.chunked ? this.readChunked() : this.readWhole();
}
close() {
}
}
D.set("blob", class extends Ne {
async readWhole() {
this.chunked = false;
let e2 = await U(this.input);
this._swapArrayBuffer(e2);
}
readChunked() {
return this.chunked = true, this.size = this.input.size, super.readChunked();
}
async _readChunk(e2, t2) {
let i2 = t2 ? e2 + t2 : void 0, n2 = this.input.slice(e2, i2), s2 = await U(n2);
return this.set(s2, e2, true);
}
});
var Ge = Object.freeze({ __proto__: null, default: we, Exifr: ce, fileParsers: T, segmentParsers: A, fileReaders: D, tagKeys: N, tagValues: G, tagRevivers: V, createDictionary: B, extendDictionary: E, fetchUrlAsArrayBuffer: L, readBlobAsArrayBuffer: U, chunkedProps: $, otherSegments: J, segments: q, tiffBlocks: Q, segmentsAndBlocks: Z, tiffExtractables: ee, inheritables: te, allFormatters: ie, Options: oe, parse: fe, gpsOnlyOptions: Ae, gps: De, thumbnailOnlyOptions: Oe, thumbnail: xe, thumbnailUrl: ve, orientationOnlyOptions: Me, orientation: Re, rotations: Le, get rotateCanvas() {
return e.rotateCanvas;
}, get rotateCss() {
return e.rotateCss;
}, rotation: Ue });
D.set("url", class extends Ne {
async readWhole() {
this.chunked = false;
let e2 = await L(this.input);
e2 instanceof ArrayBuffer ? this._swapArrayBuffer(e2) : e2 instanceof Uint8Array && this._swapBuffer(e2);
}
async _readChunk(e2, t2) {
let i2 = t2 ? e2 + t2 - 1 : void 0, n2 = this.options.httpHeaders || {};
(e2 || i2) && (n2.range = `bytes=${[e2, i2].join("-")}`);
let s2 = await u(this.input, { headers: n2 }), r2 = await s2.arrayBuffer(), a2 = r2.byteLength;
if (416 !== s2.status) return a2 !== t2 && (this.size = e2 + a2), this.set(r2, e2, true);
}
});
I.prototype.getUint64 = function(e2) {
let t2 = this.getUint32(e2), i2 = this.getUint32(e2 + 4);
return t2 < 1048575 ? t2 << 32 | i2 : void 0 !== typeof a ? (console.warn("Using BigInt because of type 64uint but JS can only handle 53b numbers."), a(t2) << a(32) | a(i2)) : void m("Trying to read 64b value but JS can only handle 53b numbers.");
};
class Ve extends pe {
parseBoxes(e2 = 0) {
let t2 = [];
for (; e2 < this.file.byteLength - 4; ) {
let i2 = this.parseBoxHead(e2);
if (t2.push(i2), 0 === i2.length) break;
e2 += i2.length;
}
return t2;
}
parseSubBoxes(e2) {
e2.boxes = this.parseBoxes(e2.start);
}
findBox(e2, t2) {
return void 0 === e2.boxes && this.parseSubBoxes(e2), e2.boxes.find(((e3) => e3.kind === t2));
}
parseBoxHead(e2) {
let t2 = this.file.getUint32(e2), i2 = this.file.getString(e2 + 4, 4), n2 = e2 + 8;
return 1 === t2 && (t2 = this.file.getUint64(e2 + 8), n2 += 8), { offset: e2, length: t2, kind: i2, start: n2 };
}
parseBoxFullHead(e2) {
if (void 0 !== e2.version) return;
let t2 = this.file.getUint32(e2.start);
e2.version = t2 >> 24, e2.start += 4;
}
}
class ze extends Ve {
static canHandle(e2, t2) {
if (0 !== t2) return false;
let i2 = e2.getUint16(2);
if (i2 > 50) return false;
let n2 = 16, s2 = [];
for (; n2 < i2; ) s2.push(e2.getString(n2, 4)), n2 += 4;
return s2.includes(this.type);
}
async parse() {
let e2 = this.file.getUint32(0), t2 = this.parseBoxHead(e2);
for (; "meta" !== t2.kind; ) e2 += t2.length, await this.file.ensureChunk(e2, 16), t2 = this.parseBoxHead(e2);
await this.file.ensureChunk(t2.offset, t2.length), this.parseBoxFullHead(t2), this.parseSubBoxes(t2), this.options.icc.enabled && await this.findIcc(t2), this.options.tiff.enabled && await this.findExif(t2);
}
async registerSegment(e2, t2, i2) {
await this.file.ensureChunk(t2, i2);
let n2 = this.file.subarray(t2, i2);
this.createParser(e2, n2);
}
async findIcc(e2) {
let t2 = this.findBox(e2, "iprp");
if (void 0 === t2) return;
let i2 = this.findBox(t2, "ipco");
if (void 0 === i2) return;
let n2 = this.findBox(i2, "colr");
void 0 !== n2 && await this.registerSegment("icc", n2.offset + 12, n2.length);
}
async findExif(e2) {
let t2 = this.findBox(e2, "iinf");
if (void 0 === t2) return;
let i2 = this.findBox(e2, "iloc");
if (void 0 === i2) return;
let n2 = this.findExifLocIdInIinf(t2), s2 = this.findExtentInIloc(i2, n2);
if (void 0 === s2) return;
let [r2, a2] = s2;
await this.file.ensureChunk(r2, a2);
let o2 = 4 + this.file.getUint32(r2);
r2 += o2, a2 -= o2, await this.registerSegment("tiff", r2, a2);
}
findExifLocIdInIinf(e2) {
this.parseBoxFullHead(e2);
let t2, i2, n2, s2, r2 = e2.start, a2 = this.file.getUint16(r2);
for (r2 += 2; a2--; ) {
if (t2 = this.parseBoxHead(r2), this.parseBoxFullHead(t2), i2 = t2.start, t2.version >= 2 && (n2 = 3 === t2.version ? 4 : 2, s2 = this.file.getString(i2 + n2 + 2, 4), "Exif" === s2)) return this.file.getUintBytes(i2, n2);
r2 += t2.length;
}
}
get8bits(e2) {
let t2 = this.file.getUint8(e2);
return [t2 >> 4, 15 & t2];
}
findExtentInIloc(e2, t2) {
this.parseBoxFullHead(e2);
let i2 = e2.start, [n2, s2] = this.get8bits(i2++), [r2, a2] = this.get8bits(i2++), o2 = 2 === e2.version ? 4 : 2, l2 = 1 === e2.version || 2 === e2.version ? 2 : 0, h2 = a2 + n2 + s2, u2 = 2 === e2.version ? 4 : 2, c2 = this.file.getUintBytes(i2, u2);
for (i2 += u2; c2--; ) {
let e3 = this.file.getUintBytes(i2, o2);
i2 += o2 + l2 + 2 + r2;
let u3 = this.file.getUint16(i2);
if (i2 += 2, e3 === t2) return u3 > 1 && console.warn("ILOC box has more than one extent but we're only processing one\nPlease create an issue at https://github.com/MikeKovarik/exifr with this file"), [this.file.getUintBytes(i2 + a2, n2), this.file.getUintBytes(i2 + a2 + n2, s2)];
i2 += u3 * h2;
}
}
}
class He extends ze {
}
f(He, "type", "heic");
class je extends ze {
}
f(je, "type", "avif"), T.set("heic", He), T.set("avif", je), B(N, ["ifd0", "ifd1"], [[256, "ImageWidth"], [257, "ImageHeight"], [258, "BitsPerSample"], [259, "Compression"], [262, "PhotometricInterpretation"], [270, "ImageDescription"], [271, "Make"], [272, "Model"], [273, "StripOffsets"], [274, "Orientation"], [277, "SamplesPerPixel"], [278, "RowsPerStrip"], [279, "StripByteCounts"], [282, "XResolution"], [283, "YResolution"], [284, "PlanarConfiguration"], [296, "ResolutionUnit"], [301, "TransferFunction"], [305, "Software"], [306, "ModifyDate"], [315, "Artist"], [316, "HostComputer"], [317, "Predictor"], [318, "WhitePoint"], [319, "PrimaryChromaticities"], [513, "ThumbnailOffset"], [514, "ThumbnailLength"], [529, "YCbCrCoefficients"], [530, "YCbCrSubSampling"], [531, "YCbCrPositioning"], [532, "ReferenceBlackWhite"], [700, "ApplicationNotes"], [33432, "Copyright"], [33723, "IPTC"], [34665, "ExifIFD"], [34675, "ICC"], [34853, "GpsIFD"], [330, "SubIFD"], [40965, "InteropIFD"], [40091, "XPTitle"], [40092, "XPComment"], [40093, "XPAuthor"], [40094, "XPKeywords"], [40095, "XPSubject"]]), B(N, "exif", [[33434, "ExposureTime"], [33437, "FNumber"], [34850, "ExposureProgram"], [34852, "SpectralSensitivity"], [34855, "ISO"], [34858, "TimeZoneOffset"], [34859, "SelfTimerMode"], [34864, "SensitivityType"], [34865, "StandardOutputSensitivity"], [34866, "RecommendedExposureIndex"], [34867, "ISOSpeed"], [34868, "ISOSpeedLatitudeyyy"], [34869, "ISOSpeedLatitudezzz"], [36864, "ExifVersion"], [36867, "DateTimeOriginal"], [36868, "CreateDate"], [36873, "GooglePlusUploadCode"], [36880, "OffsetTime"], [36881, "OffsetTimeOriginal"], [36882, "OffsetTimeDigitized"], [37121, "ComponentsConfiguration"], [37122, "CompressedBitsPerPixel"], [37377, "ShutterSpeedValue"], [37378, "ApertureValue"], [37379, "BrightnessValue"], [37380, "ExposureCompensation"], [37381, "MaxApertureValue"], [37382, "SubjectDistance"], [37383, "MeteringMode"], [37384, "LightSource"], [37385, "Flash"], [37386, "FocalLength"], [37393, "ImageNumber"], [37394, "SecurityClassification"], [37395, "ImageHistory"], [37396, "SubjectArea"], [37500, "MakerNote"], [37510, "UserComment"], [37520, "SubSecTime"], [37521, "SubSecTimeOriginal"], [37522, "SubSecTimeDigitized"], [37888, "AmbientTemperature"], [37889, "Humidity"], [37890, "Pressure"], [37891, "WaterDepth"], [37892, "Acceleration"], [37893, "CameraElevationAngle"], [40960, "FlashpixVersion"], [40961, "ColorSpace"], [40962, "ExifImageWidth"], [40963, "ExifImageHeight"], [40964, "RelatedSoundFile"], [41483, "FlashEnergy"], [41486, "FocalPlaneXResolution"], [41487, "FocalPlaneYResolution"], [41488, "FocalPlaneResolutionUnit"], [41492, "SubjectLocation"], [41493, "ExposureIndex"], [41495, "SensingMethod"], [41728, "FileSource"], [41729, "SceneType"], [41730, "CFAPattern"], [41985, "CustomRendered"], [41986, "ExposureMode"], [41987, "WhiteBalance"], [41988, "DigitalZoomRatio"], [41989, "FocalLengthIn35mmFormat"], [41990, "SceneCaptureType"], [41991, "GainControl"], [41992, "Contrast"], [41993, "Saturation"], [41994, "Sharpness"], [41996, "SubjectDistanceRange"], [42016, "ImageUniqueID"], [42032, "OwnerName"], [42033, "SerialNumber"], [42034, "LensInfo"], [42035, "LensMake"], [42036, "LensModel"], [42037, "LensSerialNumber"], [42080, "CompositeImage"], [42081, "CompositeImageCount"], [42082, "CompositeImageExposureTimes"], [42240, "Gamma"], [59932, "Padding"], [59933, "OffsetSchema"], [65e3, "OwnerName"], [65001, "SerialNumber"], [65002, "Lens"], [65100, "RawFile"], [65101, "Converter"], [65102, "WhiteBalance"], [65105, "Exposure"], [65106, "Shadows"], [65107, "Brightness"], [65108, "Contrast"], [65109, "Saturation"], [65110, "Sharpness"], [65111, "Smoothness"], [65112, "MoireFilter"], [40965, "InteropIFD"]]), B(N, "gps", [[0, "GPSVersionID"], [1, "GPSLatitudeRef"], [2, "GPSLatitude"], [3, "GPSLongitudeRef"], [4, "GPSLongitude"], [5, "GPSAltitudeRef"], [6, "GPSAltitude"], [7, "GPSTimeStamp"], [8, "GPSSatellites"], [9, "GPSStatus"], [10, "GPSMeasureMode"], [11, "GPSDOP"], [12, "GPSSpeedRef"], [13, "GPSSpeed"], [14, "GPSTrackRef"], [15, "GPSTrack"], [16, "GPSImgDirectionRef"], [17, "GPSImgDirection"], [18, "GPSMapDatum"], [19, "GPSDestLatitudeRef"], [20, "GPSDestLatitude"], [21, "GPSDestLongitudeRef"], [22, "GPSDestLongitude"], [23, "GPSDestBearingRef"], [24, "GPSDestBearing"], [25, "GPSDestDistanceRef"], [26, "GPSDestDistance"], [27, "GPSProcessingMethod"], [28, "GPSAreaInformation"], [29, "GPSDateStamp"], [30, "GPSDifferential"], [31, "GPSHPositioningError"]]), B(G, ["ifd0", "ifd1"], [[274, { 1: "Horizontal (normal)", 2: "Mirror horizontal", 3: "Rotate 180", 4: "Mirror vertical", 5: "Mirror horizontal and rotate 270 CW", 6: "Rotate 90 CW", 7: "Mirror horizontal and rotate 90 CW", 8: "Rotate 270 CW" }], [296, { 1: "None", 2: "inches", 3: "cm" }]]);
let We = B(G, "exif", [[34850, { 0: "Not defined", 1: "Manual", 2: "Normal program", 3: "Aperture priority", 4: "Shutter priority", 5: "Creative program", 6: "Action program", 7: "Portrait mode", 8: "Landscape mode" }], [37121, { 0: "-", 1: "Y", 2: "Cb", 3: "Cr", 4: "R", 5: "G", 6: "B" }], [37383, { 0: "Unknown", 1: "Average", 2: "CenterWeightedAverage", 3: "Spot", 4: "MultiSpot", 5: "Pattern", 6: "Partial", 255: "Other" }], [37384, { 0: "Unknown", 1: "Daylight", 2: "Fluorescent", 3: "Tungsten (incandescent light)", 4: "Flash", 9: "Fine weather", 10: "Cloudy weather", 11: "Shade", 12: "Daylight fluorescent (D 5700 - 7100K)", 13: "Day white fluorescent (N 4600 - 5400K)", 14: "Cool white fluorescent (W 3900 - 4500K)", 15: "White fluorescent (WW 3200 - 3700K)", 17: "Standard light A", 18: "Standard light B", 19: "Standard light C", 20: "D55", 21: "D65", 22: "D75", 23: "D50", 24: "ISO studio tungsten", 255: "Other" }], [37385, { 0: "Flash did not fire", 1: "Flash fired", 5: "Strobe return light not detected", 7: "Strobe return light detected", 9: "Flash fired, compulsory flash mode", 13: "Flash fired, compulsory flash mode, return light not detected", 15: "Flash fired, compulsory flash mode, return light detected", 16: "Flash did not fire, compulsory flash mode", 24: "Flash did not fire, auto mode", 25: "Flash fired, auto mode", 29: "Flash fired, auto mode, return light not detected", 31: "Flash fired, auto mode, return light detected", 32: "No flash function", 65: "Flash fired, red-eye reduction mode", 69: "Flash fired, red-eye reduction mode, return light not detected", 71: "Flash fired, red-eye reduction mode, return light detected", 73: "Flash fired, compulsory flash mode, red-eye reduction mode", 77: "Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected", 79: "Flash fired, compulsory flash mode, red-eye reduction mode, return light detected", 89: "Flash fired, auto mode, red-eye reduction mode", 93: "Flash fired, auto mode, return light not detected, red-eye reduction mode", 95: "Flash fired, auto mode, return light detected, red-eye reduction mode" }], [41495, { 1: "Not defined", 2: "One-chip color area sensor", 3: "Two-chip color area sensor", 4: "Three-chip color area sensor", 5: "Color sequential area sensor", 7: "Trilinear sensor", 8: "Color sequential linear sensor" }], [41728, { 1: "Film Scanner", 2: "Reflection Print Scanner", 3: "Digital Camera" }], [41729, { 1: "Directly photographed" }], [41985, { 0: "Normal", 1: "Custom", 2: "HDR (no original saved)", 3: "HDR (original saved)", 4: "Original (for HDR)", 6: "Panorama", 7: "Portrait HDR", 8: "Portrait" }], [41986, { 0: "Auto", 1: "Manual", 2: "Auto bracket" }], [41987, { 0: "Auto", 1: "Manual" }], [41990, { 0: "Standard", 1: "Landscape", 2: "Portrait", 3: "Night", 4: "Other" }], [41991, { 0: "None", 1: "Low gain up", 2: "High gain up", 3: "Low gain down", 4: "High gain down" }], [41996, { 0: "Unknown", 1: "Macro", 2: "Close", 3: "Distant" }], [42080, { 0: "Unknown", 1: "Not a Composite Image", 2: "General Composite Image", 3: "Composite Image Captured While Shooting" }]]);
const Ke = { 1: "No absolute unit of measurement", 2: "Inch", 3: "Centimeter" };
We.set(37392, Ke), We.set(41488, Ke);
const Xe = { 0: "Normal", 1: "Low", 2: "High" };
function _e(e2) {
return "object" == typeof e2 && void 0 !== e2.length ? e2[0] : e2;
}
function Ye(e2) {
let t2 = Array.from(e2).slice(1);
return t2[1] > 15 && (t2 = t2.map(((e3) => String.fromCharCode(e3)))), "0" !== t2[2] && 0 !== t2[2] || t2.pop(), t2.join(".");
}
function $e(e2) {
if ("string" == typeof e2) {
var [t2, i2, n2, s2, r2, a2] = e2.trim().split(/[-: ]/g).map(Number), o2 = new Date(t2, i2 - 1, n2);
return Number.isNaN(s2) || Number.isNaN(r2) || Number.isNaN(a2) || (o2.setHours(s2), o2.setMinutes(r2), o2.setSeconds(a2)), Number.isNaN(+o2) ? e2 : o2;
}
}
function Je(e2) {
if ("string" == typeof e2) return e2;
let t2 = [];
if (0 === e2[1] && 0 === e2[e2.length - 1]) for (let i2 = 0; i2 < e2.length; i2 += 2) t2.push(qe(e2[i2 + 1], e2[i2]));
else for (let i2 = 0; i2 < e2.length; i2 += 2) t2.push(qe(e2[i2], e2[i2 + 1]));
return S(String.fromCodePoint(...t2));
}
function qe(e2, t2) {
return e2 << 8 | t2;
}
We.set(41992, Xe), We.set(41993, Xe), We.set(41994, Xe), B(V, ["ifd0", "ifd1"], [[50827, function(e2) {
return "string" != typeof e2 ? P(e2) : e2;
}], [306, $e], [40091, Je], [40092, Je], [40093, Je], [40094, Je], [40095, Je]]), B(V, "exif", [[40960, Ye], [36864, Ye], [36867, $e], [36868, $e], [40962, _e], [40963, _e]]), B(V, "gps", [[0, (e2) => Array.from(e2).join(".")], [7, (e2) => Array.from(e2).join(":")]]);
const Qe = "http://ns.adobe.com/", Ze = "http://ns.adobe.com/xmp/extension/";
class et extends ge {
static canHandle(e2, t2) {
return 225 === e2.getUint8(t2 + 1) && 1752462448 === e2.getUint32(t2 + 4) && e2.getString(t2 + 4, Qe.length) === Qe;
}
static headerLength(e2, t2) {
return e2.getString(t2 + 4, Ze.length) === Ze ? 79 : 4 + "http://ns.adobe.com/xap/1.0/".length + 1;
}
static findPosition(e2, t2) {
let i2 = super.findPosition(e2, t2);
return i2.multiSegment = i2.extended = 79 === i2.headerLength, i2.multiSegment ? (i2.chunkCount = e2.getUint8(t2 + 72), i2.chunkNumber = e2.getUint8(t2 + 76), 0 !== e2.getUint8(t2 + 77) && i2.chunkNumber++) : (i2.chunkCount = 1 / 0, i2.chunkNumber = -1), i2;
}
static handleMultiSegments(e2) {
return e2.map(((e3) => e3.chunk.getString())).join("");
}
normalizeInput(e2) {
return "string" == typeof e2 ? e2 : I.from(e2).getString();
}
parse(e2 = this.chunk) {
if (!this.localOptions.parse) return e2;
e2 = (function(e3) {
let t3 = {}, i3 = {};
for (let e4 of ut) t3[e4] = [], i3[e4] = 0;
return e3.replace(ct, ((e4, n3, s2) => {
if ("<" === n3) {
let n4 = ++i3[s2];
return t3[s2].push(n4), `${e4}#${n4}`;
}
return `${e4}#${t3[s2].pop()}`;
}));
})(e2);
let t2 = nt.findAll(e2, "rdf", "Description");
0 === t2.length && t2.push(new nt("rdf", "Description", void 0, e2));
let i2, n2 = {};
for (let e3 of t2) for (let t3 of e3.properties) i2 = ot(t3.ns, n2), st(t3, i2);
return (function(e3) {
let t3;
for (let i3 in e3) t3 = e3[i3] = d(e3[i3]), void 0 === t3 && delete e3[i3];
return d(e3);
})(n2);
}
assignToOutput(e2, t2) {
if (this.localOptions.parse) for (let [i2, n2] of Object.entries(t2)) switch (i2) {
case "tiff":
this.assignObjectToOutput(e2, "ifd0", n2);
break;
case "exif":
this.assignObjectToOutput(e2, "exif", n2);
break;
case "xmlns":
break;
default:
this.assignObjectToOutput(e2, i2, n2);
}
else e2.xmp = t2;
}
}
f(et, "type", "xmp"), f(et, "multiSegment", true), A.set("xmp", et);
class tt {
static findAll(e2) {
return lt(e2, /([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm).map(tt.unpackMatch);
}
static unpackMatch(e2) {
let t2 = e2[1], i2 = e2[2], n2 = e2[3].slice(1, -1);
return n2 = ht(n2), new tt(t2, i2, n2);
}
constructor(e2, t2, i2) {
this.ns = e2, this.name = t2, this.value = i2;
}
serialize() {
return this.value;
}
}
const it = "[\\w\\d-]+";
class nt {
static findAll(e2, t2, i2) {
if (void 0 !== t2 || void 0 !== i2) {
t2 = t2 || it, i2 = i2 || it;
var n2 = new RegExp(`<(${t2}):(${i2})(#\\d+)?((\\s+?[\\w\\d-:]+=("[^"]*"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)`, "gm");
} else n2 = /<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm;
return lt(e2, n2).map(nt.unpackMatch);
}
static unpackMatch(e2) {
let t2 = e2[1], i2 = e2[2], n2 = e2[4], s2 = e2[8];
return new nt(t2, i2, n2, s2);
}
constructor(e2, t2, i2, n2) {
this.ns = e2, this.name = t2, this.attrString = i2, this.innerXml = n2, this.attrs = tt.findAll(i2), this.children = nt.findAll(n2), this.value = 0 === this.children.length ? ht(n2) : void 0, this.properties = [...this.attrs, ...this.children];
}
get isPrimitive() {
return void 0 !== this.value && 0 === this.attrs.length && 0 === this.children.length;
}
get isListContainer() {
return 1 === this.children.length && this.children[0].isList;
}
get isList() {
let { ns: e2, name: t2 } = this;
return "rdf" === e2 && ("Seq" === t2 || "Bag" === t2 || "Alt" === t2);
}
get isListItem() {
return "rdf" === this.ns && "li" === this.name;
}
serialize() {
if (0 === this.properties.length && void 0 === this.value) return;
if (this.isPrimitive) return this.value;
if (this.isListContainer) return this.children[0].serialize();
if (this.isList) return at(this.children.map(rt));
if (this.isListItem && 1 === this.children.length && 0 === this.attrs.length) return this.children[0].serialize();
let e2 = {};
for (let t2 of this.properties) st(t2, e2);
return void 0 !== this.value && (e2.value = this.value), d(e2);
}
}
function st(e2, t2) {
let i2 = e2.serialize();
void 0 !== i2 && (t2[e2.name] = i2);
}
var rt = (e2) => e2.serialize(), at = (e2) => 1 === e2.length ? e2[0] : e2, ot = (e2, t2) => t2[e2] ? t2[e2] : t2[e2] = {};
function lt(e2, t2) {
let i2, n2 = [];
if (!e2) return n2;
for (; null !== (i2 = t2.exec(e2)); ) n2.push(i2);
return n2;
}
function ht(e2) {
if ((function(e3) {
return null == e3 || "null" === e3 || "undefined" === e3 || "" === e3 || "" === e3.trim();
})(e2)) return;
let t2 = Number(e2);
if (!Number.isNaN(t2)) return t2;
let i2 = e2.toLowerCase();
return "true" === i2 || "false" !== i2 && e2.trim();
}
const ut = ["rdf:li", "rdf:Seq", "rdf:Bag", "rdf:Alt", "rdf:Description"], ct = new RegExp(`(<|\\/)(${ut.join("|")})`, "g");
var ft = Object.freeze({ __proto__: null, default: Ge, Exifr: ce, fileParsers: T, segmentParsers: A, fileReaders: D, tagKeys: N, tagValues: G, tagRevivers: V, createDictionary: B, extendDictionary: E, fetchUrlAsArrayBuffer: L, readBlobAsArrayBuffer: U, chunkedProps: $, otherSegments: J, segments: q, tiffBlocks: Q, segmentsAndBlocks: Z, tiffExtractables: ee, inheritables: te, allFormatters: ie, Options: oe, parse: fe, gpsOnlyOptions: Ae, gps: De, thumbnailOnlyOptions: Oe, thumbnail: xe, thumbnailUrl: ve, orientationOnlyOptions: Me, orientation: Re, rotations: Le, get rotateCanvas() {
return e.rotateCanvas;
}, get rotateCss() {
return e.rotateCss;
}, rotation: Ue });
const dt = ["xmp", "icc", "iptc", "tiff"], pt = () => {
};
async function gt(e2, t2, i2) {
let n2 = i2[e2];
return n2.enabled = true, n2.parse = true, A.get(e2).parse(t2, n2);
}
let mt = h("fs", ((e2) => e2.promises));
D.set("fs", class extends Ne {
async readWhole() {
this.chunked = false, this.fs = await mt;
let e2 = await this.fs.readFile(this.input);
this._swapBuffer(e2);
}
async readChunked() {
this.chunked = true, this.fs = await mt, await this.open(), await this.readChunk(0, this.options.firstChunkSize);
}
async open() {
void 0 === this.fh && (this.fh = await this.fs.open(this.input, "r"), this.size = (await this.fh.stat(this.input)).size);
}
async _readChunk(e2, t2) {
void 0 === this.fh && await this.open(), e2 + t2 > this.size && (t2 = this.size - e2);
var i2 = this.subarray(e2, t2, true);
return await this.fh.read(i2.dataView, 0, t2, e2), i2;
}
async close() {
if (this.fh) {
let e2 = this.fh;
this.fh = void 0, await e2.close();
}
}
});
D.set("base64", class extends Ne {
constructor(...e2) {
super(...e2), this.input = this.input.replace(/^data:([^;]+);base64,/gim, ""), this.size = this.input.length / 4 * 3, this.input.endsWith("==") ? this.size -= 2 : this.input.endsWith("=") && (this.size -= 1);
}
async _readChunk(e2, t2) {
let i2, n2, s2 = this.input;
void 0 === e2 ? (e2 = 0, i2 = 0, n2 = 0) : (i2 = 4 * Math.floor(e2 / 3), n2 = e2 - i2 / 4 * 3), void 0 === t2 && (t2 = this.size);
let a2 = e2 + t2, l2 = i2 + 4 * Math.ceil(a2 / 3);
s2 = s2.slice(i2, l2);
let h2 = Math.min(t2, this.size - e2);
if (o) {
let t3 = r.from(s2, "base64").slice(n2, n2 + h2);
return this.set(t3, e2, true);
}
{
let t3 = this.subarray(e2, h2, true), i3 = atob(s2), r2 = t3.toUint8();
for (let e3 = 0; e3 < h2; e3++) r2[e3] = i3.charCodeAt(n2 + e3);
return t3;
}
}
});
class St extends pe {
static canHandle(e2, t2) {
return 18761 === t2 || 19789 === t2;
}
extendOptions(e2) {
let { ifd0: t2, xmp: i2, iptc: n2, icc: s2 } = e2;
i2.enabled && t2.deps.add(j), n2.enabled && t2.deps.add(W), s2.enabled && t2.deps.add(K), t2.finalizeFilters();
}
async parse() {
let { tiff: e2, xmp: t2, iptc: i2, icc: n2 } = this.options;
if (e2.enabled || t2.enabled || i2.enabled || n2.enabled) {
let e3 = Math.max(C(this.options), this.options.chunkSize);
await this.file.ensureChunk(0, e3), this.createParser("tiff", this.file), this.parsers.tiff.parseHeader(), await this.parsers.tiff.parseIfd0Block(), this.adaptTiffPropAsSegment("xmp"), this.adaptTiffPropAsSegment("iptc"), this.adaptTiffPropAsSegment("icc");
}
}
adaptTiffPropAsSegment(e2) {
if (this.parsers.tiff[e2]) {
let t2 = this.parsers.tiff[e2];
this.injectSegment(e2, t2);
}
}
}
f(St, "type", "tiff"), T.set("tiff", St);
let Ct = h("zlib");
const yt = "XML:com.adobe.xmp", bt = "ihdr", Pt = "iccp", It = "text", kt = "itxt", wt = [bt, Pt, It, kt, "exif"];
class Tt extends pe {
constructor(...e2) {
super(...e2), f(this, "catchError", ((e3) => this.errors.push(e3))), f(this, "metaChunks", []), f(this, "unknownChunks", []);
}
static canHandle(e2, t2) {
return 35152 === t2 && 2303741511 === e2.getUint32(0) && 218765834 === e2.getUint32(4);
}
async parse() {
let { file: e2 } = this;
await this.findPngChunksInRange("\x89PNG\r\n\n".length, e2.byteLength), await this.readSegments(this.metaChunks), this.findIhdr(), this.parseTextChunks(), await this.findExif().catch(this.catchError), await this.findXmp().catch(this.catchError), await this.findIcc().catch(this.catchError);
}
async findPngChunksInRange(e2, t2) {
let { file: i2 } = this;
for (; e2 < t2; ) {
let t3 = i2.getUint32(e2), n2 = i2.getUint32(e2 + 4), s2 = i2.getString(e2 + 4, 4).toLowerCase(), r2 = t3 + 4 + 4 + 4, a2 = { type: s2, offset: e2, length: r2, start: e2 + 4 + 4, size: t3, marker: n2 };
wt.includes(s2) ? this.metaChunks.push(a2) : this.unknownChunks.push(a2), e2 += r2;
}
}
parseTextChunks() {
let e2 = this.metaChunks.filter(((e3) => e3.type === It));
for (let t2 of e2) {
let [e3, i2] = this.file.getString(t2.start, t2.size).split("\0");
this.injectKeyValToIhdr(e3, i2);
}
}
injectKeyValToIhdr(e2, t2) {
let i2 = this.parsers.ihdr;
i2 && i2.raw.set(e2, t2);
}
findIhdr() {
let e2 = this.metaChunks.find(((e3) => e3.type === bt));
e2 && false !== this.options.ihdr.enabled && this.createParser(bt, e2.chunk);
}
async findExif() {
let e2 = this.metaChunks.find(((e3) => "exif" === e3.type));
e2 && this.injectSegment("tiff", e2.chunk);
}
async findXmp() {
let e2 = this.metaChunks.filter(((e3) => e3.type === kt));
for (let t2 of e2) {
t2.chunk.getString(0, yt.length) === yt && this.injectSegment("xmp", t2.chunk);
}
}
async findIcc() {
let e2 = this.metaChunks.find(((e3) => e3.type === Pt));
if (!e2) return;
let { chunk: t2 } = e2, i2 = t2.getUint8Array(0, 81), n2 = 0;
for (; n2 < 80 && 0 !== i2[n2]; ) n2++;
let r2 = n2 + 2, a2 = t2.getString(0, n2);
if (this.injectKeyValToIhdr("ProfileName", a2), s) {
let e3 = await Ct, i3 = t2.getUint8Array(r2);
i3 = e3.inflateSync(i3), this.injectSegment("icc", i3);
}
}
}
f(Tt, "type", "png"), T.set("png", Tt), B(N, "interop", [[1, "InteropIndex"], [2, "InteropVersion"], [4096, "RelatedImageFileFormat"], [4097, "RelatedImageWidth"], [4098, "RelatedImageHeight"]]), E(N, "ifd0", [[11, "ProcessingSoftware"], [254, "SubfileType"], [255, "OldSubfileType"], [263, "Thresholding"], [264, "CellWidth"], [265, "CellLength"], [266, "FillOrder"], [269, "DocumentName"], [280, "MinSampleValue"], [281, "MaxSampleValue"], [285, "PageName"], [286, "XPosition"], [287, "YPosition"], [290, "GrayResponseUnit"], [297, "PageNumber"], [321, "HalftoneHints"], [322, "TileWidth"], [323, "TileLength"], [332, "InkSet"], [337, "TargetPrinter"], [18246, "Rating"], [18249, "RatingPercent"], [33550, "PixelScale"], [34264, "ModelTransform"], [34377, "PhotoshopSettings"], [50706, "DNGVersion"], [50707, "DNGBackwardVersion"], [50708, "UniqueCameraModel"], [50709, "LocalizedCameraModel"], [50736, "DNGLensInfo"], [50739, "ShadowScale"], [50740, "DNGPrivateData"], [33920, "IntergraphMatrix"], [33922, "ModelTiePoint"], [34118, "SEMInfo"], [34735, "GeoTiffDirectory"], [34736, "GeoTiffDoubleParams"], [34737, "GeoTiffAsciiParams"], [50341, "PrintIM"], [50721, "ColorMatrix1"], [50722, "ColorMatrix2"], [50723, "CameraCalibration1"], [50724, "CameraCalibration2"], [50725, "ReductionMatrix1"], [50726, "ReductionMatrix2"], [50727, "AnalogBalance"], [50728, "AsShotNeutral"], [50729, "AsShotWhiteXY"], [50730, "BaselineExposure"], [50731, "BaselineNoise"], [50732, "BaselineSharpness"], [50734, "LinearResponseLimit"], [50735, "CameraSerialNumber"], [50741, "MakerNoteSafety"], [50778, "CalibrationIlluminant1"], [50779, "CalibrationIlluminant2"], [50781, "RawDataUniqueID"], [50827, "OriginalRawFileName"], [50828, "OriginalRawFileData"], [50831, "AsShotICCProfile"], [50832, "AsShotPreProfileMatrix"], [50833, "CurrentICCProfile"], [50834, "CurrentPreProfileMatrix"], [50879, "ColorimetricReference"], [50885, "SRawType"], [50898, "PanasonicTitle"], [50899, "PanasonicTitle2"], [50931, "CameraCalibrationSig"], [50932, "ProfileCalibrationSig"], [50933, "ProfileIFD"], [50934, "AsShotProfileName"], [50936, "ProfileName"], [50937, "ProfileHueSatMapDims"], [50938, "ProfileHueSatMapData1"], [50939, "ProfileHueSatMapData2"], [50940, "ProfileToneCurve"], [50941, "ProfileEmbedPolicy"], [50942, "ProfileCopyright"], [50964, "ForwardMatrix1"], [50965, "ForwardMatrix2"], [50966, "PreviewApplicationName"], [50967, "PreviewApplicationVersion"], [50968, "PreviewSettingsName"], [50969, "PreviewSettingsDigest"], [50970, "PreviewColorSpace"], [50971, "PreviewDateTime"], [50972, "RawImageDigest"], [50973, "OriginalRawFileDigest"], [50981, "ProfileLookTableDims"], [50982, "ProfileLookTableData"], [51043, "TimeCodes"], [51044, "FrameRate"], [51058, "TStop"], [51081, "ReelName"], [51089, "OriginalDefaultFinalSize"], [51090, "OriginalBestQualitySize"], [51091, "OriginalDefaultCropSize"], [51105, "CameraLabel"], [51107, "ProfileHueSatMapEncoding"], [51108, "ProfileLookTableEncoding"], [51109, "BaselineExposureOffset"], [51110, "DefaultBlackRender"], [51111, "NewRawImageDigest"], [51112, "RawToPreviewGain"]]);
let At = [[273, "StripOffsets"], [279, "StripByteCounts"], [288, "FreeOffsets"], [289, "FreeByteCounts"], [291, "GrayResponseCurve"], [292, "T4Options"], [293, "T6Options"], [300, "ColorResponseUnit"], [320, "ColorMap"], [324, "TileOffsets"], [325, "TileByteCounts"], [326, "BadFaxLines"], [327, "CleanFaxData"], [328, "ConsecutiveBadFaxLines"], [330, "SubIFD"], [333, "InkNames"], [334, "NumberofInks"], [336, "DotRange"], [338, "ExtraSamples"], [339, "SampleFormat"], [340, "SMinSampleValue"], [341, "SMaxSampleValue"], [342, "TransferRange"], [343, "ClipPath"], [344, "XClipPathUnits"], [345, "YClipPathUnits"], [346, "Indexed"], [347, "JPEGTables"], [351, "OPIProxy"], [400, "GlobalParametersIFD"], [401, "ProfileType"], [402, "FaxProfile"], [403, "CodingMethods"], [404, "VersionYear"], [405, "ModeNumber"], [433, "Decode"], [434, "DefaultImageColor"], [435, "T82Options"], [437, "JPEGTables"], [512, "JPEGProc"], [515, "JPEGRestartInterval"], [517, "JPEGLosslessPredictors"], [518, "JPEGPointTransforms"], [519, "JPEGQTables"], [520, "JPEGDCTables"], [521, "JPEGACTables"], [559, "StripRowCounts"], [999, "USPTOMiscellaneous"], [18247, "XP_DIP_XML"], [18248, "StitchInfo"], [28672, "SonyRawFileType"], [28688, "SonyToneCurve"], [28721, "VignettingCorrection"], [28722, "VignettingCorrParams"], [28724, "ChromaticAberrationCorrection"], [28725, "ChromaticAberrationCorrParams"], [28726, "DistortionCorrection"], [28727, "DistortionCorrParams"], [29895, "SonyCropTopLeft"], [29896, "SonyCropSize"], [32781, "ImageID"], [32931, "WangTag1"], [32932, "WangAnnotation"], [32933, "WangTag3"], [32934, "WangTag4"], [32953, "ImageReferencePoints"], [32954, "RegionXformTackPoint"], [32955, "WarpQuadrilateral"], [32956, "AffineTransformMat"], [32995, "Matteing"], [32996, "DataType"], [32997, "ImageDepth"], [32998, "TileDepth"], [33300, "ImageFullWidth"], [33301, "ImageFullHeight"], [33302, "TextureFormat"], [33303, "WrapModes"], [33304, "FovCot"], [33305, "MatrixWorldToScreen"], [33306, "MatrixWorldToCamera"], [33405, "Model2"], [33421, "CFARepeatPatternDim"], [33422, "CFAPattern2"], [33423, "BatteryLevel"], [33424, "KodakIFD"], [33445, "MDFileTag"], [33446, "MDScalePixel"], [33447, "MDColorTable"], [33448, "MDLabName"], [33449, "MDSampleInfo"], [33450, "MDPrepDate"], [33451, "MDPrepTime"], [33452, "MDFileUnits"], [33589, "AdventScale"], [33590, "AdventRevision"], [33628, "UIC1Tag"], [33629, "UIC2Tag"], [33630, "UIC3Tag"], [33631, "UIC4Tag"], [33918, "IntergraphPacketData"], [33919, "IntergraphFlagRegisters"], [33921, "INGRReserved"], [34016, "Site"], [34017, "ColorSequence"], [34018, "IT8Header"], [34019, "RasterPadding"], [34020, "BitsPerRunLength"], [34021, "BitsPerExtendedRunLength"], [34022, "ColorTable"], [34023, "ImageColorIndicator"], [34024, "BackgroundColorIndicator"], [34025, "ImageColorValue"], [34026, "BackgroundColorValue"], [34027, "PixelIntensityRange"], [34028, "TransparencyIndicator"], [34029, "ColorCharacterization"], [34030, "HCUsage"], [34031, "TrapIndicator"], [34032, "CMYKEquivalent"], [34152, "AFCP_IPTC"], [34232, "PixelMagicJBIGOptions"], [34263, "JPLCartoIFD"], [34306, "WB_GRGBLevels"], [34310, "LeafData"], [34687, "TIFF_FXExtensions"], [34688, "MultiProfiles"], [34689, "SharedData"], [34690, "T88Options"], [34732, "ImageLayer"], [34750, "JBIGOptions"], [34856, "Opto-ElectricConvFactor"], [34857, "Interlace"], [34908, "FaxRecvParams"], [34909, "FaxSubAddress"], [34910, "FaxRecvTime"], [34929, "FedexEDR"], [34954, "LeafSubIFD"], [37387, "FlashEnergy"], [37388, "SpatialFrequencyResponse"], [37389, "Noise"], [37390, "FocalPlaneXResolution"], [37391, "FocalPlaneYResolution"], [37392, "FocalPlaneResolutionUnit"], [37397, "ExposureIndex"], [37398, "TIFF-EPStandardID"], [37399, "SensingMethod"], [37434, "CIP3DataFile"], [37435, "CIP3Sheet"], [37436, "CIP3Side"], [37439, "StoNits"], [37679, "MSDocumentText"], [37680, "MSPropertySetStorage"], [37681, "MSDocumentTextPosition"], [37724, "ImageSourceData"], [40965, "InteropIFD"], [40976, "SamsungRawPointersOffset"], [40977, "SamsungRawPointersLength"], [41217, "SamsungRawByteOrder"], [41218, "SamsungRawUnknown"], [41484, "SpatialFrequencyResponse"], [41485, "Noise"], [41489, "ImageNumber"], [41490, "SecurityClassification"], [41491, "ImageHistory"], [41494, "TIFF-EPStandardID"], [41995, "DeviceSettingDescription"], [42112, "GDALMetadata"], [42113, "GDALNoData"], [44992, "ExpandSoftware"], [44993, "ExpandLens"], [44994, "ExpandFilm"], [44995, "ExpandFilterLens"], [44996, "ExpandScanner"], [44997, "ExpandFlashLamp"], [46275, "HasselbladRawImage"], [48129, "PixelFormat"], [48130, "Transformation"], [48131, "Uncompressed"], [48132, "ImageType"], [48256, "ImageWidth"], [48257, "ImageHeight"], [48258, "WidthResolution"], [48259, "HeightResolution"], [48320, "ImageOffset"], [48321, "ImageByteCount"], [48322, "AlphaOffset"], [48323, "AlphaByteCount"], [48324, "ImageDataDiscard"], [48325, "AlphaDataDiscard"], [50215, "OceScanjobDesc"], [50216, "OceApplicationSelector"], [50217, "OceIDNumber"], [50218, "OceImageLogic"], [50255, "Annotations"], [50459, "HasselbladExif"], [50547, "OriginalFileName"], [50560, "USPTOOriginalContentType"], [50656, "CR2CFAPattern"], [50710, "CFAPlaneColor"], [50711, "CFALayout"], [50712, "LinearizationTable"], [50713, "BlackLevelRepeatDim"], [50714, "BlackLevel"], [50715, "BlackLevelDeltaH"], [50716, "BlackLevelDeltaV"], [50717, "WhiteLevel"], [50718, "DefaultScale"], [50719, "DefaultCropOrigin"], [50720, "DefaultCropSize"], [50733, "BayerGreenSplit"], [50737, "ChromaBlurRadius"], [50738, "AntiAliasStrength"], [50752, "RawImageSegmentation"], [50780, "BestQualityScale"], [50784, "AliasLayerMetadata"], [50829, "ActiveArea"], [50830, "MaskedAreas"], [50935, "NoiseReductionApplied"], [50974, "SubTileBlockSize"], [50975, "RowInterleaveFactor"], [51008, "OpcodeList1"], [51009, "OpcodeList2"], [51022, "OpcodeList3"], [51041, "NoiseProfile"], [51114, "CacheVersion"], [51125, "DefaultUserCrop"], [51157, "NikonNEFInfo"], [65024, "KdcIFD"]];
E(N, "ifd0", At), E(N, "exif", At), B(G, "gps", [[23, { M: "Magnetic North", T: "True North" }], [25, { K: "Kilometers", M: "Miles", N: "Nautical Miles" }]]);
class Dt extends ge {
static canHandle(e2, t2) {
return 224 === e2.getUint8(t2 + 1) && 1246120262 === e2.getUint32(t2 + 4) && 0 === e2.getUint8(t2 + 8);
}
parse() {
return this.parseTags(), this.translate(), this.output;
}
parseTags() {
this.raw = /* @__PURE__ */ new Map([[0, this.chunk.getUint16(0)], [2, this.chunk.getUint8(2)], [3, this.chunk.getUint16(3)], [5, this.chunk.getUint16(5)], [7, this.chunk.getUint8(7)], [8, this.chunk.getUint8(8)]]);
}
}
f(Dt, "type", "jfif"), f(Dt, "headerLength", 9), A.set("jfif", Dt), B(N, "jfif", [[0, "JFIFVersion"], [2, "ResolutionUnit"], [3, "XResolution"], [5, "YResolution"], [7, "ThumbnailWidth"], [8, "ThumbnailHeight"]]);
class Ot extends ge {
parse() {
return this.parseTags(), this.translate(), this.output;
}
parseTags() {
this.raw = new Map([[0, this.chunk.getUint32(0)], [4, this.chunk.getUint32(4)], [8, this.chunk.getUint8(8)], [9, this.chunk.getUint8(9)], [10, this.chunk.getUint8(10)], [11, this.chunk.getUint8(11)], [12, this.chunk.getUint8(12)], ...Array.from(this.raw)]);
}
}
f(Ot, "type", "ihdr"), A.set("ihdr", Ot), B(N, "ihdr", [[0, "ImageWidth"], [4, "ImageHeight"], [8, "BitDepth"], [9, "ColorType"], [10, "Compression"], [11, "Filter"], [12, "Interlace"]]), B(G, "ihdr", [[9, { 0: "Grayscale", 2: "RGB", 3: "Palette", 4: "Grayscale with Alpha", 6: "RGB with Alpha", DEFAULT: "Unknown" }], [10, { 0: "Deflate/Inflate", DEFAULT: "Unknown" }], [11, { 0: "Adaptive", DEFAULT: "Unknown" }], [12, { 0: "Noninterlaced", 1: "Adam7 Interlace", DEFAULT: "Unknown" }]]);
const xt = "\0\0\0\0";
class vt extends ge {
static canHandle(e2, t2) {
return 226 === e2.getUint8(t2 + 1) && 1229144927 === e2.getUint32(t2 + 4);
}
static findPosition(e2, t2) {
let i2 = super.findPosition(e2, t2);
return i2.chunkNumber = e2.getUint8(t2 + 16), i2.chunkCount = e2.getUint8(t2 + 17), i2.multiSegment = i2.chunkCount > 1, i2;
}
static handleMultiSegments(e2) {
return (function(e3) {
let t2 = (function(e4) {
let t3 = e4[0].constructor, i2 = 0;
for (let t4 of e4) i2 += t4.length;
let n2 = new t3(i2), s2 = 0;
for (let t4 of e4) n2.set(t4, s2), s2 += t4.length;
return n2;
})(e3.map(((e4) => e4.chunk.toUint8())));
return new I(t2);
})(e2);
}
parse() {
return this.raw = /* @__PURE__ */ new Map(), this.parseHeader(), this.parseTags(), this.translate(), this.output;
}
parseHeader() {
let { raw: e2 } = this;
this.chunk.byteLength < 84 && m("ICC header is too short");
for (let [t2, i2] of Object.entries(Mt)) {
t2 = parseInt(t2, 10);
let n2 = i2(this.chunk, t2);
n2 !== xt && e2.set(t2, n2);
}
}
parseTags() {
let e2, t2, i2, n2, s2, { raw: r2 } = this, a2 = this.chunk.getUint32(128), o2 = 132, l2 = this.chunk.byteLength;
for (; a2--; ) {
if (e2 = this.chunk.getString(o2, 4), t2 = this.chunk.getUint32(o2 + 4), i2 = this.chunk.getUint32(o2 + 8), n2 = this.chunk.getString(t2, 4), t2 + i2 > l2) return void console.warn("reached the end of the first ICC chunk. Enable options.tiff.multiSegment to read all ICC segments.");
s2 = this.parseTag(n2, t2, i2), void 0 !== s2 && s2 !== xt && r2.set(e2, s2), o2 += 12;
}
}
parseTag(e2, t2, i2) {
switch (e2) {
case "desc":
return this.parseDesc(t2);
case "mluc":
return this.parseMluc(t2);
case "text":
return this.parseText(t2, i2);
case "sig ":
return this.parseSig(t2);
}
if (!(t2 + i2 > this.chunk.byteLength)) return this.chunk.getUint8Array(t2, i2);
}
parseDesc(e2) {
let t2 = this.chunk.getUint32(e2 + 8) - 1;
return S(this.chunk.getString(e2 + 12, t2));
}
parseText(e2, t2) {
return S(this.chunk.getString(e2 + 8, t2 - 8));
}
parseSig(e2) {
return S(this.chunk.getString(e2 + 8, 4));
}
parseMluc(e2) {
let { chunk: t2 } = this, i2 = t2.getUint32(e2 + 8), n2 = t2.getUint32(e2 + 12), s2 = e2 + 16, r2 = [];
for (let a2 = 0; a2 < i2; a2++) {
let i3 = t2.getString(s2 + 0, 2), a3 = t2.getString(s2 + 2, 2), o2 = t2.getUint32(s2 + 4), l2 = t2.getUint32(s2 + 8) + e2, h2 = S(t2.getUnicodeString(l2, o2));
r2.push({ lang: i3, country: a3, text: h2 }), s2 += n2;
}
return 1 === i2 ? r2[0].text : r2;
}
translateValue(e2, t2) {
return "string" == typeof e2 ? t2[e2] || t2[e2.toLowerCase()] || e2 : t2[e2] || e2;
}
}
f(vt, "type", "icc"), f(vt, "multiSegment", true), f(vt, "headerLength", 18);
const Mt = { 4: Rt, 8: function(e2, t2) {
return [e2.getUint8(t2), e2.getUint8(t2 + 1) >> 4, e2.getUint8(t2 + 1) % 16].map(((e3) => e3.toString(10))).join(".");
}, 12: Rt, 16: Rt, 20: Rt, 24: function(e2, t2) {
const i2 = e2.getUint16(t2), n2 = e2.getUint16(t2 + 2) - 1, s2 = e2.getUint16(t2 + 4), r2 = e2.getUint16(t2 + 6), a2 = e2.getUint16(t2 + 8), o2 = e2.getUint16(t2 + 10);
return new Date(Date.UTC(i2, n2, s2, r2, a2, o2));
}, 36: Rt, 40: Rt, 48: Rt, 52: Rt, 64: (e2, t2) => e2.getUint32(t2), 80: Rt };
function Rt(e2, t2) {
return S(e2.getString(t2, 4));
}
A.set("icc", vt), B(N, "icc", [[4, "ProfileCMMType"], [8, "ProfileVersion"], [12, "ProfileClass"], [16, "ColorSpaceData"], [20, "ProfileConnectionSpace"], [24, "ProfileDateTime"], [36, "ProfileFileSignature"], [40, "PrimaryPlatform"], [44, "CMMFlags"], [48, "DeviceManufacturer"], [52, "DeviceModel"], [56, "DeviceAttributes"], [64, "RenderingIntent"], [68, "ConnectionSpaceIlluminant"], [80, "ProfileCreator"], [84, "ProfileID"], ["Header", "ProfileHeader"], ["MS00", "WCSProfiles"], ["bTRC", "BlueTRC"], ["bXYZ", "BlueMatrixColumn"], ["bfd", "UCRBG"], ["bkpt", "MediaBlackPoint"], ["calt", "CalibrationDateTime"], ["chad", "ChromaticAdaptation"], ["chrm", "Chromaticity"], ["ciis", "ColorimetricIntentImageState"], ["clot", "ColorantTableOut"], ["clro", "ColorantOrder"], ["clrt", "ColorantTable"], ["cprt", "ProfileCopyright"], ["crdi", "CRDInfo"], ["desc", "ProfileDescription"], ["devs", "DeviceSettings"], ["dmdd", "DeviceModelDesc"], ["dmnd", "DeviceMfgDesc"], ["dscm", "ProfileDescriptionML"], ["fpce", "FocalPlaneColorimetryEstimates"], ["gTRC", "GreenTRC"], ["gXYZ", "GreenMatrixColumn"], ["gamt", "Gamut"], ["kTRC", "GrayTRC"], ["lumi", "Luminance"], ["meas", "Measurement"], ["meta", "Metadata"], ["mmod", "MakeAndModel"], ["ncl2", "NamedColor2"], ["ncol", "NamedColor"], ["ndin", "NativeDisplayInfo"], ["pre0", "Preview0"], ["pre1", "Preview1"], ["pre2", "Preview2"], ["ps2i", "PS2RenderingIntent"], ["ps2s", "PostScript2CSA"], ["psd0", "PostScript2CRD0"], ["psd1", "PostScript2CRD1"], ["psd2", "PostScript2CRD2"], ["psd3", "PostScript2CRD3"], ["pseq", "ProfileSequenceDesc"], ["psid", "ProfileSequenceIdentifier"], ["psvm", "PS2CRDVMSize"], ["rTRC", "RedTRC"], ["rXYZ", "RedMatrixColumn"], ["resp", "OutputResponse"], ["rhoc", "ReflectionHardcopyOrigColorimetry"], ["rig0", "PerceptualRenderingIntentGamut"], ["rig2", "SaturationRenderingIntentGamut"], ["rpoc", "ReflectionPrintOutputColorimetry"], ["sape", "SceneAppearanceEstimates"], ["scoe", "SceneColorimetryEstimates"], ["scrd", "ScreeningDesc"], ["scrn", "Screening"], ["targ", "CharTarget"], ["tech", "Technology"], ["vcgt", "VideoCardGamma"], ["view", "ViewingConditions"], ["vued", "ViewingCondDesc"], ["wtpt", "MediaWhitePoint"]]);
const Lt = { "4d2p": "Erdt Systems", AAMA: "Aamazing Technologies", ACER: "Acer", ACLT: "Acolyte Color Research", ACTI: "Actix Sytems", ADAR: "Adara Technology", ADBE: "Adobe", ADI: "ADI Systems", AGFA: "Agfa Graphics", ALMD: "Alps Electric", ALPS: "Alps Electric", ALWN: "Alwan Color Expertise", AMTI: "Amiable Technologies", AOC: "AOC International", APAG: "Apago", APPL: "Apple Computer", AST: "AST", "AT&T": "AT&T", BAEL: "BARBIERI electronic", BRCO: "Barco NV", BRKP: "Breakpoint", BROT: "Brother", BULL: "Bull", BUS: "Bus Computer Systems", "C-IT": "C-Itoh", CAMR: "Intel", CANO: "Canon", CARR: "Carroll Touch", CASI: "Casio", CBUS: "Colorbus PL", CEL: "Crossfield", CELx: "Crossfield", CGS: "CGS Publishing Technologies International", CHM: "Rochester Robotics", CIGL: "Colour Imaging Group, London", CITI: "Citizen", CL00: "Candela", CLIQ: "Color IQ", CMCO: "Chromaco", CMiX: "CHROMiX", COLO: "Colorgraphic Communications", COMP: "Compaq", COMp: "Compeq/Focus Technology", CONR: "Conrac Display Products", CORD: "Cordata Technologies", CPQ: "Compaq", CPRO: "ColorPro", CRN: "Cornerstone", CTX: "CTX International", CVIS: "ColorVision", CWC: "Fujitsu Laboratories", DARI: "Darius Technology", DATA: "Dataproducts", DCP: "Dry Creek Photo", DCRC: "Digital Contents Resource Center, Chung-Ang University", DELL: "Dell Computer", DIC: "Dainippon Ink and Chemicals", DICO: "Diconix", DIGI: "Digital", "DL&C": "Digital Light & Color", DPLG: "Doppelganger", DS: "Dainippon Screen", DSOL: "DOOSOL", DUPN: "DuPont", EPSO: "Epson", ESKO: "Esko-Graphics", ETRI: "Electronics and Telecommunications Research Institute", EVER: "Everex Systems", EXAC: "ExactCODE", Eizo: "Eizo", FALC: "Falco Data Products", FF: "Fuji Photo Film", FFEI: "FujiFilm Electronic Imaging", FNRD: "Fnord Software", FORA: "Fora", FORE: "Forefront Technology", FP: "Fujitsu", FPA: "WayTech Development", FUJI: "Fujitsu", FX: "Fuji Xerox", GCC: "GCC Technologies", GGSL: "Global Graphics Software", GMB: "Gretagmacbeth", GMG: "GMG", GOLD: "GoldStar Technology", GOOG: "Google", GPRT: "Giantprint", GTMB: "Gretagmacbeth", GVC: "WayTech Development", GW2K: "Sony", HCI: "HCI", HDM: "Heidelberger Druckmaschinen", HERM: "Hermes", HITA: "Hitachi America", HP: "Hewlett-Packard", HTC: "Hitachi", HiTi: "HiTi Digital", IBM: "IBM", IDNT: "Scitex", IEC: "Hewlett-Packard", IIYA: "Iiyama North America", IKEG: "Ikegami Electronics", IMAG: "Image Systems", IMI: "Ingram Micro", INTC: "Intel", INTL: "N/A (INTL)", INTR: "Intra Electronics", IOCO: "Iocomm International Technology", IPS: "InfoPrint Solutions Company", IRIS: "Scitex", ISL: "Ichikawa Soft Laboratory", ITNL: "N/A (ITNL)", IVM: "IVM", IWAT: "Iwatsu Electric", Idnt: "Scitex", Inca: "Inca Digital Printers", Iris: "Scitex", JPEG: "Joint Photographic Experts Group", JSFT: "Jetsoft Development", JVC: "JVC Information Products", KART: "Scitex", KFC: "KFC Computek Components", KLH: "KLH Computers", KMHD: "Konica Minolta", KNCA: "Konica", KODA: "Kodak", KYOC: "Kyocera", Kart: "Scitex", LCAG: "Leica", LCCD: "Leeds Colour", LDAK: "Left Dakota", LEAD: "Leading Technology", LEXM: "Lexmark International", LINK: "Link Computer", LINO: "Linotronic", LITE: "Lite-On", Leaf: "Leaf", Lino: "Linotronic", MAGC: "Mag Computronic", MAGI: "MAG Innovision", MANN: "Mannesmann", MICN: "Micron Technology", MICR: "Microtek", MICV: "Microvitec", MINO: "Minolta", MITS: "Mitsubishi Electronics America", MITs: "Mitsuba", MNLT: "Minolta", MODG: "Modgraph", MONI: "Monitronix", MONS: "Monaco Systems", MORS: "Morse Technology", MOTI: "Motive Systems", MSFT: "Microsoft", MUTO: "MUTOH INDUSTRIES", Mits: "Mitsubishi Electric", NANA: "NANAO", NEC: "NEC", NEXP: "NexPress Solutions", NISS: "Nissei Sangyo America", NKON: "Nikon", NONE: "none", OCE: "Oce Technologies", OCEC: "OceColor", OKI: "Oki", OKID: "Okidata", OKIP: "Okidata", OLIV: "Olivetti", OLYM: "Olympus", ONYX: "Onyx Graphics", OPTI: "Optiquest", PACK: "Packard Bell", PANA: "Matsushita Electric Industrial", PANT: "Pantone", PBN: "Packard Bell", PFU: "PFU", PHIL: "Philips Consumer Electronics", PNTX: "HOYA", POne: "Phase One A/S", PREM: "Premier Computer Innovations", PRIN: "Princeton Graphic Systems", PRIP: "Princeton Publishing Labs", QLUX: "Hong Kong", QMS: "QMS", QPCD: "QPcard AB", QUAD: "QuadLaser", QUME: "Qume", RADI: "Radius", RDDx: "Integrated Color Solutions", RDG: "Roland DG", REDM: "REDMS Group", RELI: "Relisys", RGMS: "Rolf Gierling Multitools", RICO: "Ricoh", RNLD: "Edmund Ronald", ROYA: "Royal", RPC: "Ricoh Printing Systems", RTL: "Royal Information Electronics", SAMP: "Sampo", SAMS: "Samsung", SANT: "Jaime Santana Pomares", SCIT: "Scitex", SCRN: "Dainippon Screen", SDP: "Scitex", SEC: "Samsung", SEIK: "Seiko Instruments", SEIk: "Seikosha", SGUY: "ScanGuy.com", SHAR: "Sharp Laboratories", SICC: "International Color Consortium", SONY: "Sony", SPCL: "SpectraCal", STAR: "Star", STC: "Sampo Technology", Scit: "Scitex", Sdp: "Scitex", Sony: "Sony", TALO: "Talon Technology", TAND: "Tandy", TATU: "Tatung", TAXA: "TAXAN America", TDS: "Tokyo Denshi Sekei", TECO: "TECO Information Systems", TEGR: "Tegra", TEKT: "Tektronix", TI: "Texas Instruments", TMKR: "TypeMaker", TOSB: "Toshiba", TOSH: "Toshiba", TOTK: "TOTOKU ELECTRIC", TRIU: "Triumph", TSBT: "Toshiba", TTX: "TTX Computer Products", TVM: "TVM Professional Monitor", TW: "TW Casper", ULSX: "Ulead Systems", UNIS: "Unisys", UTZF: "Utz Fehlau & Sohn", VARI: "Varityper", VIEW: "Viewsonic", VISL: "Visual communication", VIVO: "Vivo Mobile Communication", WANG: "Wang", WLBR: "Wilbur Imaging", WTG2: "Ware To Go", WYSE: "WYSE Technology", XERX: "Xerox", XRIT: "X-Rite", ZRAN: "Zoran", Zebr: "Zebra Technologies", appl: "Apple Computer", bICC: "basICColor", berg: "bergdesign", ceyd: "Integrated Color Solutions", clsp: "MacDermid ColorSpan", ds: "Dainippon Screen", dupn: "DuPont", ffei: "FujiFilm Electronic Imaging", flux: "FluxData", iris: "Scitex", kart: "Scitex", lcms: "Little CMS", lino: "Linotronic", none: "none", ob4d: "Erdt Systems", obic: "Medigraph", quby: "Qubyx Sarl", scit: "Scitex", scrn: "Dainippon Screen", sdp: "Scitex", siwi: "SIWI GRAFIKA", yxym: "YxyMaster" }, Ut = { scnr: "Scanner", mntr: "Monitor", prtr: "Printer", link: "Device Link", abst: "Abstract", spac: "Color Space Conversion Profile", nmcl: "Named Color", cenc: "ColorEncodingSpace profile", mid: "MultiplexIdentification profile", mlnk: "MultiplexLink profile", mvis: "MultiplexVisualization profile", nkpf: "Nikon Input Device Profile (NON-STANDARD!)" };
B(G, "icc", [[4, Lt], [12, Ut], [40, Object.assign({}, Lt, Ut)], [48, Lt], [80, Lt], [64, { 0: "Perceptual", 1: "Relative Colorimetric", 2: "Saturation", 3: "Absolute Colorimetric" }], ["tech", { amd: "Active Matrix Display", crt: "Cathode Ray Tube Display", kpcd: "Photo CD", pmd: "Passive Matrix Display", dcam: "Digital Camera", dcpj: "Digital Cinema Projector", dmpc: "Digital Motion Picture Camera", dsub: "Dye Sublimation Printer", epho: "Electrophotographic Printer", esta: "Electrostatic Printer", flex: "Flexography", fprn: "Film Writer", fscn: "Film Scanner", grav: "Gravure", ijet: "Ink Jet Printer", imgs: "Photo Image Setter", mpfr: "Motion Picture Film Recorder", mpfs: "Motion Picture Film Scanner", offs: "Offset Lithography", pjtv: "Projection Television", rpho: "Photographic Paper Printer", rscn: "Reflective Scanner", silk: "Silkscreen", twax: "Thermal Wax Printer", vidc: "Video Camera", vidm: "Video Monitor" }]]);
class Ft extends ge {
static canHandle(e2, t2, i2) {
return 237 === e2.getUint8(t2 + 1) && "Photoshop" === e2.getString(t2 + 4, 9) && void 0 !== this.containsIptc8bim(e2, t2, i2);
}
static headerLength(e2, t2, i2) {
let n2, s2 = this.containsIptc8bim(e2, t2, i2);
if (void 0 !== s2) return n2 = e2.getUint8(t2 + s2 + 7), n2 % 2 != 0 && (n2 += 1), 0 === n2 && (n2 = 4), s2 + 8 + n2;
}
static containsIptc8bim(e2, t2, i2) {
for (let n2 = 0; n2 < i2; n2++) if (this.isIptcSegmentHead(e2, t2 + n2)) return n2;
}
static isIptcSegmentHead(e2, t2) {
return 56 === e2.getUint8(t2) && 943868237 === e2.getUint32(t2) && 1028 === e2.getUint16(t2 + 4);
}
parse() {
let { raw: e2 } = this, t2 = this.chunk.byteLength - 1, i2 = false;
for (let n2 = 0; n2 < t2; n2++) if (28 === this.chunk.getUint8(n2) && 2 === this.chunk.getUint8(n2 + 1)) {
i2 = true;
let t3 = this.chunk.getUint16(n2 + 3), s2 = this.chunk.getUint8(n2 + 2), r2 = this.chunk.getLatin1String(n2 + 5, t3);
e2.set(s2, this.pluralizeValue(e2.get(s2), r2)), n2 += 4 + t3;
} else if (i2) break;
return this.translate(), this.output;
}
pluralizeValue(e2, t2) {
return void 0 !== e2 ? e2 instanceof Array ? (e2.push(t2), e2) : [e2, t2] : t2;
}
}
f(Ft, "type", "iptc"), f(Ft, "translateValues", false), f(Ft, "reviveValues", false), A.set("iptc", Ft), B(N, "iptc", [[0, "ApplicationRecordVersion"], [3, "ObjectTypeReference"], [4, "ObjectAttributeReference"], [5, "ObjectName"], [7, "EditStatus"], [8, "EditorialUpdate"], [10, "Urgency"], [12, "SubjectReference"], [15, "Category"], [20, "SupplementalCategories"], [22, "FixtureIdentifier"], [25, "Keywords"], [26, "ContentLocationCode"], [27, "ContentLocationName"], [30, "ReleaseDate"], [35, "ReleaseTime"], [37, "ExpirationDate"], [38, "ExpirationTime"], [40, "SpecialInstructions"], [42, "ActionAdvised"], [45, "ReferenceService"], [47, "ReferenceDate"], [50, "ReferenceNumber"], [55, "DateCreated"], [60, "TimeCreated"], [62, "DigitalCreationDate"], [63, "DigitalCreationTime"], [65, "OriginatingProgram"], [70, "ProgramVersion"], [75, "ObjectCycle"], [80, "Byline"], [85, "BylineTitle"], [90, "City"], [92, "Sublocation"], [95, "State"], [100, "CountryCode"], [101, "Country"], [103, "OriginalTransmissionReference"], [105, "Headline"], [110, "Credit"], [115, "Source"], [116, "CopyrightNotice"], [118, "Contact"], [120, "Caption"], [121, "LocalCaption"], [122, "Writer"], [125, "RasterizedCaption"], [130, "ImageType"], [131, "ImageOrientation"], [135, "LanguageIdentifier"], [150, "AudioType"], [151, "AudioSamplingRate"], [152, "AudioSamplingResolution"], [153, "AudioDuration"], [154, "AudioOutcue"], [184, "JobID"], [185, "MasterDocumentID"], [186, "ShortDocumentID"], [187, "UniqueDocumentID"], [188, "OwnerID"], [200, "ObjectPreviewFileFormat"], [201, "ObjectPreviewFileVersion"], [202, "ObjectPreviewData"], [221, "Prefs"], [225, "ClassifyState"], [228, "SimilarityIndex"], [230, "DocumentNotes"], [231, "DocumentHistory"], [232, "ExifCameraInfo"], [255, "CatalogSets"]]), B(G, "iptc", [[10, { 0: "0 (reserved)", 1: "1 (most urgent)", 2: "2", 3: "3", 4: "4", 5: "5 (normal urgency)", 6: "6", 7: "7", 8: "8 (least urgent)", 9: "9 (user-defined priority)" }], [75, { a: "Morning", b: "Both Morning and Evening", p: "Evening" }], [131, { L: "Landscape", P: "Portrait", S: "Square" }]]), e.Exifr = ce, e.Options = oe, e.allFormatters = ie, e.chunkedProps = $, e.createDictionary = B, e.default = ft, e.extendDictionary = E, e.fetchUrlAsArrayBuffer = L, e.fileParsers = T, e.fileReaders = D, e.gps = De, e.gpsOnlyOptions = Ae, e.inheritables = te, e.orientation = Re, e.orientationOnlyOptions = Me, e.otherSegments = J, e.parse = fe, e.readBlobAsArrayBuffer = U, e.rotation = Ue, e.rotations = Le, e.segmentParsers = A, e.segments = q, e.segmentsAndBlocks = Z, e.sidecar = async function(e2, t2, i2) {
let n2 = new oe(t2);
n2.chunked = false, void 0 === i2 && "string" == typeof e2 && (i2 = (function(e3) {
let t3 = e3.toLowerCase().split(".").pop();
if (/* @__PURE__ */ (function(e4) {
return "exif" === e4 || "tiff" === e4 || "tif" === e4;
})(t3)) return "tiff";
if (dt.includes(t3)) return t3;
})(e2));
let s2 = await x(e2, n2);
if (i2) {
if (dt.includes(i2)) return gt(i2, s2, n2);
m("Invalid segment type");
} else {
if ((function(e3) {
let t3 = e3.getString(0, 50).trim();
return t3.includes("<?xpacket") || t3.includes("<x:");
})(s2)) return gt("xmp", s2, n2);
for (let [e3] of A) {
if (!dt.includes(e3)) continue;
let t3 = await gt(e3, s2, n2).catch(pt);
if (t3) return t3;
}
m("Unknown file format");
}
}, e.tagKeys = N, e.tagRevivers = V, e.tagValues = G, e.thumbnail = xe, e.thumbnailOnlyOptions = Oe, e.thumbnailUrl = ve, e.tiffBlocks = Q, e.tiffExtractables = ee, Object.defineProperty(e, "__esModule", { value: true });
}));
}
});
// src/helpers/pluginMeta.ts
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
function getModuleDir() {
try {
return path.dirname(fileURLToPath(import.meta.url));
} catch {
return process.cwd();
}
}
function readJsonFile(filePath) {
try {
const raw = fs.readFileSync(filePath, "utf8");
return JSON.parse(raw);
} catch {
return null;
}
}
function findUpwards(startDir, fileName, maxDepth = 8) {
let dir = startDir;
for (let i = 0; i < maxDepth; i++) {
const candidate = path.join(dir, fileName);
if (fs.existsSync(candidate)) return candidate;
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
return null;
}
function getPluginMeta() {
const moduleDir = getModuleDir();
const packageJsonPath = findUpwards(moduleDir, "package.json");
const manifestJsonPath = findUpwards(moduleDir, "manifest.json");
const packageJson = packageJsonPath ? readJsonFile(packageJsonPath) : null;
const manifestJson = manifestJsonPath ? readJsonFile(manifestJsonPath) : null;
const version = String(packageJson?.version || "unknown");
const owner = String(manifestJson?.owner || "").trim();
const name = String(manifestJson?.name || "").trim();
const revisionsUrl = owner && name ? `https://raw.githubusercontent.com/${owner}/${name}-docs/main/docs/CHANGELOG.md` : "https://raw.githubusercontent.com";
const pluginIdentifier = owner && name ? `${owner}/${name}` : name ? name : "unknown";
return { version, owner, name, revisionsUrl, pluginIdentifier };
}
function formatToolMetaBlock(meta = getPluginMeta()) {
return `Plugin-Identifier: ${meta.pluginIdentifier}
Plugin version: ${meta.version}`;
}
// src/services/defaultParamsDrawThingsTxt2Img.ts
var defaultParams = {
aesthetic_score: 6.5,
batch_count: 1,
batch_size: 1,
causal_inference: 0,
causal_inference_pad: 0,
cfg_zero_init_steps: 1,
cfg_zero_star: false,
clip_l_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
clip_skip: 1,
clip_weight: 1,
controls: [],
crop_left: 0,
crop_top: 0,
fps: 25,
guidance_embed: 1,
guidance_scale: 1,
guiding_frame_noise: 0.019999999552965164,
height: 1024,
hires_fix: false,
hires_fix_height: 512,
hires_fix_strength: 0.4000000059604645,
hires_fix_width: 384,
image_guidance: 1.5,
image_prior_steps: 5,
loras: [],
mask_blur: 1.5,
mask_blur_outset: 0,
model: "z_image_turbo_1.0_q6p.ckpt",
motion_scale: 127,
negative_aesthetic_score: 0,
// negative_original_height: 512, negative_original_width: 512,
negative_prompt: "",
negative_prompt_for_image_prior: true,
num_frames: 1,
open_clip_g_text: "Could this be it, or not, I am not sure really.",
// original_height: 768, original_width: 576,
preserve_original_after_inpaint: true,
prompt: "3d fluffy llama, closeup cute and adorable, cute big circular reflective eyes, long fuzzy fur, pixar render, unreal engine cinematic smooth, intricate detail, cinematic",
refiner_model: null,
refiner_start: 0.4000000059604645,
resolution_dependent_shift: true,
sampler: "UniPC Trailing",
seed: 175308301,
seed_mode: "Scale Alike",
separate_clip_l: false,
separate_open_clip_g: false,
separate_t5: false,
sharpness: 0,
shift: 3,
speed_up_with_guidance_embed: true,
stage_2_guidance: 1,
stage_2_shift: 1,
start_frame_guidance: 1.2000000476837158,
steps: 8,
stochastic_sampling_gamma: 0.3,
strength: 1,
t5_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
t5_text_encoder_decoding: true,
// target_height: 768, target_width: 576,
tea_cache: false,
tea_cache_end: 100,
tea_cache_max_skip_steps: 3,
tea_cache_start: 5,
tea_cache_threshold: 0.20000000298023224,
tiled_decoding: true,
tiled_diffusion: false,
upscaler: null,
upscaler_scale: 0,
width: 768,
zero_negative_prompt: false
};
var generateRuntimeDefaults = {
saveOriginal: true,
previewInChat: true
};
var engineConnectionDefaults = {
transport: "auto",
http: {
baseUrl: "http://127.0.0.1:7860",
host: "127.0.0.1",
port: 7860
},
grpc: {
target: "127.0.0.1:7859",
service: "ImageGenerationService",
compression: "identity",
acceptEncoding: "",
protoPath: void 0
},
sharedSecret: null
};
function getEngineConnectionDefaults(overrides) {
const host = overrides?.host || engineConnectionDefaults.http.host;
const httpPort = overrides?.httpPort || engineConnectionDefaults.http.port;
const grpcPort = overrides?.grpcPort || parseInt(engineConnectionDefaults.grpc.target.split(":")[1], 10);
return {
...engineConnectionDefaults,
http: {
...engineConnectionDefaults.http,
baseUrl: `http://${host}:${httpPort}`,
host,
port: httpPort
},
grpc: {
...engineConnectionDefaults.grpc,
target: `${host}:${grpcPort}`
}
};
}
// src/services/drawthingsLimits.ts
var drawthingsLimits = {
// Limits for RENDERED output (requested_effective)
min: 256,
minDim: 256,
// Minimum dimension per side
maxWidth: 2048,
// Maximum render width
maxHeight: 2048,
// Maximum render height (note: was 2048 in old docs)
// Limits for INPUT images (adjusted) - Canvas & Moodboard
targetSum: 2240,
// Sum constraint: width + height ≤ 2240 (image2image / edit)
targetSumZoom: 4096,
// Sum constraint for zoom profile input (Pass 2 canvas; tuned for SeedVR2)
targetSumRestore: 704,
// Source sum threshold below which restore-pass fires before zoom-in
targetSumHandover: 1344,
// Restore-pass output sum (Pass 1 -> Pass 2 handover point); decoupled from targetSum
align: 64,
// Dimensions must be multiples of 64
// Postprocessing when requested_raw exceeds render limits
upscaler: "4x_ultrasharp_f16.ckpt",
upscalerScaleFactor: 2,
// Upscale method used when _dt_needs_upscaler is true.
upscaleMethod: "zoom-pass",
// Minimum scale factor (max(rawW/adjW, rawH/adjH)) to trigger upscaling.
minUpscaleFactorUpscaler: 1.5,
minUpscaleFactorZoomPass: 1.5,
// Preview generation for ALL MediaTypes (attachment, variant, image, picture).
previewMaxSum: 1792,
previewQuality: 80,
previewFormat: "jpeg"
};
// src/services/defaultParamsDrawThingsImg2Img.ts
var defaultParamsImg2Img = {
aesthetic_score: 6.5,
batch_count: 1,
batch_size: 1,
causal_inference: 0,
causal_inference_pad: 0,
cfg_zero_init_steps: 1,
cfg_zero_star: false,
clip_l_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
clip_skip: 1,
clip_weight: 1,
controls: [],
crop_left: 0,
crop_top: 0,
fps: 5,
guidance_embed: 3.5,
guidance_scale: 1,
guiding_frame_noise: 0.02,
// Ensure size keys exist for filtering; service overwrites with actual PNG size
width: 768,
height: 1024,
hires_fix: false,
hires_fix_height: 512,
hires_fix_strength: 0.4,
// hires_fix_width: 384,
image_guidance: 1.5,
image_prior_steps: 5,
loras: [],
mask_blur: 1.5,
mask_blur_outset: 0,
model: "krea_2_turbo_q6p.ckpt",
motion_scale: 127,
negative_aesthetic_score: 0,
// negative_original_height: 512, negative_original_width: 512,
negative_prompt: "",
negative_prompt_for_image_prior: true,
num_frames: 1,
open_clip_g_text: "Could this be it, or not, I am not sure really.",
// original_height: 512, original_width: 512,
preserve_original_after_inpaint: true,
prompt: "",
refiner_model: null,
refiner_start: 0.4,
resolution_dependent_shift: true,
sampler: "Euler A Trailing",
seed: 175308301,
seed_mode: "Scale Alike",
separate_clip_l: false,
separate_open_clip_g: false,
separate_t5: false,
sharpness: 0,
shift: 3,
speed_up_with_guidance_embed: true,
stage_2_guidance: 1,
stage_2_shift: 1,
start_frame_guidance: 1.2,
steps: 8,
stochastic_sampling_gamma: 0.3,
strength: 0.925,
t5_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
t5_text_encoder_decoding: true,
// target_height: 512, target_width: 512,
tea_cache: false,
tea_cache_end: 100,
tea_cache_max_skip_steps: 3,
tea_cache_start: 5,
tea_cache_threshold: 0.2,
tiled_decoding: false,
tiled_diffusion: false,
upscaler: null,
upscaler_scale: 0,
zero_negative_prompt: false
};
// src/services/defaultParamsDrawThingsEdit.ts
var defaultParamsImg2Img2 = {
aesthetic_score: 6.5,
batch_count: 1,
batch_size: 1,
causal_inference: 0,
causal_inference_pad: 0,
cfg_zero_init_steps: 0,
cfg_zero_star: false,
clip_l_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
clip_skip: 1,
clip_weight: 1,
controls: [],
crop_left: 0,
crop_top: 0,
fps: 25,
guidance_embed: 1,
guidance_scale: 1,
guiding_frame_noise: 0.019999999552965164,
// Ensure size keys exist for filtering; service overwrites with actual PNG size
width: 768,
height: 1024,
hires_fix: false,
hires_fix_height: 512,
hires_fix_strength: 0.4000000059604645,
// hires_fix_width: 384,
image_guidance: 1.5,
image_prior_steps: 5,
loras: [],
mask_blur: 2.5,
mask_blur_outset: 0,
model: "flux_2_klein_9b_kv_q6p.ckpt",
motion_scale: 127,
negative_aesthetic_score: 0,
// negative_original_height: 512, negative_original_width: 512,
negative_prompt: "",
negative_prompt_for_image_prior: true,
num_frames: 1,
open_clip_g_text: "Could this be it, or not, I am not sure really.",
// original_height: 512, original_width: 512,
preserve_original_after_inpaint: true,
prompt: "",
refiner_model: null,
refiner_start: 0.4000000059604645,
resolution_dependent_shift: true,
sampler: "DDIM Trailing",
seed: 175308301,
seed_mode: "Scale Alike",
separate_clip_l: false,
separate_open_clip_g: false,
separate_t5: false,
sharpness: 0,
shift: 3,
speed_up_with_guidance_embed: true,
stage_2_guidance: 1,
stage_2_shift: 1,
start_frame_guidance: 1.2000000476837158,
steps: 12,
stochastic_sampling_gamma: 0.3,
strength: 1,
t5_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
t5_text_encoder_decoding: true,
// target_height: 512, target_width: 512,
tea_cache: false,
tea_cache_end: 100,
tea_cache_max_skip_steps: 3,
tea_cache_start: 5,
tea_cache_threshold: 0.20000000298023224,
tiled_decoding: false,
tiled_diffusion: false,
upscaler: null,
upscaler_scale: 0,
zero_negative_prompt: false
};
// src/services/defaultParamsDrawThingsText2Video.ts
var defaultParamsText2Video = {
aesthetic_score: 6,
batch_count: 1,
batch_size: 1,
causal_inference: 0,
causal_inference_pad: 0,
cfg_zero_init_steps: 0,
cfg_zero_star: false,
clip_l_text: "",
clip_skip: 1,
clip_weight: 1,
compression_artifacts: "h264",
compression_artifacts_quality: 43.1,
controls: [],
crop_left: 0,
crop_top: 0,
fps: 25,
guidance_embed: 3.5,
guidance_scale: 1,
guiding_frame_noise: 0.02,
height: 1024,
hires_fix: false,
hires_fix_height: 768,
hires_fix_strength: 0.7,
hires_fix_width: 576,
image_guidance: 1.5,
image_prior_steps: 5,
loras: [],
mask_blur: 1.5,
mask_blur_outset: 0,
model: "ltx_2.3_22b_distilled_1.1_q6p.ckpt",
motion_scale: 127,
negative_aesthetic_score: 2.5,
// negative_original_height: 512, negative_original_width: 512,
negative_prompt: "",
negative_prompt_for_image_prior: true,
num_frames: 65,
open_clip_g_text: "",
// original_height: 1024, original_width: 768,
preserve_original_after_inpaint: true,
prompt: "3d fluffy llama, closeup cute and adorable, cute big circular reflective eyes, long fuzzy fur, pixar render, unreal engine cinematic smooth, intricate detail, cinematic",
refiner_model: null,
refiner_start: 0.85,
resolution_dependent_shift: true,
sampler: "DDIM Trailing",
seed: 175308301,
seed_mode: "Scale Alike",
separate_clip_l: false,
separate_open_clip_g: false,
separate_t5: false,
sharpness: 0,
shift: 7,
speed_up_with_guidance_embed: true,
stage_2_guidance: 1,
stage_2_shift: 1,
start_frame_guidance: 1,
steps: 12,
stochastic_sampling_gamma: 0.3,
strength: 1,
t5_text: "",
t5_text_encoder_decoding: true,
// target_height: 1024, target_width: 768,
tea_cache: false,
tea_cache_end: 100,
tea_cache_max_skip_steps: 3,
tea_cache_start: 5,
tea_cache_threshold: 0.06,
tiled_decoding: false,
tiled_diffusion: false,
upscaler: null,
upscaler_scale: 0,
width: 768,
zero_negative_prompt: false
};
// src/services/defaultParamsDrawThingsImage2Video.ts
var defaultParamsImage2Video = {
aesthetic_score: 6,
batch_count: 1,
batch_size: 1,
causal_inference: 0,
causal_inference_pad: 0,
cfg_zero_init_steps: 0,
cfg_zero_star: false,
clip_l_text: "",
clip_skip: 1,
clip_weight: 1,
compression_artifacts: "h264",
compression_artifacts_quality: 43.1,
controls: [],
crop_left: 0,
crop_top: 0,
fps: 25,
guidance_embed: 3.5,
guidance_scale: 1,
guiding_frame_noise: 0.02,
// Ensure size keys exist for filtering; service overwrites with actual PNG size
width: 768,
height: 1024,
hires_fix: false,
hires_fix_height: 768,
hires_fix_strength: 0.7,
// hires_fix_width: 576,
image_guidance: 1.5,
image_prior_steps: 5,
loras: [],
mask_blur: 1.5,
mask_blur_outset: 0,
model: "ltx_2.3_22b_distilled_1.1_q6p.ckpt",
motion_scale: 127,
negative_aesthetic_score: 2.5,
// negative_original_height: 512, negative_original_width: 512,
negative_prompt: "",
negative_prompt_for_image_prior: true,
num_frames: 65,
open_clip_g_text: "",
// original_height: 512, original_width: 512,
preserve_original_after_inpaint: true,
prompt: "",
refiner_model: null,
refiner_start: 0.85,
resolution_dependent_shift: true,
sampler: "DDIM Trailing",
seed: 175308301,
seed_mode: "Scale Alike",
separate_clip_l: false,
separate_open_clip_g: false,
separate_t5: false,
sharpness: 0,
shift: 7,
speed_up_with_guidance_embed: true,
stage_2_guidance: 1,
stage_2_shift: 1,
start_frame_guidance: 1,
steps: 8,
stochastic_sampling_gamma: 0.3,
strength: 1,
t5_text: "",
t5_text_encoder_decoding: true,
// target_height: 512, target_width: 512,
tea_cache: false,
tea_cache_end: 100,
tea_cache_max_skip_steps: 3,
tea_cache_start: 5,
tea_cache_threshold: 0.06,
tiled_decoding: false,
tiled_diffusion: false,
upscaler: null,
upscaler_scale: 0,
zero_negative_prompt: false
};
// src/services/flux2_9bParamsDrawThings.ts
var flux2_9bOverlays = {
txt2img: {
model: "flux_2_klein_9b_kv_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 6,
resolution_dependent_shift: false,
shift: 6,
sharpness: 0,
strength: 1,
mask_blur: 2.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
},
img2img: {
model: "flux_2_klein_9b_kv_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 6,
resolution_dependent_shift: false,
shift: 6,
sharpness: 0,
strength: 0.925,
mask_blur: 2.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
},
edit: {
maxReferenceImages: 4,
model: "flux_2_klein_9b_kv_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 12,
resolution_dependent_shift: true,
shift: 6,
sharpness: 0,
strength: 1,
mask_blur: 2.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
}
};
// src/services/flux3ParamsDrawThings.ts
var flux3Overlays = {
txt2img: {
model: "flux_3_klein_f16.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 16,
resolution_dependent_shift: false,
shift: 16,
sharpness: 0,
strength: 1,
mask_blur: 2.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
},
img2img: null,
edit: {
maxReferenceImages: 10,
model: "flux_3_klein_f16.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 16,
resolution_dependent_shift: false,
shift: 16,
sharpness: 0,
strength: 1,
mask_blur: 2.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
}
};
// src/services/krea_2ParamsDrawThings.ts
var krea_2Overlays = {
txt2img: {
model: "krea_2_turbo_q6p.ckpt",
guidance_scale: 1,
sampler: "Euler A Trailing",
steps: 8,
shift: 3,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
},
img2img: {
model: "krea_2_turbo_q6p.ckpt",
guidance_scale: 1,
sampler: "Euler A Trailing",
steps: 8,
shift: 3,
sharpness: 0,
strength: 0.925,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
}
};
// src/services/ltx2_3ParamsDrawThings.ts
var ltx2_3Overlays = {
txt2vid: {
model: "ltx_2.3_22b_distilled_1.1_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 12,
shift: 7,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [],
compression_artifacts: "h264",
compression_artifacts_quality: 43.1
},
img2vid: {
maxReferenceImages: 1,
model: "ltx_2.3_22b_distilled_1.1_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 12,
shift: 7,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [],
compression_artifacts: "h264",
compression_artifacts_quality: 43.1
}
};
// src/services/minimax_h3ParamsDrawThings.ts
var minimax_h3Overlays = {
txt2vid: {
model: "minimax_h3_fl2va_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 8,
shift: 12,
shift_for_audio: 3,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [
{
mode: "all",
file: "minimax_h3_fl2v_turbo_4step_v1.2_768p_comfyui_bf16_lora_f16.ckpt",
weight: 0.9
}
],
compression_artifacts: "h264",
compression_artifacts_quality: 43.1,
tiled_decoding: true,
decoding_tile_height: 256,
decoding_tile_overlap: 64,
decoding_tile_width: 256
},
img2vid: {
maxReferenceImages: 2,
model: "minimax_h3_fl2va_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 8,
shift: 12,
shift_for_audio: 3,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [
{
mode: "all",
file: "minimax_h3_fl2v_turbo_4step_v1.2_768p_comfyui_bf16_lora_f16.ckpt",
weight: 0.9
}
],
compression_artifacts: "h264",
compression_artifacts_quality: 43.1,
tiled_decoding: true,
decoding_tile_height: 256,
decoding_tile_overlap: 64,
decoding_tile_width: 256
}
};
// src/services/minimax_h3_ref2vaParamsDrawThings.ts
var minimax_h3_ref2vaOverlays = {
txt2vid: {
model: "minimax_h3_ref2va_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 10,
shift: 12,
shift_for_audio: 3,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [
{
mode: "all",
file: "minimax_h3_ref2v_turbo_8step_v1.0_768p_comfyui_bf16_lora_f16.ckpt",
weight: 0.9
}
],
compression_artifacts: "h264",
compression_artifacts_quality: 43.1,
tiled_decoding: true,
decoding_tile_height: 256,
decoding_tile_overlap: 64,
decoding_tile_width: 256
},
img2vid: {
maxReferenceImages: 4,
model: "minimax_h3_ref2va_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 10,
shift: 12,
shift_for_audio: 3,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [
{
mode: "all",
file: "minimax_h3_ref2v_turbo_8step_v1.0_768p_comfyui_bf16_lora_f16.ckpt",
weight: 0.9
}
],
compression_artifacts: "h264",
compression_artifacts_quality: 43.1,
tiled_decoding: true,
decoding_tile_height: 256,
decoding_tile_overlap: 64,
decoding_tile_width: 256
}
};
// src/services/qwen_imageParamsDrawThings.ts
var qwen_imageOverlays = {
txt2img: {
model: "qwen_image_2512_bf16_q6p.ckpt",
negative_prompt: "\u4F4E\u5206\u8FA8\u7387\uFF0C\u4F4E\u753B\u8D28\uFF0C\u80A2\u4F53\u7578\u5F62\uFF0C\u624B\u6307\u7578\u5F62\uFF0C\u753B\u9762\u8FC7\u9971\u548C\uFF0C\u8721\u50CF\u611F\uFF0C\u4EBA\u8138\u65E0\u7EC6\u8282\uFF0C\u8FC7\u5EA6\u5149\u6ED1\uFF0C\u753B\u9762\u5177\u6709AI\u611F\u3002\u6784\u56FE\u6DF7\u4E71\u3002\u6587\u5B57\u6A21\u7CCA\uFF0C\u626D\u66F2\u3002",
guidance_scale: 1,
sampler: "UniPC Trailing",
steps: 10,
shift: 3,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [
{
mode: "all",
file: "qwen_image_2512_lightning_4_step_v1.0_lora_f16.ckpt",
weight: 1
}
]
},
img2img: {
model: "qwen_image_edit_2511_q6p.ckpt",
guidance_scale: 1,
sampler: "UniPC Trailing",
steps: 8,
shift: 3,
sharpness: 0,
strength: 0.9,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [
{
mode: "all",
file: "qwen_image_edit_2511_lightning_4_step_v1.0_lora_f16.ckpt",
weight: 1
}
]
},
edit: {
maxReferenceImages: 4,
model: "qwen_image_edit_2511_q6p.ckpt",
guidance_scale: 1,
sampler: "UniPC Trailing",
steps: 8,
shift: 3,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [
{
mode: "all",
file: "qwen_image_edit_2511_lightning_4_step_v1.0_lora_f16.ckpt",
weight: 1
}
]
}
};
// src/services/qwen_image_2_1ParamsDrawThings.ts
var NEGATIVE_PROMPT = "\u4F4E\u5206\u8FA8\u7387\uFF0C\u4F4E\u753B\u8D28\uFF0C\u80A2\u4F53\u7578\u5F62\uFF0C\u624B\u6307\u7578\u5F62\uFF0C\u753B\u9762\u8FC7\u9971\u548C\uFF0C\u8721\u50CF\u611F\uFF0C\u4EBA\u8138\u65E0\u7EC6\u8282\uFF0C\u8FC7\u5EA6\u5149\u6ED1\uFF0C\u753B\u9762\u5177\u6709AI\u611F\u3002\u6784\u56FE\u6DF7\u4E71\u3002\u6587\u5B57\u6A21\u7CCA\uFF0C\u626D\u66F2\u3002";
var qwen_image_2_1Overlays = {
txt2img: {
turbo: {
model: "qwen_image_2.1_turbo_q6p.ckpt",
negative_prompt: NEGATIVE_PROMPT,
guidance_embed: 3.5,
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 8,
resolution_dependent_shift: false,
shift: 4,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
clip_l_text: "",
open_clip_g_text: "",
t5_text: "",
controls: [],
loras: []
},
base: {
model: "qwen_image_2.1_q6p.ckpt",
negative_prompt: NEGATIVE_PROMPT,
guidance_embed: 3.5,
guidance_scale: 4,
sampler: "DDIM Trailing",
steps: 16,
resolution_dependent_shift: false,
shift: 4,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
clip_l_text: "",
open_clip_g_text: "",
t5_text: "",
controls: [],
loras: [
{
mode: "all",
file: "qwen_image_2.1_viggle_turbo_v0.3_6step_lora_r256_lora_f16.ckpt",
weight: 0.25
}
]
}
},
img2img: null,
edit: {
turbo: {
maxReferenceImages: 10,
model: "qwen_image_2.1_turbo_q6p.ckpt",
guidance_embed: 3.5,
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 8,
resolution_dependent_shift: true,
shift: 4,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
clip_l_text: "",
open_clip_g_text: "",
t5_text: "",
controls: [],
loras: []
},
base: {
maxReferenceImages: 10,
model: "qwen_image_2.1_q6p.ckpt",
guidance_embed: 3.5,
guidance_scale: 4,
sampler: "DDIM Trailing",
steps: 16,
resolution_dependent_shift: false,
shift: 4,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
clip_l_text: "",
open_clip_g_text: "",
t5_text: "",
controls: [],
loras: [
{
mode: "all",
file: "qwen_image_2.1_viggle_turbo_v0.3_6step_lora_r256_lora_f16.ckpt",
weight: 0.25
}
]
}
}
};
// src/services/z_imageParamsDrawThings.ts
var z_imageOverlays = {
txt2img: {
model: "z_image_turbo_1.0_q6p.ckpt",
guidance_scale: 1,
sampler: "UniPC Trailing",
steps: 8,
shift: 3,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
},
img2img: {
model: "z_image_turbo_1.0_q6p.ckpt",
guidance_scale: 1,
sampler: "UniPC Trailing",
steps: 8,
shift: 3,
sharpness: 0,
strength: 0.925,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
}
};
// src/services/overlays.generated.ts
var OVERLAY_REGISTRY = {
flux2_9b: flux2_9bOverlays,
flux3: flux3Overlays,
krea_2: krea_2Overlays,
ltx2_3: ltx2_3Overlays,
minimax_h3: minimax_h3Overlays,
minimax_h3_ref2va: minimax_h3_ref2vaOverlays,
qwen_image: qwen_imageOverlays,
qwen_image_2_1: qwen_image_2_1Overlays,
z_image: z_imageOverlays
};
// src/services/overlayTypes.ts
var DEFAULT_MAX_REFERENCE_IMAGES = 4;
// src/services/modelOverlays.ts
var MODES = ["txt2img", "img2img", "edit", "txt2vid", "img2vid"];
var LEGACY_IDS = {
"z-image": "z_image",
krea: "krea_2",
krea2: "krea_2",
"qwen-image": "qwen_image",
"qwen-edit": "qwen_image",
"qwen-image-2.1": "qwen_image_2_1:base",
"qwen-image-2.1-turbo": "qwen_image_2_1:turbo",
flux: "flux2_9b",
"flux-2": "flux2_9b",
"flux-3": "flux3",
"flux-3-klein": "flux3",
ltx: "ltx2_3",
minimax: "minimax_h3",
"minimax-ref": "minimax_h3_ref2va"
};
function normalizeModelId(modelId) {
return LEGACY_IDS[modelId] ?? modelId;
}
function isLegacyPresetName(name) {
return Object.prototype.hasOwnProperty.call(LEGACY_IDS, name);
}
function legacyNamesOf(modelId) {
return Object.entries(LEGACY_IDS).filter(([, id]) => id === modelId).map(([name]) => name);
}
var isVariantTable = (value) => !!value && typeof value === "object" && !("model" in value) && Object.values(value).every((v) => !!v && typeof v === "object");
var variantsOf = (file) => [
...new Set(MODES.flatMap((mode) => isVariantTable(file[mode]) ? Object.keys(file[mode]) : []))
];
var emptyOverlay = () => ({ txt2img: null, img2img: null, edit: null, txt2vid: null, img2vid: null });
var modelOverlays = { auto: emptyOverlay() };
for (const [key, file] of Object.entries(OVERLAY_REGISTRY)) {
const variants = variantsOf(file);
for (const variant of variants.length ? variants : [null]) {
const overlay = emptyOverlay();
for (const mode of MODES) {
const entry = file[mode] ?? null;
overlay[mode] = entry === null ? null : isVariantTable(entry) ? variant ? entry[variant] ?? null : null : entry;
}
modelOverlays[variant ? `${key}:${variant}` : key] = overlay;
}
}
modelOverlays.custom = emptyOverlay();
var MODEL_IDS = Object.keys(modelOverlays);
var MODEL_FAMILIES = MODEL_IDS;
var stripToolFields = ({ maxReferenceImages: _max, ...params }) => params;
function getModelOverlay(modelId, mode) {
if (!modelId || modelId === "auto") return null;
const entry = modelOverlays[normalizeModelId(modelId)];
if (!entry) {
console.error(`Unknown model '${modelId}', using defaults`);
return null;
}
if (mode === "zoom" || mode === "restore") return null;
const overlay = entry[mode];
return overlay ? stripToolFields(overlay) : null;
}
function getMaxReferenceImages(modelId, mode) {
const value = modelId ? modelOverlays[normalizeModelId(modelId)]?.[mode]?.maxReferenceImages : void 0;
return typeof value === "number" && value >= 1 ? Math.floor(value) : DEFAULT_MAX_REFERENCE_IMAGES;
}
function isValidModelId(value) {
return typeof value === "string" && MODEL_IDS.includes(normalizeModelId(value));
}
function getModelFilename(modelId, mode) {
if (!modelId || modelId === "auto") return null;
const overlay = modelOverlays[normalizeModelId(modelId)]?.[mode];
return typeof overlay?.model === "string" ? overlay.model : null;
}
function getModelRequiredFiles(modelId, mode) {
const files = [];
if (!modelId || modelId === "auto") return files;
const overlay = modelOverlays[normalizeModelId(modelId)]?.[mode];
if (!overlay) return files;
if (typeof overlay.model === "string") files.push(overlay.model);
if (Array.isArray(overlay.loras)) {
for (const lora of overlay.loras) {
if (typeof lora === "object" && lora !== null && typeof lora.file === "string") files.push(lora.file);
}
}
return files;
}
// src/services/modelInventory.ts
import fs2 from "node:fs";
import path2 from "node:path";
// src/catalog/modelZoo.runtime.json
var modelZoo_runtime_default = { schema: "dtc.model-catalog.runtime.v1", sources: { drawThingsCommunity: "db37e657ad329dd16c2f1200bb47f940369cd9f4", communityModels: "e9851164709187e7249471701708301842f9f222" }, families: { auraflow: { label: "AuraFlow", kind: "image" }, "cosmos2.5_2b": { label: "Cosmos 2.5 2B", kind: "image" }, ernie_image: { label: "ERNIE Image", kind: "image", fallback: { params: { steps: 30, guidance_scale: 4, shift: 4, sampler: "UniPCTrailing" } } }, flux1: { label: "FLUX.1", kind: "image", fallback: { params: { steps: 28, guidance_scale: 4.5, shift: 1, sampler: "EulerATrailing" } } }, flux2: { label: "FLUX.2", kind: "image", fallback: { params: { steps: 28, guidance_scale: 4.5, shift: 1, sampler: "DDIMTrailing" } } }, flux2_4b: { label: "FLUX.2 4B", kind: "image", fallback: { params: { steps: 30, guidance_scale: 4, shift: 3, sampler: "DDIMTrailing" } } }, flux2_9b: { label: "FLUX.2 9B", kind: "image", fallback: { params: { steps: 4, guidance_scale: 1, shift: 3, sampler: "DDIMTrailing" } } }, flux3_5b: { label: "FLUX.3 5B", kind: "image" }, hidream_i1: { label: "HiDream I1", kind: "image", fallback: { params: { steps: 28, guidance_scale: 1, shift: 3, sampler: "EulerATrailing" } } }, hunyuan_video: { label: "Hunyuan Video", kind: "video" }, ideogram_4: { label: "Ideogram 4", kind: "image" }, "kandinsky2.1": { label: "Kandinsky v2.1", kind: "image" }, krea_2: { label: "Krea 2", kind: "image" }, ltx2: { label: "LTX-2", kind: "video" }, "ltx2.3": { label: "LTX-2.3", kind: "video", fallback: { params: { steps: 30, guidance_scale: 5, shift: 5, sampler: "UniPCTrailing" } } }, minimax_h3: { label: "MiniMax H3", kind: "video" }, moss_image: { label: "MOSS Image", kind: "image" }, pixart: { label: "PixArt Sigma", kind: "image" }, qwen_image: { label: "Qwen Image", kind: "image", fallback: { params: { steps: 30, guidance_scale: 4, shift: 2, sampler: "UniPCTrailing" } } }, "qwen_image_2.1": { label: "Qwen Image 2.1", kind: "image" }, sd3: { label: "Stable Diffusion 3 Medium", kind: "image" }, sd3_large: { label: "Stable Diffusion 3 Large", kind: "image" }, "sdxl_base_v0.9": { label: "Stable Diffusion XL Base", kind: "image", fallback: { params: { steps: 16, guidance_scale: 5, shift: 1, sampler: "DPMPP2MAYS" } } }, "sdxl_refiner_v0.9": { label: "Stable Diffusion XL Refiner", kind: "image" }, seedvr2_3b: { label: "SeedVR2", kind: "upscaler" }, seedvr2_7b: { label: "SeedVR2", kind: "upscaler" }, ssd_1b: { label: "Segmind Stable Diffusion XL 1B", kind: "image" }, svd_i2v: { label: "Stable Video Diffusion", kind: "video" }, v1: { label: "Stable Diffusion v1", kind: "image", fallback: { params: { steps: 16, guidance_scale: 5, shift: 1, sampler: "DPMPP2MAYS" } } }, v2: { label: "Stable Diffusion v2", kind: "image" }, "wan_v2.1_1.3b": { label: "Wan v2.1 1.3B", kind: "video", fallback: { params: { steps: 30, guidance_scale: 5, shift: 5, sampler: "EulerATrailing" } } }, "wan_v2.1_14b": { label: "Wan v2.x 14B", kind: "video", fallback: { params: { steps: 30, guidance_scale: 5, shift: 5, sampler: "EulerATrailing" } } }, "wan_v2.2_5b": { label: "Wan v2.2 5B", kind: "video" }, "wurstchen_v3.0_stage_c": { label: "Stable Cascade (W\xFCrstchen v3.0)", kind: "image" }, z_image: { label: "Z Image", kind: "image", fallback: { params: { steps: 30, guidance_scale: 4, shift: 3, sampler: "UniPCTrailing" } } } }, files: ["fasth3_omni_i8x.ckpt", "fasth3_omni_i4x.ckpt", "fasth3_omni_q8p.ckpt", "minimax_h3_vae_f16.ckpt", "qwen_3_vl_32b_50_i8x.ckpt", "moss_image_sft_i8x.ckpt", "moss_image_sft_i4x.ckpt", "moss_image_sft_q8p.ckpt", "flux_2_vae_f16.ckpt", "qwen_3.5_9b_i5x.ckpt", "moss_image_base_i8x.ckpt", "moss_image_base_i4x.ckpt", "moss_image_base_q8p.ckpt", "flux_3_klein_i8x.ckpt", "flux_3_klein_i4x.ckpt", "flux_3_klein_q8p.ckpt", "qwen_3_vl_4b_instruct_i8x.ckpt", "flux_3_klein_base_i8x.ckpt", "flux_3_klein_base_i4x.ckpt", "flux_3_klein_base_q8p.ckpt", "flux_3_klein_f16.ckpt", "flux_3_klein_base_f16.ckpt", "qwen_image_2.1_turbo_i8x.ckpt", "qwen_image_2.1_turbo_i4x.ckpt", "qwen_image_2.1_turbo_q8p.ckpt", "qwen_image_2.1_turbo_q6p.ckpt", "qwen_3_vl_8b_instruct_i8x.ckpt", "qwen_image_2.1_vae_f16.ckpt", "qwen_image_2.1_turbo_f16.ckpt", "qwen_3_vl_8b_instruct_f16.ckpt", "qwen_image_2.1_f16.ckpt", "qwen_image_2.1_i8x.ckpt", "qwen_image_2.1_i4x.ckpt", "qwen_image_2.1_q8p.ckpt", "qwen_image_2.1_q6p.ckpt", "minimax_h3_fl2va_i8x.ckpt", "minimax_h3_fl2va_i4x.ckpt", "minimax_h3_fl2va_q8p.ckpt", "minimax_h3_fl2va_q6p.ckpt", "minimax_h3_ref2va_i8x.ckpt", "minimax_h3_ref2va_i4x.ckpt", "minimax_h3_ref2va_q8p.ckpt", "minimax_h3_ref2va_q6p.ckpt", "anima_aesthetic_1.1_f16.ckpt", "anima_aesthetic_1.1_i8x.ckpt", "anima_aesthetic_1.1_q8p.ckpt", "qwen_3_0.6b_q8p.ckpt", "qwen_image_vae_f16.ckpt", "anima_turbo_1.0_f16.ckpt", "anima_turbo_1.0_i8x.ckpt", "anima_turbo_1.0_q8p.ckpt", "anima_base_1.0_f16.ckpt", "anima_base_1.0_i8x.ckpt", "anima_base_1.0_q8p.ckpt", "krea_2_turbo_i8x.ckpt", "krea_2_turbo_i6x.ckpt", "krea_2_turbo_i4x.ckpt", "krea_2_turbo_q8p.ckpt", "krea_2_turbo_q6p.ckpt", "qwen_3_vl_4b_q8p.ckpt", "ideogram_4_i8x.ckpt", "ideogram_4_i6x.ckpt", "ideogram_4_q8p.ckpt", "ideogram_4_q6p.ckpt", "qwen_3_vl_8b_instruct_q8p.ckpt", "ideogram_4_instant_i8x.ckpt", "ideogram_4_instant_i6x.ckpt", "ideogram_4_instant_q8p.ckpt", "ideogram_4_instant_q6p.ckpt", "ideogram_4_fast_i8x.ckpt", "ideogram_4_fast_i6x.ckpt", "ideogram_4_fast_q8p.ckpt", "ideogram_4_fast_q6p.ckpt", "krea_2_raw_i8x.ckpt", "krea_2_raw_i4x.ckpt", "krea_2_raw_q8p.ckpt", "krea_2_raw_q6p.ckpt", "seedvr2_3b_i8x.ckpt", "seedvr2_3b_q8p.ckpt", "seedvr2_3b_q6p.ckpt", "seedvr2_vae_f16.ckpt", "seedvr2_7b_i8x.ckpt", "seedvr2_7b_q8p.ckpt", "seedvr2_7b_q6p.ckpt", "ltx_2.3_22b_distilled_1.1_i8x.ckpt", "ltx_2.3_22b_distilled_1.1_q8p.ckpt", "ltx_2.3_22b_distilled_1.1_q6p.ckpt", "gemma_3_12b_it_qat_q8p.ckpt", "ltx_2.3_audio_video_vae_f16.ckpt", "ernie_image_turbo_i8x.ckpt", "ernie_image_turbo_q8p.ckpt", "ernie_image_turbo_q6p.ckpt", "ministral_3_3b_q8p.ckpt", "ernie_image_i8x.ckpt", "ernie_image_q8p.ckpt", "ernie_image_q6p.ckpt", "ernie_image_turbo_f16.ckpt", "ministral_3_3b_f16.ckpt", "ernie_image_f16.ckpt", "ltx_2.3_22b_distilled_f16.ckpt", "gemma_3_12b_it_qat_f16.ckpt", "ltx_2.3_22b_dev_f16.ckpt", "flux_2_klein_9b_kv_i8x.ckpt", "flux_2_klein_9b_kv_q8p.ckpt", "flux_2_klein_9b_kv_q6p.ckpt", "qwen_3_8b_q8p.ckpt", "flux_2_klein_9b_kv_f16.ckpt", "qwen_3_8b_f16.ckpt", "ltx_2.3_22b_dev_i8x.ckpt", "ltx_2.3_22b_dev_q8p.ckpt", "ltx_2.3_22b_dev_q6p.ckpt", "ltx_2.3_22b_distilled_i8x.ckpt", "ltx_2.3_22b_distilled_q8p.ckpt", "ltx_2.3_22b_distilled_q6p.ckpt", "z_image_1.0_f16.ckpt", "flux_1_vae_f16.ckpt", "qwen_3_vl_4b_instruct_f16.ckpt", "z_image_1.0_i8x.ckpt", "z_image_1.0_q8p.ckpt", "z_image_1.0_q6p.ckpt", "qwen_3_vl_4b_instruct_q8p.ckpt", "ltx_2_19b_dev_q8p.ckpt", "ltx_2_19b_dev_q6p.ckpt", "ltx_2_audio_video_vae_f16.ckpt", "ltx_2_19b_distilled_q8p.ckpt", "ltx_2_19b_distilled_q6p.ckpt", "flux_2_klein_4b_i8x.ckpt", "flux_2_klein_4b_q8p.ckpt", "flux_2_klein_4b_q6p.ckpt", "qwen_3_4b_q8p.ckpt", "flux_2_klein_base_4b_i8x.ckpt", "flux_2_klein_base_4b_q8p.ckpt", "flux_2_klein_base_4b_q6p.ckpt", "flux_2_klein_base_9b_i8x.ckpt", "flux_2_klein_base_9b_q8p.ckpt", "flux_2_klein_base_9b_q6p.ckpt", "flux_2_klein_4b_f16.ckpt", "qwen_3_4b_f16.ckpt", "flux_2_klein_base_4b_f16.ckpt", "flux_2_klein_9b_f16.ckpt", "flux_2_klein_base_9b_f16.ckpt", "flux_2_klein_9b_i8x.ckpt", "flux_2_klein_9b_q8p.ckpt", "flux_2_klein_9b_q6p.ckpt", "qwen_image_2512_i8x.ckpt", "qwen_image_2512_bf16_q8p.ckpt", "qwen_image_2512_q8p.ckpt", "qwen_image_2512_q6p.ckpt", "qwen_2.5_vl_7b_q8p.ckpt", "qwen_image_2512_bf16_i8x.ckpt", "qwen_image_2512_bf16_q6p.ckpt", "qwen_image_2512_bf16.ckpt", "qwen_2.5_vl_7b_f16.ckpt", "qwen_image_edit_2511_i8x.ckpt", "qwen_image_edit_2511_bf16_q8p.ckpt", "qwen_image_edit_2511_q8p.ckpt", "qwen_image_edit_2511_q6p.ckpt", "qwen_2.5_vl_7b_vit_f16.ckpt", "qwen_image_edit_2511_bf16_i8x.ckpt", "qwen_image_edit_2511_bf16_q6p.ckpt", "qwen_image_layered_1.0_bf16_q8p.ckpt", "qwen_image_layered_vae_f16.ckpt", "qwen_image_layered_1.0_bf16_q6p.ckpt", "flux_2_dev_i8x.ckpt", "flux_2_dev_q8p.ckpt", "flux_2_dev_q6p.ckpt", "mistral_small_3.2_24b_instruct_2506_q8p.ckpt", "flux_2_dev_f16.ckpt", "mistral_small_3.2_24b_instruct_2506_f16.ckpt", "z_image_turbo_1.0_f16.ckpt", "z_image_turbo_1.0_i8x.ckpt", "z_image_turbo_1.0_q8p.ckpt", "z_image_turbo_1.0_q6p.ckpt", "anisora_v3.2_i2v_wan_2.2_a14b_hne_q8p.ckpt", "anisora_v3.2_i2v_wan_2.2_a14b_hne_q6p_svd.ckpt", "umt5_xxl_encoder_q8p.ckpt", "wan_v2.1_video_vae_f16.ckpt", "anisora_v3.2_i2v_wan_2.2_a14b_lne_q8p.ckpt", "anisora_v3.2_i2v_wan_2.2_a14b_lne_q6p_svd.ckpt", "chronoedit_14b_q8p.ckpt", "chronoedit_14b_q6p_svd.ckpt", "open_clip_xlm_roberta_large_vit_h14_f16.ckpt", "wan_v2.2_a14b_hne_t2v_lightning_250928_q8p.ckpt", "wan_v2.2_a14b_hne_t2v_lightning_250928_q6p_svd.ckpt", "qwen_image_edit_2509_bf16.ckpt", "qwen_image_edit_2509_f16.ckpt", "qwen_image_1.0_bf16_q6p.ckpt", "qwen_image_edit_2509_bf16_q6p.ckpt", "qwen_image_edit_2509_bf16_q8p.ckpt", "qwen_image_edit_2509_q8p.ckpt", "qwen_image_edit_2509_q6p.ckpt", "wan_v2.2_5b_ti2v_f16.ckpt", "wan_v2.2_5b_ti2v_q8p.ckpt", "wan_v2.2_video_vae_f16.ckpt", "qwen_image_edit_1.0_q8p.ckpt", "qwen_image_edit_1.0_q6p.ckpt", "qwen_image_1.0_bf16.ckpt", "qwen_image_1.0_f16.ckpt", "chroma_1_hd_r0.1_q8p.ckpt", "chroma_1_hd_r0.1_q5p.ckpt", "clip_vit_l14_f16.ckpt", "t5_xxl_encoder_q6p.ckpt", "qwen_image_1.0_bf16_q8p.ckpt", "qwen_image_1.0_q8p.ckpt", "qwen_image_1.0_q6p.ckpt", "flux_1_krea_dev_q8p.ckpt", "flux_1_krea_dev_q5p.ckpt", "wan_v2.2_a14b_hne_i2v_i8x.ckpt", "wan_v2.2_a14b_hne_i2v_q8p.ckpt", "wan_v2.2_a14b_hne_i2v_q6p_svd.ckpt", "wan_v2.2_a14b_lne_i2v_i8x.ckpt", "wan_v2.2_a14b_lne_i2v_q8p.ckpt", "wan_v2.2_a14b_lne_i2v_q6p_svd.ckpt", "chroma_v48_detail_calibrated_q8p.ckpt", "chroma_v48_detail_calibrated_q5p.ckpt", "wan_v2.2_a14b_hne_t2v_i8x.ckpt", "wan_v2.2_a14b_hne_t2v_q8p.ckpt", "wan_v2.2_a14b_hne_t2v_q6p_svd.ckpt", "wan_v2.2_a14b_lne_t2v_i8x.ckpt", "wan_v2.2_a14b_lne_t2v_q8p.ckpt", "wan_v2.2_a14b_lne_t2v_q6p_svd.ckpt", "chroma_v47_detail_calibrated_q8p.ckpt", "chroma_v47_detail_calibrated_q5p.ckpt", "hidream_e1_1_q8p.ckpt", "hidream_e1_1_q5p.ckpt", "llama_3.1_8b_instruct_q8p.ckpt", "long_clip_vit_l14_f16.ckpt", "hidream_e1_1_f16.ckpt", "llama_3.1_8b_instruct_f16.ckpt", "long_open_clip_vit_bigg14_f16.ckpt", "t5_xxl_encoder_f16.ckpt", "flux_1_kontext_dev_q8p.ckpt", "flux_1_kontext_dev_q5p.ckpt", "flux_1_kontext_dev_f16.ckpt", "wan_2.1_14b_t2v_fusionx_q8p.ckpt", "wan_2.1_14b_t2v_fusionx_q6p_svd.ckpt", "wan_2.1_14b_i2v_fusionx_q8p.ckpt", "wan_2.1_14b_i2v_fusionx_q6p_svd.ckpt", "rayflux_v3.0_aio_q8p.ckpt", "rayflux_v3.0_aio_q5p.ckpt", "pixelwave_flux_1_schnell_04_q8p.ckpt", "pixelwave_flux_1_schnell_04_q5p_svd.ckpt", "juggernaut_xl_ragnarok_f16.ckpt", "juggernaut_xl_ragnarok_q6p_q8p.ckpt", "juggernaut_xl_ragnarok_clip_vit_l14_f16.ckpt", "juggernaut_xl_ragnarok_open_clip_vit_bigg14_f16.ckpt", "sdxl_vae_v1.0_f16.ckpt", "hidream_e1_full_q8p.ckpt", "hidream_e1_full_q5p.ckpt", "wan_2.1_14b_v1.1_fun_inp_q8p.ckpt", "wan_2.1_14b_v1.1_fun_inp_q6p_svd.ckpt", "wan_2.1_1.3b_v1.1_fun_inp_f16.ckpt", "wan_2.1_1.3b_v1.1_fun_inp_q8p.ckpt", "skyreels_v2_i2v_14b_540p_q8p.ckpt", "skyreels_v2_i2v_14b_540p_q6p_svd.ckpt", "skyreels_v2_i2v_14b_720p_q8p.ckpt", "skyreels_v2_i2v_14b_720p_q6p_svd.ckpt", "skyreels_v2_t2v_14b_540p_q8p.ckpt", "skyreels_v2_t2v_14b_540p_q6p_svd.ckpt", "skyreels_v2_t2v_14b_720p_q8p.ckpt", "skyreels_v2_t2v_14b_720p_q6p_svd.ckpt", "hidream_i1_dev_f16.ckpt", "hidream_i1_full_f16.ckpt", "hidream_i1_fast_f16.ckpt", "skyreels_v2_i2v_1.3b_540p_f16.ckpt", "skyreels_v2_i2v_1.3b_540p_q8p.ckpt", "hidream_i1_fast_i8x.ckpt", "hidream_i1_fast_q8p.ckpt", "hidream_i1_fast_q5p.ckpt", "hidream_i1_full_i8x.ckpt", "hidream_i1_full_q8p.ckpt", "hidream_i1_full_q5p.ckpt", "hidream_i1_dev_i8x.ckpt", "hidream_i1_dev_q8p.ckpt", "hidream_i1_dev_q5p.ckpt", "wan_2.1_14b_fun_inp_q8p.ckpt", "wan_2.1_14b_fun_inp_q6p_svd.ckpt", "wan_2.1_1.3b_fun_inp_f16.ckpt", "wan_2.1_1.3b_fun_inp_q8p.ckpt", "wan_v2.1_14b_i2v_480p_q8p.ckpt", "wan_v2.1_14b_i2v_480p_q6p_svd.ckpt", "wan_v2.1_14b_i2v_720p_q8p.ckpt", "wan_v2.1_14b_i2v_720p_q6p_svd.ckpt", "wan_v2.1_14b_720p_q8p.ckpt", "wan_v2.1_14b_720p_q6p_svd.ckpt", "wan_v2.1_14b_720p_q5p_svd.ckpt", "wan_v2.1_1.3b_480p_f16.ckpt", "wan_v2.1_1.3b_480p_q8p.ckpt", "skyreels_v1_hunyuan_t2v_q8p.ckpt", "skyreels_v1_hunyuan_t2v_q5p_svd.ckpt", "hunyuan_video_vae_f16.ckpt", "llava_llama_3_8b_v1.1_q8p.ckpt", "skyreels_v1_hunyuan_i2v_q8p.ckpt", "skyreels_v1_hunyuan_i2v_q5p_svd.ckpt", "devmode_v0.3_turbo_q8p.ckpt", "devmode_v0.3_turbo_q5p_svd.ckpt", "shuttle_v3.1_aesthetic_q8p.ckpt", "shuttle_v3.1_aesthetic_q5p_svd.ckpt", "shuttle_jaguar_q8p.ckpt", "shuttle_jaguar_q5p_svd.ckpt", "schnellmode_v3.3_q8p.ckpt", "schnellmode_v3.3_q5p_svd.ckpt", "artsy_vibe_v1_q8p.ckpt", "artsy_vibe_v1_q5p_svd.ckpt", "hunyuan_video_t2v_720p_q8p.ckpt", "hunyuan_video_t2v_720p_q5p_svd.ckpt", "flux_1_canny_dev_q8p.ckpt", "flux_1_canny_dev_q5p.ckpt", "flux_1_dev_de_distill_q8p.ckpt", "flux_1_dev_de_distill_q5p.ckpt", "flux_1_fill_dev_q8p.ckpt", "flux_1_fill_dev_q5p.ckpt", "flux_1_depth_dev_q8p.ckpt", "flux_1_depth_dev_q5p.ckpt", "sd3_medium_3.5_f16.ckpt", "sd3_medium_3.5_q8p.ckpt", "open_clip_vit_bigg14_f16.ckpt", "sd3_vae_f16.ckpt", "sd3_large_turbo_3.5_q8p.ckpt", "sd3_large_turbo_3.5_q6p.ckpt", "sd3_large_3.5_q8p.ckpt", "sd3_large_3.5_q6p.ckpt", "sd3_large_3.5_f16.ckpt", "ootd_vton_upper_body_1.0_f16.ckpt", "vae_ft_mse_840000_f16.ckpt", "ootd_vton_full_body_1.0_f16.ckpt", "flux_1_dev_f16.ckpt", "flux_1_dev_q8p.ckpt", "flux_1_dev_q5p.ckpt", "flux_1_schnell_q8p.ckpt", "flux_1_schnell_q5p.ckpt", "auraflow_v0.2_q8p.ckpt", "auraflow_v0.2_q5p.ckpt", "pile_t5_xl_encoder_q8p.ckpt", "kwai_kolors_inpainting_1.0_f16.ckpt", "kwai_kolors_inpainting_1.0_q6p_q8p.ckpt", "chatglm3_6b_q6p_q8p.ckpt", "auraflow_v0.1_q8p.ckpt", "auraflow_v0.1_q5p.ckpt", "kwai_kolors_1.0_f16.ckpt", "kwai_kolors_1.0_q6p_q8p.ckpt", "pixart_sigma_xl_2_512_ms_f16.ckpt", "pixart_sigma_xl_2_512_ms_q8p.ckpt", "svd_i2v_xt_1.1_f16.ckpt", "svd_i2v_xt_1.1_q6p_q8p.ckpt", "open_clip_vit_h14_vision_model_f16.ckpt", "svd_i2v_1.0_f16.ckpt", "svd_i2v_1.0_q6p_q8p.ckpt", "pixart_sigma_xl_2_1024_ms_f16.ckpt", "pixart_sigma_xl_2_1024_ms_q8p.ckpt", "wurstchen_3.0_stage_b_f16.ckpt", "wurstchen_3.0_stage_c_f32_f16.ckpt", "wurstchen_3.0_stage_b_q6p_q8p.ckpt", "wurstchen_3.0_stage_c_f32_q6p_q8p.ckpt", "wurstchen_3.0_stage_a_hq_f16.ckpt", "sd3_medium_f16.ckpt", "sd3_medium_q8p.ckpt", "sd_xl_turbo_f16.ckpt", "sd_xl_turbo_q6p_q8p.ckpt", "colorfulxl_v6.0_f16.ckpt", "colorfulxl_v6.0_q6p_q8p.ckpt", "colorfulxl_v6.0_clip_vit_l14_f16.ckpt", "colorfulxl_v6.0_open_clip_vit_bigg14_f16.ckpt", "proteus_v0.3_f16.ckpt", "proteus_v0.3_q6p_q8p.ckpt", "proteus_v0.3_clip_vit_l14_f16.ckpt", "proteus_v0.3_open_clip_vit_bigg14_f16.ckpt", "icatcher_realistic_f16.ckpt", "icatcher_realistic_q6p_q8p.ckpt", "icatcher_realistic_clip_vit_l14_f16.ckpt", "icatcher_realistic_open_clip_vit_bigg14_f16.ckpt", "icatcher_cartoon_f16.ckpt", "icatcher_cartoon_q6p_q8p.ckpt", "icatcher_cartoon_clip_vit_l14_f16.ckpt", "icatcher_cartoon_open_clip_vit_bigg14_f16.ckpt", "realvisxl_v4.0_f16.ckpt", "realvisxl_v4.0_q6p_q8p.ckpt", "realvisxl_v4.0_clip_vit_l14_f16.ckpt", "realvisxl_v4.0_open_clip_vit_bigg14_f16.ckpt", "pixelwave_10_f16.ckpt", "pixelwave_10_q6p_q8p.ckpt", "pixelwave_10_clip_vit_l14_f16.ckpt", "pixelwave_10_open_clip_vit_bigg14_f16.ckpt", "juggernaut_xl_v9_f16.ckpt", "juggernaut_xl_v9_q6p_q8p.ckpt", "juggernaut_xl_v9_clip_vit_l14_f16.ckpt", "juggernaut_xl_v9_open_clip_vit_bigg14_f16.ckpt", "pixelwave_v9_f16.ckpt", "pixelwave_v9_q6p_q8p.ckpt", "pixelwave_v9_clip_vit_l14_f16.ckpt", "pixelwave_v9_open_clip_vit_bigg14_f16.ckpt", "juggernaut_xl_x_f16.ckpt", "juggernaut_xl_x_q6p_q8p.ckpt", "juggernaut_xl_x_clip_vit_l14_f16.ckpt", "juggernaut_xl_x_open_clip_vit_bigg14_f16.ckpt", "animatelcm_svd_xt_v1.1_f16.ckpt", "animatelcm_svd_xt_v1.1_q6p_q8p.ckpt", "open_clip_vit_h14_visual_proj_f16.ckpt", "dreamshaper_xl_v2.1_turbo_f16.ckpt", "dreamshaper_xl_v2.1_turbo_q6p_q8p.ckpt", "dreamshaper_xl_v2.1_turbo_clip_vit_l14_f16.ckpt", "dreamshaper_xl_v2.1_turbo_open_clip_vit_bigg14_f16.ckpt", "juggernaut_xl_v9_lightning_f16.ckpt", "juggernaut_xl_v9_lightning_q6p_q8p.ckpt", "juggernaut_xl_v9_lightning_clip_vit_l14_f16.ckpt", "juggernaut_xl_v9_lightning_open_clip_vit_bigg14_f16.ckpt", "rev_animated_v1.22_f16.ckpt", "rev_animated_v1.22_q6p_q8p.ckpt", "rev_animated_v1.22_clip_vit_l14_f16.ckpt", "realistic_vision_v5.1_f16.ckpt", "realistic_vision_v5.1_q6p_q8p.ckpt", "realistic_vision_v5.1_clip_vit_l14_f16.ckpt", "dreamshaper_v8_f16.ckpt", "dreamshaper_v8_q6p_q8p.ckpt", "dreamshaper_v8_clip_vit_l14_f16.ckpt", "counterfeit_v3.0_f16.ckpt", "counterfeit_v3.0_q6p_q8p.ckpt", "counterfeit_v3.0_clip_vit_l14_f16.ckpt", "majicmix_realistic_v7_f16.ckpt", "majicmix_realistic_v7_q6p_q8p.ckpt", "majicmix_realistic_v7_clip_vit_l14_f16.ckpt", "animagine_xl_v3.1_f16.ckpt", "animagine_xl_v3.1_q6p_q8p.ckpt", "animagine_xl_v3.1_clip_vit_l14_f16.ckpt", "animagine_xl_v3.1_open_clip_vit_bigg14_f16.ckpt", "juggernaut_reborn_f16.ckpt", "juggernaut_reborn_q6p_q8p.ckpt", "juggernaut_reborn_clip_vit_l14_f16.ckpt", "playground_v2_f16.ckpt", "playground_v2_q6p_q8p.ckpt", "playground_v2.5_f16.ckpt", "playground_v2.5_q6p_q8p.ckpt", "ssd_1b_f16.ckpt", "ssd_1b_q6p_q8p.ckpt", "disney_pixar_cartoon_type_b_q6p_q8p.ckpt", "disney_pixar_cartoon_type_b_clip_vit_l14_f16.ckpt", "wd_v1.3_f16.ckpt", "nitro_v1_f16.ckpt", "nitro_v1_clip_vit_l14_f16.ckpt", "cyberpunk_anime_f16.ckpt", "cyberpunk_anime_clip_vit_l14_f16.ckpt", "redshift_v1_f16.ckpt", "redshift_v1_clip_vit_l14_f16.ckpt", "redshift_768_v_f16.ckpt", "redshift_768_v_open_clip_vit_h14_f16.ckpt", "dnd_30000_f16.ckpt", "dnd_30000_clip_vit_l14_f16.ckpt", "trnlgcy_f16.ckpt", "trnlgcy_clip_vit_l14_f16.ckpt", "mdjrny_v4_f16.ckpt", "mdjrny_v4_clip_vit_l14_f16.ckpt", "anything_v3_f16.ckpt", "anything_v3_clip_vit_l14_f16.ckpt", "anything_v3_vae_f16.ckpt", "classicanim_v1_f16.ckpt", "classicanim_v1_clip_vit_l14_f16.ckpt", "modi_v1_f16.ckpt", "modi_v1_clip_vit_l14_f16.ckpt", "arcane_v3_f16.ckpt", "arcane_v3_clip_vit_l14_f16.ckpt", "hassanblend_v1.5.1.2_f16.ckpt", "hassanblend_v1.5.1.2_clip_vit_l14_f16.ckpt", "lvngvncnt_v2_f16.ckpt", "lvngvncnt_v2_clip_vit_l14_f16.ckpt", "spiderverse_v1_f16.ckpt", "spiderverse_v1_clip_vit_l14_f16.ckpt", "eldenring_v3_f16.ckpt", "eldenring_v3_clip_vit_l14_f16.ckpt", "papercut_v1_f16.ckpt", "papercut_v1_clip_vit_l14_f16.ckpt", "voxelart_v1_f16.ckpt", "voxelart_v1_clip_vit_l14_f16.ckpt", "balloonart_v1_f16.ckpt", "balloonart_v1_clip_vit_l14_f16.ckpt", "f222_f16.ckpt", "supermarionation_v2_f16.ckpt", "supermarionation_v2_clip_vit_l14_f16.ckpt", "inkpunk_v2_f16.ckpt", "inkpunk_v2_clip_vit_l14_f16.ckpt", "samdoesart_v3_f16.ckpt", "samdoesart_v3_clip_vit_l14_f16.ckpt", "ghibli_v1_f16.ckpt", "ghibli_v1_clip_vit_l14_f16.ckpt", "analog_v1_f16.ckpt", "analog_v1_clip_vit_l14_f16.ckpt", "dnd_classes_and_species_f16.ckpt", "dnd_classes_and_species_clip_vit_l14_f16.ckpt", "aloeveras_simpmaker_3k1_f16.ckpt", "hna_3dkx_1.1_f16.ckpt", "hna_3dkx_1.1_clip_vit_l14_f16.ckpt", "seek_art_mega_v1_f16.ckpt", "seek_art_mega_v1_clip_vit_l14_f16.ckpt", "deliberate_v2_q6p_q8p.ckpt", "deliberate_v2_clip_vit_l14_f16.ckpt", "sd_xl_base_1.0_f16.ckpt", "sd_xl_base_1.0_q6p_q8p.ckpt", "sd_xl_refiner_1.0_f16.ckpt", "sd_xl_refiner_1.0_q6p_q8p.ckpt", "sd_xl_base_0.9_f16.ckpt", "sdxl_vae_f16.ckpt", "sd_xl_refiner_0.9_f16.ckpt", "fooocus_inpaint_sd_xl_v2.6_f16.ckpt", "fooocus_inpaint_sd_xl_v2.6_q6p_q8p.ckpt", "sd_v1.4_f16.ckpt", "sd_v1.5_f16.ckpt", "sd_v1.5_inpainting_f16.ckpt", "sd_v2.0_f16.ckpt", "open_clip_vit_h14_f16.ckpt", "sd_v2.0_768_v_f16.ckpt", "sd_v2.0_inpainting_f16.ckpt", "sd_v2.0_depth_f16.ckpt", "sd_v2.1_f16.ckpt", "sd_v2.1_768_v_f16.ckpt", "kandinsky_f16.ckpt", "kandinsky_movq_f16.ckpt", "xlm_roberta_f16.ckpt", "svd_i2v_xt_1.0_f16.ckpt", "svd_i2v_xt_1.0_q6p_q8p.ckpt", "minisd_v1.4_f16.ckpt", "instruct_pix2pix_22000_f16.ckpt", "2dn_f16.ckpt", "2dn_clip_vit_l14_f16.ckpt", "2dn_open_clip_vit_bigg14_f16.ckpt", "1693152_8stepscrearthyperflux_creartultimate_q8p.ckpt", "862930_8stepscrearthyperflux_v24hyperdevfp8unet_q8p.ckpt", "930403_8stepscrearthyperflux_v26hyperdevfp8unet_f16.ckpt", "930403_8stepscrearthyperflux_v26hyperdevfp8unet_q8p.ckpt", "1187144_8stepscrearthyperflux_v30hyperdevfp8unet_q8p.ckpt", "1315145_8stepscrearthyperflux_v40hyperdevfp8unet_q8p.ckpt", "987485_acornisspinningflux_aisfluxdedistilled_q8p.ckpt", "1374658_acornisspinningflux_aisfluxv15_q8p.ckpt", "1450688_acornisspinningflux_aisfdedistilledv15_q8p.ckpt", "1298942_acornisspinningflux_aisfhyper8stepv15_q8p.ckpt", "1656743_acornisspinningflux_aisfv169_q8p.ckpt", "1052470_acornisspinningflux_aisf11h8stpchinfx_q8p.ckpt", "1095910_agfluxfillnsfwfp8_agfluxfillnsfwv17fp8_q8p.ckpt", "884843_agflux_schnellv10fp8_q8p.ckpt", "864441_agflux_v10fp8_q8p.ckpt", "1055211_agflux_v21fp8_q8p.ckpt", "1244250_agflux_v3fp8_q8p.ckpt", "agga_s_utopia__illustrious_sdxl_f16.ckpt", "agga_s_utopia__illustrious_sdxl_clip_vit_l14_f16.ckpt", "agga_s_utopia__illustrious_sdxl_open_clip_vit_bigg14_f16.ckpt", "amanatsu_illustrious_f16.ckpt", "amanatsu_illustrious_clip_vit_l14_f16.ckpt", "amanatsu_illustrious_open_clip_vit_bigg14_f16.ckpt", "anillustrious_f16.ckpt", "anillustrious_clip_vit_l14_f16.ckpt", "anillustrious_open_clip_vit_bigg14_f16.ckpt", "animij_f16.ckpt", "animij_clip_vit_l14_f16.ckpt", "animij_open_clip_vit_bigg14_f16.ckpt", "anisora_v2_i2v_wan_2.1_14b_q8p.ckpt", "anisora_v2_i2v_wan_2.1_14b_q6p_svd.ckpt", "anisora_v3.1_i2v_wan_2.1_14b_q8p.ckpt", "anisora_v3.1_i2v_wan_2.1_14b_q6p_svd.ckpt", "artofura_furry_mix_f16.ckpt", "artofura_furry_mix_clip_vit_l14_f16.ckpt", "artofura_furry_mix_open_clip_vit_bigg14_f16.ckpt", "974825_artsydream_v1fp16_q8p.ckpt", "974932_artsydream_v1fp8_q8p.ckpt", "1004320_artsydream_v2fp16_q8p.ckpt", "1004235_artsydream_v2fp8_q8p.ckpt", "1023964_artsydream_v3fp16_q8p.ckpt", "1023471_artsydream_v3fp8_q8p.ckpt", "1071391_artsydream_v4fp16_q8p.ckpt", "1070930_artsydream_v4fp8_q8p.ckpt", "1136806_artsydream_v5fp16_q8p.ckpt", "1136364_artsydream_v5fp8_q8p.ckpt", "1213649_artsydream_v6fp16_q8p.ckpt", "1213097_artsydream_v6fp8_q8p.ckpt", "1308807_artsyvibe_v1fp16_q8p.ckpt", "1308180_artsyvibe_v1fp8_q8p.ckpt", "1842885_artsyvibe_v2fp16_q8p.ckpt", "1840540_artsyvibe_v2fp8_q8p.ckpt", "asian_realism_by_stable_yogi_pony_f16.ckpt", "asian_realism_by_stable_yogi_pony_clip_vit_l14_f16.ckpt", "asian_realism_by_stable_yogi_pony_open_clip_vit_bigg14_f16.ckpt", "980131_atomixfluxunet_v10_q8p.ckpt", "aungir_aungir_t6a4_1405004_f16.ckpt", "aungir_aungir_t6a4_1405004_clip_vit_l14_f16.ckpt", "aungir_aungir_t6a4_1405004_open_clip_vit_bigg14_f16.ckpt", "aungir_aungir_t6ao4.5_1723632_f16.ckpt", "aungir_aungir_t6ao4.5_1723632_clip_vit_l14_f16.ckpt", "aungir_aungir_t6ao4.5_1723632_open_clip_vit_bigg14_f16.ckpt", "big_love_f16.ckpt", "big_love_clip_vit_l14_f16.ckpt", "big_love_open_clip_vit_bigg14_f16.ckpt", "bismuth_illustrious_mix_f16.ckpt", "bismuth_illustrious_mix_clip_vit_l14_f16.ckpt", "bismuth_illustrious_mix_open_clip_vit_bigg14_f16.ckpt", "blendermix_f16.ckpt", "blendermix_clip_vit_l14_f16.ckpt", "blendermix_open_clip_vit_bigg14_f16.ckpt", "808159_bluepencilflux1_v010_q8p.ckpt", "867256_bluepencilflux1_v021_q8p.ckpt", "boleromixillustrious_f16.ckpt", "boleromixillustrious_clip_vit_l14_f16.ckpt", "boleromixillustrious_open_clip_vit_bigg14_f16.ckpt", "978066_c4pacitor_av2alpha_q8p.ckpt", "1035832_c4pacitor_av2beta_q8p.ckpt", "845592_c4pacitor_dv1_q8p.ckpt", "949363_c4pacitor_dv11_q8p.ckpt", "1123235_c4pacitor_dv2_q8p.ckpt", "1700674_c4pacitor_dv3alpha_q8p.ckpt", "954181_c4pacitor_sv11_q8p.ckpt", "1086868_c4pacitor_sv2alpha_q8p.ckpt", "candied_anime_illustriousxl_f16.ckpt", "candied_anime_illustriousxl_clip_vit_l14_f16.ckpt", "candied_anime_illustriousxl_open_clip_vit_bigg14_f16.ckpt", "1178183_centerfoldflux_v35fp8e54steps_q8p.ckpt", "1845222_centerfoldflux_v40fp8e5m2_q8p.ckpt", "chroma_1_hd_annealed_q8p.ckpt", "chroma_1_hd_annealed_q5p.ckpt", "chroma_v38_detail_calibrated_q8p.ckpt", "chroma_v38_detail_calibrated_q5p.ckpt", "chroma_v39_detail_calibrated_q8p.ckpt", "chroma_v39_detail_calibrated_q5p.ckpt", "chroma_v40_detail_calibrated_q8p.ckpt", "chroma_v40_detail_calibrated_q5p.ckpt", "chroma_v41_detail_calibrated_q8p.ckpt", "chroma_v41_detail_calibrated_q5p.ckpt", "chroma_v42_detail_calibrated_q8p.ckpt", "chroma_v42_detail_calibrated_q5p.ckpt", "chroma_v43_detail_calibrated_q8p.ckpt", "chroma_v43_detail_calibrated_q5p.ckpt", "chroma_v44_detail_calibrated_q8p.ckpt", "chroma_v44_detail_calibrated_q5p.ckpt", "chroma_v45_detail_calibrated_q8p.ckpt", "chroma_v45_detail_calibrated_q5p.ckpt", "chroma_v46_detail_calibrated_q8p.ckpt", "chroma_v46_detail_calibrated_q5p.ckpt", "circusmix_f16.ckpt", "circusmix_clip_vit_l14_f16.ckpt", "circusmix_open_clip_vit_bigg14_f16.ckpt", "765642_colorfulasiangirlflux_beta_q8p.ckpt", "996001_colossusprojectflux_21dedistilledaioexp_q8p.ckpt", "1846322_colossusprojectflux_v10aiofp8_q8p.ckpt", "931988_colossusprojectflux_v10allinonefp8_q8p.ckpt", "1860608_colossusprojectflux_v10bfp8aiobobfp8_q8p.ckpt", "1851709_colossusprojectflux_v10behemothaiofp16_q8p.ckpt", "940696_colossusprojectflux_v10fp16unetonly_q8p.ckpt", "1855312_colossusprojectflux_v10unetonlyfp16_q8p.ckpt", "1848909_colossusprojectflux_v10unetonlyfp8_q8p.ckpt", "971579_colossusprojectflux_v20allinoneexp_q8p.ckpt", "1159932_colossusprojectflux_v42aio_q8p.ckpt", "1495910_colossusprojectflux_v44aio_q8p.ckpt", "1443922_colossusprojectflux_v50aio_q8p.ckpt", "1507835_colossusprojectflux_v50aiobehemoth_q8p.ckpt", "1462430_colossusprojectflux_v50fp8unet_q8p.ckpt", "1703060_colossusprojectflux_v90aio_q8p.ckpt", "1045901_copaxtimeless_fluxrealfast_q8p.ckpt", "894590_copaxtimeless_stylemix1fluxdevfp16_q8p.ckpt", "897535_copaxtimeless_stylemix1fp8_q8p.ckpt", "975743_copaxtimeless_stylemix2_q8p.ckpt", "1338565_copaxtimeless_xpluscartoon_q8p.ckpt", "954640_copaxtimeless_xplusmix1_q8p.ckpt", "962412_copaxtimeless_xplusmix1fp8_q8p.ckpt", "982160_copaxtimeless_xplusmix2_q8p.ckpt", "1134093_copaxtimeless_xplusmix3_q8p.ckpt", "1148473_copaxtimeless_xplusmix3dark_q8p.ckpt", "1217501_copaxtimeless_xplusmix4_q8p.ckpt", "801556_copaxtimeless_xplusposes_q8p.ckpt", "783956_copaxtimeless_xplusunrealfast_q8p.ckpt", "778112_copaxtimeless_xplus1_q8p.ckpt", "907183_copaxtimeless_xplus2_q8p.ckpt", "1085190_copaxtimeless_xplus2basetrain_q8p.ckpt", "copax_pony_xl_f16.ckpt", "copax_pony_xl_clip_vit_l14_f16.ckpt", "copax_pony_xl_open_clip_vit_bigg14_f16.ckpt", "crow___pony_qp_f16.ckpt", "crow___pony_qp_clip_vit_l14_f16.ckpt", "crow___pony_qp_open_clip_vit_bigg14_f16.ckpt", "cyberillustrious_cyberrealistic_f16.ckpt", "cyberillustrious_cyberrealistic_clip_vit_l14_f16.ckpt", "cyberillustrious_cyberrealistic_open_clip_vit_bigg14_f16.ckpt", "cyberrealistic_f16.ckpt", "cyberrealistic_clip_vit_l14_f16.ckpt", "cyberrealistic_pony_v8_1346181_f16.ckpt", "cyberrealistic_pony_v8_1346181_clip_vit_l14_f16.ckpt", "cyberrealistic_pony_v8_1346181_open_clip_vit_bigg14_f16.ckpt", "cyberrealistic_pony_v8.5_1478064_f16.ckpt", "cyberrealistic_pony_v8.5_1478064_clip_vit_l14_f16.ckpt", "cyberrealistic_pony_v8.5_1478064_open_clip_vit_bigg14_f16.ckpt", "cyberrealistic_pony_v9.0_alt_1_1691220_f16.ckpt", "cyberrealistic_pony_v9.0_alt_1_1691220_clip_vit_l14_f16.ckpt", "cyberrealistic_pony_v9.0_alt_1_1691220_open_clip_vit_bigg14_f16.ckpt", "cyberrealistic_flux_v2.5_f16.ckpt", "cyberrealistic_flux_v2.5_q8p.ckpt", "cyberrealistic_pony_catalyst_f16.ckpt", "cyberrealistic_pony_catalyst_clip_vit_l14_f16.ckpt", "cyberrealistic_pony_catalyst_open_clip_vit_bigg14_f16.ckpt", "cyberrealistic_pony_semi_realistic_f16.ckpt", "cyberrealistic_pony_semi_realistic_clip_vit_l14_f16.ckpt", "cyberrealistic_pony_semi_realistic_open_clip_vit_bigg14_f16.ckpt", "cyberrealistic_xl_f16.ckpt", "cyberrealistic_xl_clip_vit_l14_f16.ckpt", "cyberrealistic_xl_open_clip_vit_bigg14_f16.ckpt", "1048219_demoncoresfwnsfw_fluxv13_q8p.ckpt", "1357212_demoncoresfwnsfw_v25helheimprojectaio_q8p.ckpt", "dhxl_v1.0_f16.ckpt", "dhxl_v1.0_clip_vit_l14_f16.ckpt", "dhxl_v1.0_open_clip_vit_bigg14_f16.ckpt", "dixar_f16.ckpt", "dixar_clip_vit_l14_f16.ckpt", "dixar_open_clip_vit_bigg14_f16.ckpt", "dreamisoa_remix_f16.ckpt", "dreamisoa_remix_clip_vit_l14_f16.ckpt", "dreamisoa_remix_open_clip_vit_bigg14_f16.ckpt", "duchaiten_pony_xl_no_score_v5.2_706363_f16.ckpt", "duchaiten_pony_xl_no_score_v5.2_706363_clip_vit_l14_f16.ckpt", "duchaiten_pony_xl_no_score_v5.2_706363_open_clip_vit_bigg14_f16.ckpt", "duchaiten_pony_xl_no_score_v6.0_817261_f16.ckpt", "duchaiten_pony_xl_no_score_v6.0_817261_clip_vit_l14_f16.ckpt", "duchaiten_pony_xl_no_score_v6.0_817261_open_clip_vit_bigg14_f16.ckpt", "duchaiten_cool_age_f16.ckpt", "duchaiten_cool_age_clip_vit_l14_f16.ckpt", "duchaiten_cool_age_open_clip_vit_bigg14_f16.ckpt", "duchaiten_noobai_f16.ckpt", "duchaiten_noobai_clip_vit_l14_f16.ckpt", "duchaiten_noobai_open_clip_vit_bigg14_f16.ckpt", "duchaiten_noobai_cinematic_f16.ckpt", "duchaiten_noobai_cinematic_clip_vit_l14_f16.ckpt", "duchaiten_noobai_cinematic_open_clip_vit_bigg14_f16.ckpt", "duchaiten_pony_real_f16.ckpt", "duchaiten_pony_real_clip_vit_l14_f16.ckpt", "duchaiten_pony_real_open_clip_vit_bigg14_f16.ckpt", "1677057_edgeofreality_32beyondreality_q8p.ckpt", "1224657_edgeofreality_v30_q8p.ckpt", "editijon_k_pop_f16.ckpt", "editijon_k_pop_clip_vit_l14_f16.ckpt", "editijon_k_pop_open_clip_vit_bigg14_f16.ckpt", "epicrealism_xl_f16.ckpt", "epicrealism_xl_clip_vit_l14_f16.ckpt", "epicrealism_xl_open_clip_vit_bigg14_f16.ckpt", "eri_lumenveil_v1_illustrious_nai_f16.ckpt", "eri_lumenveil_v1_illustrious_nai_clip_vit_l14_f16.ckpt", "eri_lumenveil_v1_illustrious_nai_open_clip_vit_bigg14_f16.ckpt", "fantasm_pony_xl_f16.ckpt", "fantasm_pony_xl_clip_vit_l14_f16.ckpt", "fantasm_pony_xl_open_clip_vit_bigg14_f16.ckpt", "795206_fenrisxlflux_fenrisfluxv1fp8_q8p.ckpt", "five_stars_illustrious_1.0_1398525_f16.ckpt", "five_stars_illustrious_1.0_1398525_clip_vit_l14_f16.ckpt", "five_stars_illustrious_1.0_1398525_open_clip_vit_bigg14_f16.ckpt", "five_stars_illustrious_4.0_1657020_f16.ckpt", "five_stars_illustrious_4.0_1657020_clip_vit_l14_f16.ckpt", "five_stars_illustrious_4.0_1657020_open_clip_vit_bigg14_f16.ckpt", "959302_fluxrealistic_fluxrealisticsamayv2_q8p.ckpt", "1054490_flux1_v10fp8_q8p.ckpt", "1103485_flux1_v10fp8schnell_q8p.ckpt", "1219311_flux1_v20fp8_q8p.ckpt", "1319871_flux1_v30fp8_q8p.ckpt", "1442202_flux1_v30papfp8_q8p.ckpt", "752959_flux1devasian_v10fp16_q8p.ckpt", "1519790_flux1eastfp8_canny_q8p.ckpt", "1519801_flux1eastfp8_depth_q8p.ckpt", "1519030_flux1eastfp8_dev_q8p.ckpt", "1519446_flux1eastfp8_fill_q8p.ckpt", "947686_fluxedupfluxnsfw_10_q8p.ckpt", "1126942_fluxedupfluxnsfw_21_q8p.ckpt", "1182699_fluxedupfluxnsfw_22_q8p.ckpt", "1305680_fluxedupfluxnsfw_24_q8p.ckpt", "1466679_fluxedupfluxnsfw_25_q8p.ckpt", "1700814_fluxedupfluxnsfw_40devfp8_q8p.ckpt", "1823302_fluxedupfluxnsfw_41_q8p.ckpt", "1050076_fluxmania_i_q8p.ckpt", "1463804_fluxmania_iv_q8p.ckpt", "1769925_fluxmania_legacy_q8p.ckpt", "1539776_fluxmania_v_q8p.ckpt", "furrytoonmix_f16.ckpt", "furrytoonmix_clip_vit_l14_f16.ckpt", "furrytoonmix_open_clip_vit_bigg14_f16.ckpt", "1329004_genovaapex_1618experiment_q8p.ckpt", "1831456_genovaapex_genovav2_q8p.ckpt", "1209969_genovaapex_plus_q8p.ckpt", "1111281_genovaapex_real_q8p.ckpt", "1068773_genovaapex_s_q8p.ckpt", "getphat_flux_reality_nsfw_v11_softcore_q8p.ckpt", "1868950_gonzalomoxlfluxpony_v03fluxityfp8_q8p.ckpt", "1883195_gonzalomoxlfluxpony_v10fluxityfp8_q8p.ckpt", "homosimile_xl_pony__illustrious__noobai_f16.ckpt", "homosimile_xl_pony__illustrious__noobai_clip_vit_l14_f16.ckpt", "homosimile_xl_pony__illustrious__noobai_open_clip_vit_bigg14_f16.ckpt", "hoseki_lustrousmix_illustriousxl_f16.ckpt", "hoseki_lustrousmix_illustriousxl_clip_vit_l14_f16.ckpt", "hoseki_lustrousmix_illustriousxl_open_clip_vit_bigg14_f16.ckpt", "hoseki_lustrousmix_pony_xl_f16.ckpt", "hoseki_lustrousmix_pony_xl_clip_vit_l14_f16.ckpt", "hoseki_lustrousmix_pony_xl_open_clip_vit_bigg14_f16.ckpt", "hs_ultrahd_cg_f16.ckpt", "hs_ultrahd_cg_clip_vit_l14_f16.ckpt", "hs_ultrahd_cg_open_clip_vit_bigg14_f16.ckpt", "1254943_hyperfluxdedistilled_hyper16stepsfp8_q8p.ckpt", "1255083_hyperfluxdedistilled_hyper8stepsfp8_q8p.ckpt", "icedcoffeeil_f16.ckpt", "icedcoffeeil_clip_vit_l14_f16.ckpt", "icedcoffeeil_open_clip_vit_bigg14_f16.ckpt", "iffymix_xl_f16.ckpt", "iffymix_xl_clip_vit_l14_f16.ckpt", "iffymix_xl_open_clip_vit_bigg14_f16.ckpt", "illumiyume_xl_illustrious_f16.ckpt", "illumiyume_xl_illustrious_clip_vit_l14_f16.ckpt", "illumiyume_xl_illustrious_open_clip_vit_bigg14_f16.ckpt", "1108227_illustrationjuanerghibli_v10_q8p.ckpt", "1215918_illustrationjuanerghibli_v20_q8p.ckpt", "illustrij_f16.ckpt", "illustrij_clip_vit_l14_f16.ckpt", "illustrij_open_clip_vit_bigg14_f16.ckpt", "illustrij_genv1_f16.ckpt", "illustrij_genv1_q6p_q8p.ckpt", "illustrij_genv1_clip_vit_l14_f16.ckpt", "illustrij_genv1_open_clip_vit_bigg14_f16.ckpt", "illustrious_black_magic_illustrious_noob_more_f16.ckpt", "illustrious_black_magic_illustrious_noob_more_clip_vit_l14_f16.ckpt", "illustrious_black_magic_illustrious_noob_more_open_clip_vit_bigg14_f16.ckpt", "illustrious_gehenna_illustrious_checkpoint_f16.ckpt", "illustrious_gehenna_illustrious_checkpoint_clip_vit_l14_f16.ckpt", "illustrious_gehenna_illustrious_checkpoint_open_clip_vit_bigg14_f16.ckpt", "illustrious_realism_by_klaabu_f16.ckpt", "illustrious_realism_by_klaabu_clip_vit_l14_f16.ckpt", "illustrious_realism_by_klaabu_open_clip_vit_bigg14_f16.ckpt", "illustrious_xl_f16.ckpt", "illustrious_xl_clip_vit_l14_f16.ckpt", "illustrious_xl_open_clip_vit_bigg14_f16.ckpt", "illustrious_xl_personal_merge_noob_v_pred0.5_test_merge_updated_f16.ckpt", "illustrious_xl_personal_merge_noob_v_pred0.5_test_merge_updated_clip_vit_l14_f16.ckpt", "illustrious_xl_personal_merge_noob_v_pred0.5_test_merge_updated_open_clip_vit_bigg14_f16.ckpt", "inbetweij___no.04_f16.ckpt", "inbetweij___no.04_q6p_q8p.ckpt", "inbetweij___no.04_clip_vit_l14_f16.ckpt", "inbetweij___no.04_open_clip_vit_bigg14_f16.ckpt", "indigo_void_furry_fused_xl_furry_noobai_noobai_v1.7_1569147_f16.ckpt", "indigo_void_furry_fused_xl_furry_noobai_noobai_v1.7_1569147_clip_vit_l14_f16.ckpt", "indigo_void_furry_fused_xl_furry_noobai_noobai_v1.7_1569147_open_clip_vit_bigg14_f16.ckpt", "indigo_void_furry_fused_xl_furry_noobai_noobai_v1.8_1731573_f16.ckpt", "indigo_void_furry_fused_xl_furry_noobai_noobai_v1.8_1731573_clip_vit_l14_f16.ckpt", "indigo_void_furry_fused_xl_furry_noobai_noobai_v1.8_1731573_open_clip_vit_bigg14_f16.ckpt", "indigo_furry_mix_xl_f16.ckpt", "indigo_furry_mix_xl_clip_vit_l14_f16.ckpt", "indigo_furry_mix_xl_open_clip_vit_bigg14_f16.ckpt", "indigo_void_furry_vpred_furry_noobai_v_pred_f16.ckpt", "indigo_void_furry_vpred_furry_noobai_v_pred_clip_vit_l14_f16.ckpt", "indigo_void_furry_vpred_furry_noobai_v_pred_open_clip_vit_bigg14_f16.ckpt", "1006775_iniversemixsfwnsfw_f1drealguofengfp8v20_q8p.ckpt", "1031531_iniversemixsfwnsfw_f1drealnsfwguofengv2_q8p.ckpt", "973626_iniversemixsfwnsfw_flux1dnsfwfp16v12_q8p.ckpt", "966095_iniversemixsfwnsfw_flux1dnsfwfp8v10_q8p.ckpt", "ionsyx_f16.ckpt", "ionsyx_clip_vit_l14_f16.ckpt", "ionsyx_open_clip_vit_bigg14_f16.ckpt", "886474_isenganmixflux_vb_q8p.ckpt", "796103_jibmixflux_fp16v1_q8p.ckpt", "918242_jibmixflux_fp8v2electric_q8p.ckpt", "1001176_jibmixflux_fp8v4canvasgalore_q8p.ckpt", "1249737_jibmixflux_v72pixelheaven_q8p.ckpt", "1355240_jibmixflux_v78cleartextfocus_q8p.ckpt", "1193229_jibmixflux_v7pixelheavenbeta_q8p.ckpt", "1755367_jibmixflux_v85consisteight_q8p.ckpt", "1389019_jibmixflux_v8accentueightnow_q8p.ckpt", "jib_mix_pony_realistic_f16.ckpt", "jib_mix_pony_realistic_clip_vit_l14_f16.ckpt", "jib_mix_pony_realistic_open_clip_vit_bigg14_f16.ckpt", "jib_mix_realistic_xl_f16.ckpt", "jib_mix_realistic_xl_clip_vit_l14_f16.ckpt", "jib_mix_realistic_xl_open_clip_vit_bigg14_f16.ckpt", "jujumix_f16.ckpt", "jujumix_clip_vit_l14_f16.ckpt", "jujumix_open_clip_vit_bigg14_f16.ckpt", "kageillustrious_illustrious_xl_f16.ckpt", "kageillustrious_illustrious_xl_clip_vit_l14_f16.ckpt", "kageillustrious_illustrious_xl_open_clip_vit_bigg14_f16.ckpt", "kantanmix_xlillustrious_f16.ckpt", "kantanmix_xlillustrious_clip_vit_l14_f16.ckpt", "kantanmix_xlillustrious_open_clip_vit_bigg14_f16.ckpt", "kft_requiem_fur_a_dream_illustrious_semi_real_checkpoint_f16.ckpt", "kft_requiem_fur_a_dream_illustrious_semi_real_checkpoint_clip_vit_l14_f16.ckpt", "kft_requiem_fur_a_dream_illustrious_semi_real_checkpoint_open_clip_vit_bigg14_f16.ckpt", "konanmix_noobai_xl_illustriousxl_f16.ckpt", "konanmix_noobai_xl_illustriousxl_clip_vit_l14_f16.ckpt", "konanmix_noobai_xl_illustriousxl_open_clip_vit_bigg14_f16.ckpt", "koronemix_illustrious_f16.ckpt", "koronemix_illustrious_clip_vit_l14_f16.ckpt", "koronemix_illustrious_open_clip_vit_bigg14_f16.ckpt", "872820_lahmysteriousflux_fluxalpha_q8p.ckpt", "like_reality_pony_by_ethanar_f16.ckpt", "like_reality_pony_by_ethanar_clip_vit_l14_f16.ckpt", "like_reality_pony_by_ethanar_open_clip_vit_bigg14_f16.ckpt", "lox_s_souls_mix_prisma__f16.ckpt", "lox_s_souls_mix_prisma__clip_vit_l14_f16.ckpt", "lox_s_souls_mix_prisma__open_clip_vit_bigg14_f16.ckpt", "lunargrapemix_illustrious_f16.ckpt", "lunargrapemix_illustrious_clip_vit_l14_f16.ckpt", "lunargrapemix_illustrious_open_clip_vit_bigg14_f16.ckpt", "835744_lyhanimeflux_delete_q8p.ckpt", "madly_mix_ver_nightnoob_f16.ckpt", "madly_mix_ver_nightnoob_clip_vit_l14_f16.ckpt", "madly_mix_ver_nightnoob_open_clip_vit_bigg14_f16.ckpt", "1247362_majicflus_v10_q8p.ckpt", "meichidarkmix_reload_f16.ckpt", "meichidarkmix_reload_clip_vit_l14_f16.ckpt", "meichidarkmix_reload_open_clip_vit_bigg14_f16.ckpt", "miruku_f16.ckpt", "miruku_clip_vit_l14_f16.ckpt", "miruku_open_clip_vit_bigg14_f16.ckpt", "mistoon_anime_f16.ckpt", "mistoon_anime_clip_vit_l14_f16.ckpt", "mistoon_anime_open_clip_vit_bigg14_f16.ckpt", "mol_keun_mix_f16.ckpt", "mol_keun_mix_clip_vit_l14_f16.ckpt", "mol_keun_mix_open_clip_vit_bigg14_f16.ckpt", "molcajetemix_noobil_f16.ckpt", "molcajetemix_noobil_clip_vit_l14_f16.ckpt", "molcajetemix_noobil_open_clip_vit_bigg14_f16.ckpt", "905329_moxieflux1ds_flux1d8step_q8p.ckpt", "905879_moxieflux1ds_flux1s8step_q8p.ckpt", "883958_moxieflux1ds_v138step_q8p.ckpt", "986682_moxieflux1ds_v14_q8p.ckpt", "1453489_moxieflux1ds_v16d_q8p.ckpt", "1802008_moxieflux1ds_v17s_q8p.ckpt", "1718411_moxiefusionflux_17d_q8p.ckpt", "876813_moxiefusionflux_v1318step_q8p.ckpt", "874291_moxiefusionflux_v132_q8p.ckpt", "873546_moxiefusionflux_v1328step_q8p.ckpt", "913024_moxiefusionflux_v1338step_q8p.ckpt", "943051_moxiefusionflux_v134_q8p.ckpt", "932231_moxiefusionflux_v1348step_q8p.ckpt", "985269_moxiefusionflux_v135_q8p.ckpt", "1255371_moxiefusionflux_v141d_q8p.ckpt", "1249359_moxiefusionflux_v141s_q8p.ckpt", "1292596_moxiefusionflux_v15s_q8p.ckpt", "1473409_moxiefusionflux_v16s_q8p.ckpt", "1742386_moxiefusionflux_v17s_q8p.ckpt", "1505959_msfluxsfwnsfwv3_v3_q8p.ckpt", "866874_myhumanflux_12train_q8p.ckpt", "885693_myhumanflux_myh11_q8p.ckpt", "989443_myhumanflux_myh13_q8p.ckpt", "991687_myhumanflux_myh13fp8_q8p.ckpt", "1288366_nepotism_xdit_q8p.ckpt", "1326315_nepotism_xidit_q8p.ckpt", "nevolution_sdxl_v2_anim_1733673_f16.ckpt", "nevolution_sdxl_v2_anim_1733673_clip_vit_l14_f16.ckpt", "nevolution_sdxl_v2_anim_1733673_open_clip_vit_bigg14_f16.ckpt", "nevolution_sdxl_v2_base_1645671_f16.ckpt", "nevolution_sdxl_v2_base_1645671_clip_vit_l14_f16.ckpt", "nevolution_sdxl_v2_base_1645671_open_clip_vit_bigg14_f16.ckpt", "noobai_xl_nai_xl_f16.ckpt", "noobai_xl_nai_xl_clip_vit_l14_f16.ckpt", "noobai_xl_nai_xl_open_clip_vit_bigg14_f16.ckpt", "nostramix_f16.ckpt", "nostramix_clip_vit_l14_f16.ckpt", "nostramix_open_clip_vit_bigg14_f16.ckpt", "nova_animal_xl_illustrious_v3.0_1634769_f16.ckpt", "nova_animal_xl_illustrious_v3.0_1634769_clip_vit_l14_f16.ckpt", "nova_animal_xl_illustrious_v3.0_1634769_open_clip_vit_bigg14_f16.ckpt", "nova_animal_xl_v4.0_1028888_f16.ckpt", "nova_animal_xl_v4.0_1028888_clip_vit_l14_f16.ckpt", "nova_animal_xl_v4.0_1028888_open_clip_vit_bigg14_f16.ckpt", "nova_furry_xl_illustrious_v6a_1625975_f16.ckpt", "nova_furry_xl_illustrious_v6a_1625975_clip_vit_l14_f16.ckpt", "nova_furry_xl_illustrious_v6a_1625975_open_clip_vit_bigg14_f16.ckpt", "nova_furry_xl_illustrious_v6b_1626156_f16.ckpt", "nova_furry_xl_illustrious_v6b_1626156_clip_vit_l14_f16.ckpt", "nova_furry_xl_illustrious_v6b_1626156_open_clip_vit_bigg14_f16.ckpt", "nova_furry_xl_illustrious_v7a_1759909_f16.ckpt", "nova_furry_xl_illustrious_v7a_1759909_clip_vit_l14_f16.ckpt", "nova_furry_xl_illustrious_v7a_1759909_open_clip_vit_bigg14_f16.ckpt", "nova_furry_xl_illustrious_v7b_1760102_f16.ckpt", "nova_furry_xl_illustrious_v7b_1760102_clip_vit_l14_f16.ckpt", "nova_furry_xl_illustrious_v7b_1760102_open_clip_vit_bigg14_f16.ckpt", "nova_orange_xl_v7.0_1525944_f16.ckpt", "nova_orange_xl_v7.0_1525944_clip_vit_l14_f16.ckpt", "nova_orange_xl_v7.0_1525944_open_clip_vit_bigg14_f16.ckpt", "nova_orange_xl_v9.0_1701002_f16.ckpt", "nova_orange_xl_v9.0_1701002_clip_vit_l14_f16.ckpt", "nova_orange_xl_v9.0_1701002_open_clip_vit_bigg14_f16.ckpt", "nova_3dcg_xl_f16.ckpt", "nova_3dcg_xl_clip_vit_l14_f16.ckpt", "nova_3dcg_xl_open_clip_vit_bigg14_f16.ckpt", "nova_anime_xl_f16.ckpt", "nova_anime_xl_clip_vit_l14_f16.ckpt", "nova_anime_xl_open_clip_vit_bigg14_f16.ckpt", "nova_anime3d_xl_f16.ckpt", "nova_anime3d_xl_clip_vit_l14_f16.ckpt", "nova_anime3d_xl_open_clip_vit_bigg14_f16.ckpt", "nova_asian_xl_f16.ckpt", "nova_asian_xl_clip_vit_l14_f16.ckpt", "nova_asian_xl_open_clip_vit_bigg14_f16.ckpt", "nova_cross_xl_f16.ckpt", "nova_cross_xl_clip_vit_l14_f16.ckpt", "nova_cross_xl_open_clip_vit_bigg14_f16.ckpt", "nova_flat_xl_f16.ckpt", "nova_flat_xl_clip_vit_l14_f16.ckpt", "nova_flat_xl_open_clip_vit_bigg14_f16.ckpt", "nova_reality_xl_f16.ckpt", "nova_reality_xl_clip_vit_l14_f16.ckpt", "nova_reality_xl_open_clip_vit_bigg14_f16.ckpt", "nova_unreal_xl_f16.ckpt", "nova_unreal_xl_clip_vit_l14_f16.ckpt", "nova_unreal_xl_open_clip_vit_bigg14_f16.ckpt", "one_for_all_pony_fantasy_dpovae_f16.ckpt", "one_for_all_pony_fantasy_dpovae_clip_vit_l14_f16.ckpt", "one_for_all_pony_fantasy_dpovae_open_clip_vit_bigg14_f16.ckpt", "oops_all_toons_illustrious_v1.0_f16.ckpt", "oops_all_toons_illustrious_v1.0_clip_vit_l14_f16.ckpt", "oops_all_toons_illustrious_v1.0_open_clip_vit_bigg14_f16.ckpt", "oops_all_vpred_noobai_western_2d_furry_toon_f16.ckpt", "oops_all_vpred_noobai_western_2d_furry_toon_clip_vit_l14_f16.ckpt", "oops_all_vpred_noobai_western_2d_furry_toon_open_clip_vit_bigg14_f16.ckpt", "1308101_originbyn0utis_fluxfp8v1_q8p.ckpt", "photonic_fusion_sdxl_f16.ckpt", "photonic_fusion_sdxl_clip_vit_l14_f16.ckpt", "photonic_fusion_sdxl_open_clip_vit_bigg14_f16.ckpt", "pikon_realism_v2_alt_f16.ckpt", "pikon_realism_v2_alt_q6p_q8p.ckpt", "pikon_realism_v2_alt_clip_vit_l14_f16.ckpt", "pikon_realism_v2_alt_open_clip_vit_bigg14_f16.ckpt", "826571_pixelwave_flux1dev02_q8p.ckpt", "992642_pixelwave_flux1dev03_q8p.ckpt", "1002647_pixelwave_flux1schnell03_q8p.ckpt", "plant_milk_model_suite_flax_1331188_f16.ckpt", "plant_milk_model_suite_flax_1331188_clip_vit_l14_f16.ckpt", "plant_milk_model_suite_flax_1331188_open_clip_vit_bigg14_f16.ckpt", "plant_milk_model_suite_hemp_ii_1714314_f16.ckpt", "plant_milk_model_suite_hemp_ii_1714314_clip_vit_l14_f16.ckpt", "plant_milk_model_suite_hemp_ii_1714314_open_clip_vit_bigg14_f16.ckpt", "pony_realism_v2.1_534642_f16.ckpt", "pony_realism_v2.1_534642_clip_vit_l14_f16.ckpt", "pony_realism_v2.1_534642_open_clip_vit_bigg14_f16.ckpt", "pony_realism_v2.2_914390_f16.ckpt", "pony_realism_v2.2_914390_clip_vit_l14_f16.ckpt", "pony_realism_v2.2_914390_open_clip_vit_bigg14_f16.ckpt", "praeclarus_illustriousxl_f16.ckpt", "praeclarus_illustriousxl_clip_vit_l14_f16.ckpt", "praeclarus_illustriousxl_open_clip_vit_bigg14_f16.ckpt", "prefect_illustrious_xl_v1.0_1379960_f16.ckpt", "prefect_illustrious_xl_v1.0_1379960_clip_vit_l14_f16.ckpt", "prefect_illustrious_xl_v1.0_1379960_open_clip_vit_bigg14_f16.ckpt", "prefect_illustrious_xl_v1.5_1731647_f16.ckpt", "prefect_illustrious_xl_v1.5_1731647_clip_vit_l14_f16.ckpt", "prefect_illustrious_xl_v1.5_1731647_open_clip_vit_bigg14_f16.ckpt", "prefect_pony_xl_f16.ckpt", "prefect_pony_xl_clip_vit_l14_f16.ckpt", "prefect_pony_xl_open_clip_vit_bigg14_f16.ckpt", "806846_projectgaiaflux1d_v10unet_q8p.ckpt", "1451754_project0_real1smfp16_q8p.ckpt", "1591370_project0_real1smv2fp16_q8p.ckpt", "1596255_project0_real1smv2fp8_q8p.ckpt", "1875661_project0_real1smv3fp16_q8p.ckpt", "1878051_project0_real1smv3fp8aio_q8p.ckpt", "1181877_project0_v10fp8unetonly_q8p.ckpt", "1249092_project0_v20fp16_q8p.ckpt", "1249496_project0_v20fp8_q8p.ckpt", "1320268_project0_v30artfp8_q8p.ckpt", "793143_ratatoskranimalcreature_v29_q8p.ckpt", "835047_ratatoskranimalcreature_v40fp8_q8p.ckpt", "873136_ratatoskranimalcreature_v41_q8p.ckpt", "1024165_ratatoskranimalcreature_v594fp8dev1hybrid_q8p.ckpt", "1637227_ratatoskranimalcreature_v667fp16_q8p.ckpt", "1637484_ratatoskranimalcreature_v667fp8_q8p.ckpt", "ratatoskr_animal__creature_and_furry__f16.ckpt", "ratatoskr_animal__creature_and_furry__clip_vit_l14_f16.ckpt", "ratatoskr_animal__creature_and_furry__open_clip_vit_bigg14_f16.ckpt", "1186008_rayflux_v10_q8p.ckpt", "1785042_rayflux_v30aio_q8p.ckpt", "1703341_realdream_flux1v1_q8p.ckpt", "realcartoon_xl_f16.ckpt", "realcartoon_xl_clip_vit_l14_f16.ckpt", "realcartoon_xl_open_clip_vit_bigg14_f16.ckpt", "881836_realflux10b_10bcompactschnell_q8p.ckpt", "882554_realflux10b_10btransformer_q8p.ckpt", "915279_realflux10b_10btransformerdev_q8p.ckpt", "realism_by_stable_yogi_pony_v3_vae_992946_f16.ckpt", "realism_by_stable_yogi_pony_v3_vae_992946_clip_vit_l14_f16.ckpt", "realism_by_stable_yogi_pony_v3_vae_992946_open_clip_vit_bigg14_f16.ckpt", "realism_by_stable_yogi_v4.0_fp16_1422871_f16.ckpt", "realism_by_stable_yogi_v4.0_fp16_1422871_clip_vit_l14_f16.ckpt", "realism_by_stable_yogi_v4.0_fp16_1422871_open_clip_vit_bigg14_f16.ckpt", "realism_sdxl_by_stable_yogi_f16.ckpt", "realism_sdxl_by_stable_yogi_clip_vit_l14_f16.ckpt", "realism_sdxl_by_stable_yogi_open_clip_vit_bigg14_f16.ckpt", "realistic_blend_xl_f16.ckpt", "realistic_blend_xl_clip_vit_l14_f16.ckpt", "realistic_blend_xl_open_clip_vit_bigg14_f16.ckpt", "1138590_redbluefantasy_fluxv10_q8p.ckpt", "1445047_redcraftcadsupdatedjun1_f1fillnsfw_q8p.ckpt", "1315432_redcraftcadsupdatedjun1_newreveal_q8p.ckpt", "1093373_redcraftcadsupdatedjun1_rasch1forge_q8p.ckpt", "1115605_redcraftcadsupdatedjun1_rasch2_q8p.ckpt", "1344905_redcraftcadsupdatedjun1_rasch3rushreveal_q8p.ckpt", "1550408_redcraftcadsupdatedjun1_realreveal5_q8p.ckpt", "1745151_redcraftcadsupdatedjun1_redediticedit11_q8p.ckpt", "1849802_redcraftcadsupdatedjun1_redomniflux1dreamo_q8p.ckpt", "1087807_redcraftcadsupdatedjun1_revealnsfw_q8p.ckpt", "1171942_redcraftcadsupdatedjun1_revealultrav35_q8p.ckpt", "1576605_redcraftcadsupdatedjun1_reveal5sfwultra_q8p.ckpt", "1201074_redcraftcadsupdatedjun1_turborevealhotfix21_q8p.ckpt", "redcraft___cads_updated_may4_commercial___advertising_design_system_f16.ckpt", "redcraft___cads_updated_may4_commercial___advertising_design_system_clip_vit_l14_f16.ckpt", "redcraft___cads_updated_may4_commercial___advertising_design_system_open_clip_vit_bigg14_f16.ckpt", "richyrichmixixl_f16.ckpt", "richyrichmixixl_clip_vit_l14_f16.ckpt", "richyrichmixixl_open_clip_vit_bigg14_f16.ckpt", "rillusm___realistic_il_f16.ckpt", "rillusm___realistic_il_clip_vit_l14_f16.ckpt", "rillusm___realistic_il_open_clip_vit_bigg14_f16.ckpt", "878315_sdvn11ghibliflux_fp8hyper_q8p.ckpt", "silvermoonmix_illustrious_evolved_f16.ckpt", "silvermoonmix_illustrious_evolved_clip_vit_l14_f16.ckpt", "silvermoonmix_illustrious_evolved_open_clip_vit_bigg14_f16.ckpt", "singlo_illustrious_f16.ckpt", "singlo_illustrious_clip_vit_l14_f16.ckpt", "singlo_illustrious_open_clip_vit_bigg14_f16.ckpt", "skibidimix_f16.ckpt", "skibidimix_clip_vit_l14_f16.ckpt", "skibidimix_open_clip_vit_bigg14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_illustrious_v.2_1401686_f16.ckpt", "smooth_mix_noobai_illustrious_pony_illustrious_v.2_1401686_clip_vit_l14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_illustrious_v.2_1401686_open_clip_vit_bigg14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_illustrious_v.3_1470541_f16.ckpt", "smooth_mix_noobai_illustrious_pony_illustrious_v.3_1470541_clip_vit_l14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_illustrious_v.3_1470541_open_clip_vit_bigg14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_noobai_v2.0_1629718_f16.ckpt", "smooth_mix_noobai_illustrious_pony_noobai_v2.0_1629718_clip_vit_l14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_noobai_v2.0_1629718_open_clip_vit_bigg14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_pony_v.3_997031_f16.ckpt", "smooth_mix_noobai_illustrious_pony_pony_v.3_997031_clip_vit_l14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_pony_v.3_997031_open_clip_vit_bigg14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_realism_1675843_f16.ckpt", "smooth_mix_noobai_illustrious_pony_realism_1675843_clip_vit_l14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_realism_1675843_open_clip_vit_bigg14_f16.ckpt", "snowpony_f16.ckpt", "snowpony_clip_vit_l14_f16.ckpt", "snowpony_open_clip_vit_bigg14_f16.ckpt", "steinillustrious_f16.ckpt", "steinillustrious_clip_vit_l14_f16.ckpt", "steinillustrious_open_clip_vit_bigg14_f16.ckpt", "869391_stoiqonewrealityfluxsd35_f1dalpha_q8p.ckpt", "979329_stoiqonewrealityfluxsd35_f1dalphatwo_q8p.ckpt", "897489_stoiqoafroditefluxxl_f1dalpha_q8p.ckpt", "742904_thearamintaexperiment_flux1a1_q8p.ckpt", "throwing_pasta_mix_spaghetti_f16.ckpt", "throwing_pasta_mix_spaghetti_clip_vit_l14_f16.ckpt", "throwing_pasta_mix_spaghetti_open_clip_vit_bigg14_f16.ckpt", "toonify_toonify_illustrious_1495132_f16.ckpt", "toonify_toonify_illustrious_1495132_clip_vit_l14_f16.ckpt", "toonify_toonify_illustrious_1495132_open_clip_vit_bigg14_f16.ckpt", "toonify_toonify_ponydiffusionxl_410539_f16.ckpt", "toonify_toonify_ponydiffusionxl_410539_clip_vit_l14_f16.ckpt", "toonify_toonify_ponydiffusionxl_410539_open_clip_vit_bigg14_f16.ckpt", "tt_animerge_f16.ckpt", "tt_animerge_clip_vit_l14_f16.ckpt", "ultra_realistic_by_stable_yogi_pony_f16.ckpt", "ultra_realistic_by_stable_yogi_pony_clip_vit_l14_f16.ckpt", "ultra_realistic_by_stable_yogi_pony_open_clip_vit_bigg14_f16.ckpt", "1454015_ultrarealfinetune_v1_q8p.ckpt", "1095703_ultrarealfinetune_v10_q8p.ckpt", "1164498_ultrarealfinetune_v20_q8p.ckpt", "1413133_ultrarealfinetune_v4_q8p.ckpt", "umbroxponyxl_f16.ckpt", "umbroxponyxl_clip_vit_l14_f16.ckpt", "umbroxponyxl_open_clip_vit_bigg14_f16.ckpt", "uncanny_valley_f16.ckpt", "uncanny_valley_clip_vit_l14_f16.ckpt", "uncanny_valley_open_clip_vit_bigg14_f16.ckpt", "untitled_pony_f16.ckpt", "untitled_pony_clip_vit_l14_f16.ckpt", "untitled_pony_open_clip_vit_bigg14_f16.ckpt", "988886_verusvision10b_10btransformer_q8p.ckpt", "virtual_diffusion_pony_xl_2025_f16.ckpt", "virtual_diffusion_pony_xl_2025_clip_vit_l14_f16.ckpt", "virtual_diffusion_pony_xl_2025_open_clip_vit_bigg14_f16.ckpt", "vixon_s_dream_weave_f16.ckpt", "vixons_dream_weave_f16.ckpt", "vixon_s_dream_weave_clip_vit_l14_f16.ckpt", "vixon_s_dream_weave_open_clip_vit_bigg14_f16.ckpt", "wai_shuffle_noob_f16.ckpt", "wai_shuffle_noob_clip_vit_l14_f16.ckpt", "wai_shuffle_noob_open_clip_vit_bigg14_f16.ckpt", "862533_whiteflux1_v10_q8p.ckpt", "791130_xehentaianimeflux_03_q8p.ckpt", "807911_xehentaianimeflux_04_q8p.ckpt", "951641_xueronecyantencolor_fluxv10_q8p.ckpt", "zavychromaxl_f16.ckpt", "zavychromaxl_clip_vit_l14_f16.ckpt", "zavychromaxl_open_clip_vit_bigg14_f16.ckpt", "zep9_f16.ckpt", "zep9_clip_vit_l14_f16.ckpt", "zep9_open_clip_vit_bigg14_f16.ckpt"], models: [{ id: "fasth3-omni", rubric: "community", name: "FastH3 Omni", family: "minimax_h3", since: "2026-10-22", flavor: ["ref2va"], modifier: "ref2va", files: [[0, 10], [1, 7], [2, 5]], requires: [3, 4], modes: ["text2video", "image2video"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 512, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: true, decoding_tile_width: 256, decoding_tile_height: 256, decoding_tile_overlap: 64, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, resolution_dependent_shift: false, shift: 12, shift_for_audio: 3, preserve_original_after_inpaint: true, width: 832, steps: 8, num_frames: 124, fps: 24, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, compression_artifacts: "disabled" } } }, { id: "moss_image_sft", rubric: "official", name: "MOSS Image SFT", family: "moss_image", since: "2026-10-20", files: [[5, 10], [6, 7], [7, 5]], requires: [8, 9], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 3, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3, resolution_dependent_shift: false }, negative_prompt: "nsfw, worst quality, bad anatomy, watermark, jpeg artifact" } }, { id: "moss_image_base", rubric: "official", name: "MOSS Image Base", family: "moss_image", since: "2026-10-20", variant: "base", files: [[10, 10], [11, 7], [12, 5]], requires: [8, 9], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 3, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3, resolution_dependent_shift: false }, negative_prompt: "nsfw, worst quality, bad anatomy, watermark, jpeg artifact" } }, { id: "flux-3-klein", rubric: "community", name: "FLUX.3 [klein] 5.6B", family: "flux3_5b", since: "2026-10-20", modifier: "kontext", files: [[13, 10], [14, 7], [15, 5]], requires: [8, 16], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 16, preserve_original_after_inpaint: true, steps: 16, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3, resolution_dependent_shift: false } } }, { id: "flux-3-klein-base", rubric: "community", name: "FLUX.3 [klein] 5.6B Base", family: "flux3_5b", since: "2026-10-20", variant: "base", modifier: "kontext", files: [[17, 10], [18, 7], [19, 5]], requires: [8, 16], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 16, preserve_original_after_inpaint: true, steps: 50, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3, resolution_dependent_shift: false } } }, { id: "flux-3-klein-exact", rubric: "community", name: "FLUX.3 [klein] 5.6B (Exact)", family: "flux3_5b", since: "2026-10-20", modifier: "kontext", files: [[20, 11]], requires: [8, 16], modes: ["text2image", "edit"], recommended: { source: "note", params: { steps: 16, guidance_scale: 1, shift: 16 } } }, { id: "flux-3-klein-base-exact", rubric: "community", name: "FLUX.3 [klein] 5.6B Base (Exact)", family: "flux3_5b", since: "2026-10-20", variant: "base", modifier: "kontext", files: [[21, 11]], requires: [8, 16], modes: ["text2image", "edit"], recommended: { source: "note", params: { steps: 50, guidance_scale: 4, shift: 16 } } }, { id: "qwen-image-2.1-turbo", rubric: "community", name: "Qwen Image 2.1 Turbo", family: "qwen_image_2.1", since: "2026-10-09", variant: "turbo", modifier: "kontext", files: [[22, 10], [23, 7], [24, 5], [25, 4]], requires: [26, 27], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 6.5, preserve_original_after_inpaint: true, steps: 8, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3, resolution_dependent_shift: false } } }, { id: "qwen-image-2.1-turbo-exact", rubric: "community", name: "Qwen Image 2.1 Turbo (Exact)", family: "qwen_image_2.1", since: "2026-10-09", variant: "turbo", modifier: "kontext", files: [[28, 11]], requires: [29, 27], modes: ["text2image", "edit"], recommended: { source: "note", params: { guidance_scale: 1, shift: 6.5 } } }, { id: "qwen-image-2.1-exact", rubric: "community", name: "Qwen Image 2.1 (Exact)", family: "qwen_image_2.1", since: "2026-09-22", modifier: "kontext", files: [[30, 11]], requires: [29, 27], modes: ["text2image", "edit"], recommended: { source: "note", params: { guidance_scale: 1, shift: 1 } } }, { id: "qwen-image-2.1", rubric: "community", name: "Qwen Image 2.1", family: "qwen_image_2.1", since: "2026-09-21", modifier: "kontext", files: [[31, 10], [32, 7], [33, 5], [34, 4]], requires: [26, 27], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 1, preserve_original_after_inpaint: true, steps: 40, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3, resolution_dependent_shift: true } } }, { id: "minimax-h3-fl2va", rubric: "community", name: "MiniMax H3", family: "minimax_h3", since: "2026-09-09", flavor: ["fl2va"], modifier: "fl2va", files: [[35, 10], [36, 7], [37, 5], [38, 4]], requires: [3, 4], modes: ["text2video", "image2video"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 512, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: true, decoding_tile_width: 256, decoding_tile_height: 256, decoding_tile_overlap: 64, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, resolution_dependent_shift: false, shift: 12, shift_for_audio: 3, preserve_original_after_inpaint: true, width: 832, steps: 50, num_frames: 124, fps: 24, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, compression_artifacts: "disabled" } } }, { id: "minimax-h3-ref2va", rubric: "community", name: "MiniMax H3 [ref2va]", family: "minimax_h3", since: "2026-09-09", flavor: ["ref2va"], modifier: "ref2va", files: [[39, 10], [40, 7], [41, 5], [42, 4]], requires: [3, 4], modes: ["text2video", "image2video"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 512, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: true, decoding_tile_width: 256, decoding_tile_height: 256, decoding_tile_overlap: 64, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, resolution_dependent_shift: false, shift: 12, shift_for_audio: 3, preserve_original_after_inpaint: true, width: 832, steps: 50, num_frames: 124, fps: 24, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, compression_artifacts: "disabled" } } }, { id: "anima-aesthetic-1.1", rubric: "community", name: "Anima Aesthetic 1.1", family: "cosmos2.5_2b", since: "2026-07-16", files: [[43, 11], [44, 10], [45, 5]], requires: [46, 47], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 4, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: true, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, steps: 30, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: "worst quality, low quality, score_1, score_2, score_3, artist name" } }, { id: "anima-turbo-1.0", rubric: "community", name: "Anima Turbo 1.0", family: "cosmos2.5_2b", since: "2026-07-16", variant: "turbo", files: [[48, 11], [49, 10], [50, 5]], requires: [46, 47], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 1, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: true, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, steps: 8, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: "worst quality, low quality, score_1, score_2, score_3, artist name" } }, { id: "anima-base-1.0", rubric: "community", name: "Anima Base 1.0", family: "cosmos2.5_2b", since: "2026-07-16", variant: "base", files: [[51, 11], [52, 10], [53, 5]], requires: [46, 47], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 4, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: true, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, steps: 30, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: "worst quality, low quality, score_1, score_2, score_3, artist name" } }, { id: "krea-2-turbo", rubric: "community", name: "Krea 2 Turbo", family: "krea_2", since: "2026-07-13", variant: "turbo", files: [[54, 10], [55, 9], [56, 7], [57, 5], [58, 4]], requires: [59, 47], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 3, resolution_dependent_shift: false, preserve_original_after_inpaint: true, steps: 8, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "ideogram-4", rubric: "community", name: "Ideogram 4", family: "ideogram_4", since: "2026-07-13", files: [[60, 10], [61, 9], [62, 5], [63, 4]], requires: [8, 64], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 7, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 1, resolution_dependent_shift: false, zero_negative_prompt: true, expand_prompt_to_json: true, preserve_original_after_inpaint: true, steps: 48, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "ideogram-4-instant", rubric: "community", name: "Ideogram 4 Instant", family: "ideogram_4", since: "2026-07-13", variant: "turbo", files: [[65, 10], [66, 9], [67, 5], [68, 4]], requires: [8, 64], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 1, resolution_dependent_shift: false, zero_negative_prompt: true, expand_prompt_to_json: true, preserve_original_after_inpaint: true, steps: 8, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "ideogram-4-fast", rubric: "community", name: "Ideogram 4 Fast", family: "ideogram_4", since: "2026-07-13", variant: "turbo", files: [[69, 10], [70, 9], [71, 5], [72, 4]], requires: [8, 64], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 1, resolution_dependent_shift: false, zero_negative_prompt: true, expand_prompt_to_json: true, preserve_original_after_inpaint: true, steps: 20, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "krea-2-raw", rubric: "community", name: "Krea 2 Raw", family: "krea_2", since: "2026-07-13", variant: "base", files: [[73, 10], [74, 7], [75, 5], [76, 4]], requires: [59, 47], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 3.5, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, resolution_dependent_shift: true, preserve_original_after_inpaint: true, steps: 52, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "seedvr2_3b", rubric: "official", name: "SeedVR2 3B", family: "seedvr2_3b", since: "2026-04-29", modifier: "inpainting", files: [[77, 10], [78, 5], [79, 4]], requires: [80], modes: ["upscale"] }, { id: "seedvr2_7b", rubric: "official", name: "SeedVR2 7B", family: "seedvr2_7b", since: "2026-04-29", modifier: "inpainting", files: [[81, 10], [82, 5], [83, 4]], requires: [80], modes: ["upscale"] }, { id: "ltx_2.3_22b_distilled_1.1", rubric: "official", name: "LTX-2.3 22B [distilled] 1.1", family: "ltx2.3", since: "2026-04-18", variant: "turbo", modifier: "kontext", files: [[84, 10], [85, 5], [86, 4]], requires: [87, 88], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "ernie_image_turbo", rubric: "official", name: "ERNIE Image Turbo 1.0", family: "ernie_image", since: "2026-04-18", variant: "turbo", files: [[89, 10], [90, 5], [91, 4]], requires: [8, 92], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 4, resolution_dependent_shift: false, preserve_original_after_inpaint: true, steps: 8, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: " " } }, { id: "ernie_image", rubric: "official", name: "ERNIE Image Base 1.0", family: "ernie_image", since: "2026-04-18", files: [[93, 10], [94, 5], [95, 4]], requires: [8, 92], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, resolution_dependent_shift: true, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "ernie-image-turbo-1.0-exact", rubric: "community", name: "ERNIE Image Turbo 1.0 (Exact)", family: "ernie_image", since: "2026-04-17", variant: "turbo", files: [[96, 11]], requires: [8, 97], modes: ["text2image"], recommended: { source: "note", params: { guidance_scale: 1 } } }, { id: "ernie-image-1.0-exact", rubric: "community", name: "ERNIE Image Base 1.0 (Exact)", family: "ernie_image", since: "2026-04-17", files: [[98, 11]], requires: [8, 97], modes: ["text2image"] }, { id: "ltx-2.3-22b-distilled-exact", rubric: "community", name: "LTX-2.3 22B [distilled] (Exact)", family: "ltx2.3", since: "2026-03-17", variant: "turbo", modifier: "kontext", files: [[99, 11]], requires: [100, 88], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "ltx-2.3-22b-dev-exact", rubric: "community", name: "LTX-2.3 22B [dev] (Exact)", family: "ltx2.3", since: "2026-03-17", variant: "dev", modifier: "kontext", files: [[101, 11]], requires: [100, 88], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "flux-2-klein-9b-kv", rubric: "community", name: "FLUX.2 [klein] 9B KV", family: "flux2_9b", since: "2026-03-14", flavor: ["kv"], modifier: "kontext_kv", files: [[102, 10], [103, 5], [104, 4]], requires: [8, 105], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 1, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 3, speed_up_with_guidance_embed: true, steps: 4, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "flux-2-klein-9b-kv-exact", rubric: "community", name: "FLUX.2 [klein] 9B KV (Exact)", family: "flux2_9b", since: "2026-03-14", flavor: ["kv"], modifier: "kontext_kv", files: [[106, 11]], requires: [8, 107], modes: ["text2image", "edit"] }, { id: "ltx_2.3_22b_dev", rubric: "official", name: "LTX-2.3 22B [dev]", family: "ltx2.3", since: "2026-03-11", variant: "dev", modifier: "kontext", files: [[108, 10], [109, 5], [110, 4]], requires: [87, 88], modes: ["text2video", "image2video"], modesUncertain: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 768, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 5, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, width: 1280, steps: 30, num_frames: 121, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: true, tea_cache: false, causal_inference: 0, hires_fix_strength: 0.7, hires_fix_height: 384, hires_fix_width: 640, compression_artifacts_quality: 43.1, compression_artifacts: "disabled" }, negative_prompt: "worst quality, inconsistent motion, blurry, jittery, distorted" } }, { id: "ltx_2.3_22b_distilled", rubric: "official", name: "LTX-2.3 22B [distilled]", family: "ltx2.3", since: "2026-03-10", variant: "turbo", modifier: "kontext", files: [[111, 10], [112, 5], [113, 4]], requires: [87, 88], modes: ["text2video", "image2video"], modesUncertain: true, deprecated: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 768, sampler: "TCDTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, width: 1280, steps: 8, num_frames: 121, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: true, tea_cache: false, causal_inference: 0, hires_fix_strength: 0.7, hires_fix_height: 384, hires_fix_width: 640, compression_artifacts_quality: 43.1, compression_artifacts: "disabled" } } }, { id: "z-image-1.0-exact", rubric: "community", name: "Z Image Base 1.0 (Exact)", family: "z_image", since: "2026-02-12", files: [[114, 11]], requires: [115, 116], modes: ["text2image"] }, { id: "z_image_1.0", rubric: "official", name: "Z Image Base 1.0", family: "z_image", since: "2026-01-28", files: [[117, 10], [118, 5], [119, 4]], requires: [115, 120], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, resolution_dependent_shift: true, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "ltx_2_19b_dev", rubric: "official", name: "LTX-2 19B [dev]", family: "ltx2", since: "2026-01-26", variant: "dev", modifier: "kontext", files: [[121, 5], [122, 4]], requires: [87, 123], modes: ["text2video", "image2video"], modesUncertain: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 768, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 5, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, width: 1280, steps: 30, num_frames: 121, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, compression_artifacts_quality: 43.1, compression_artifacts: "h264" }, negative_prompt: "worst quality, inconsistent motion, blurry, jittery, distorted" } }, { id: "ltx_2_19b_distilled", rubric: "official", name: "LTX-2 19B [distilled]", family: "ltx2", since: "2026-01-21", variant: "turbo", modifier: "kontext", files: [[124, 5], [125, 4]], requires: [87, 123], modes: ["text2video", "image2video"], modesUncertain: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 768, sampler: "TCDTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, width: 1280, steps: 8, num_frames: 121, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, compression_artifacts_quality: 43.1, compression_artifacts: "h264" } } }, { id: "flux_2_klein_4b", rubric: "official", name: "FLUX.2 [klein] 4B", family: "flux2_4b", since: "2026-01-17", modifier: "kontext", files: [[126, 10], [127, 5], [128, 4]], requires: [8, 129], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 1, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 3, speed_up_with_guidance_embed: true, steps: 4, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "flux_2_klein_base_4b", rubric: "official", name: "FLUX.2 [klein] 4B Base", family: "flux2_4b", since: "2026-01-17", variant: "base", modifier: "kontext", files: [[130, 10], [131, 5], [132, 4]], requires: [8, 129], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 4, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: true, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, steps: 30, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "flux-2-klein-base-9b", rubric: "community", name: "FLUX.2 [klein] 9B Base", family: "flux2_9b", since: "2026-01-17", variant: "base", modifier: "kontext", files: [[133, 10], [134, 5], [135, 4]], requires: [8, 105], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 4, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: true, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, steps: 30, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "flux-2-klein-4b-exact", rubric: "community", name: "FLUX.2 [klein] 4B (Exact)", family: "flux2_4b", since: "2026-01-17", modifier: "kontext", files: [[136, 11]], requires: [8, 137], modes: ["text2image", "edit"] }, { id: "flux-2-klein-base-4b-exact", rubric: "community", name: "FLUX.2 [klein] 4B Base (Exact)", family: "flux2_4b", since: "2026-01-17", variant: "base", modifier: "kontext", files: [[138, 11]], requires: [8, 137], modes: ["text2image", "edit"] }, { id: "flux-2-klein-9b-exact", rubric: "community", name: "FLUX.2 [klein] 9B (Exact)", family: "flux2_9b", since: "2026-01-17", modifier: "kontext", files: [[139, 11]], requires: [8, 107], modes: ["text2image", "edit"] }, { id: "flux-2-klein-base-9b-exact", rubric: "community", name: "FLUX.2 [klein] 9B Base (Exact)", family: "flux2_9b", since: "2026-01-17", variant: "base", modifier: "kontext", files: [[140, 11]], requires: [8, 107], modes: ["text2image", "edit"] }, { id: "flux-2-klein-9b", rubric: "community", name: "FLUX.2 [klein] 9B", family: "flux2_9b", since: "2026-01-16", modifier: "kontext", files: [[141, 10], [142, 5], [143, 4]], requires: [8, 105], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 1, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 3, speed_up_with_guidance_embed: true, steps: 4, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "qwen_image_2512", rubric: "official", name: "Qwen Image 2512", family: "qwen_image", since: "2025-12-31", files: [[144, 10], [145, 5], [146, 5], [147, 4]], requires: [148, 47], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 2, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: "\u4F4E\u5206\u8FA8\u7387\uFF0C\u4F4E\u753B\u8D28\uFF0C\u80A2\u4F53\u7578\u5F62\uFF0C\u624B\u6307\u7578\u5F62\uFF0C\u753B\u9762\u8FC7\u9971\u548C\uFF0C\u8721\u50CF\u611F\uFF0C\u4EBA\u8138\u65E0\u7EC6\u8282\uFF0C\u8FC7\u5EA6\u5149\u6ED1\uFF0C\u753B\u9762\u5177\u6709AI\u611F\u3002\u6784\u56FE\u6DF7\u4E71\u3002\u6587\u5B57\u6A21\u7CCA\uFF0C\u626D\u66F2\u3002" } }, { id: "qwen_image_2512_bf16", rubric: "official", name: "Qwen Image 2512 (BF16, 8-bit S)", family: "qwen_image", since: "2025-12-31", files: [[149, 10], [150, 4]], requires: [148, 47], modes: ["text2image"] }, { id: "qwen-image-2512-bf-exact", rubric: "community", name: "Qwen Image 2512 (BF16, Exact)", family: "qwen_image", since: "2025-12-31", files: [[151, 11]], requires: [152, 47], modes: ["text2image"] }, { id: "qwen_image_edit_2511", rubric: "official", name: "Qwen Image Edit 2511", family: "qwen_image", since: "2025-12-23", modifier: "qwenimage_edit_2511", files: [[153, 10], [154, 5], [155, 5], [156, 4]], requires: [148, 157, 47], modes: ["edit"], modesUncertain: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 2, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: " " } }, { id: "qwen_image_edit_2511_bf16", rubric: "official", name: "Qwen Image Edit 2511 (BF16, 8-bit S)", family: "qwen_image", since: "2025-12-23", modifier: "qwenimage_edit_2511", files: [[158, 10], [159, 4]], requires: [148, 157, 47], modes: ["edit"], modesUncertain: true }, { id: "qwen_image_layered_1.0", rubric: "official", name: "Qwen Image Layered 1.0 (BF16)", family: "qwen_image", since: "2025-12-20", modifier: "qwenimage_layered", files: [[160, 5]], requires: [148, 161], modes: ["edit"], modesUncertain: true }, { id: "qwen_image_layered_1.0_bf16", rubric: "official", name: "Qwen Image Layered 1.0 (BF16, 6-bit)", family: "qwen_image", since: "2025-12-20", modifier: "qwenimage_layered", files: [[162, 4]], requires: [148, 161], modes: ["edit"], modesUncertain: true }, { id: "flux-2-dev", rubric: "community", name: "FLUX.2 [dev]", family: "flux2", since: "2025-12-17", variant: "dev", modifier: "kontext", files: [[163, 10], [164, 5], [165, 4]], requires: [8, 166], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_embed: 4.5, guidance_scale: 4.5, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: true, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 1, speed_up_with_guidance_embed: true, steps: 28, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "flux-2-dev-exact", rubric: "community", name: "FLUX.2 [dev] (Exact)", family: "flux2", since: "2025-12-17", variant: "dev", modifier: "kontext", files: [[167, 11]], requires: [8, 168], modes: ["text2image", "edit"] }, { id: "z-image-turbo-1.0-exact", rubric: "community", name: "Z Image Turbo 1.0 (Exact)", family: "z_image", since: "2025-12-05", variant: "turbo", files: [[169, 11]], requires: [115, 116], modes: ["text2image"] }, { id: "z_image_turbo_1.0", rubric: "official", name: "Z Image Turbo 1.0", family: "z_image", since: "2025-12-03", variant: "turbo", files: [[170, 10], [171, 5], [172, 4]], requires: [115, 120], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 3, resolution_dependent_shift: false, preserve_original_after_inpaint: true, steps: 8, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: " " } }, { id: "anisora-v3.2-i2v-wan-2.2-a14b-hne", rubric: "community", name: "AniSora v3.2 I2V Wan 2.2 A14B High Noise Expert", family: "wan_v2.1_14b", since: "2025-11-19", modifier: "inpainting", files: [[173, 5], [174, 4]], requires: [175, 176], modes: ["image2video"] }, { id: "anisora-v3.2-i2v-wan-2.2-a14b-lne", rubric: "community", name: "AniSora v3.2 I2V Wan 2.2 A14B Low Noise Expert", family: "wan_v2.1_14b", since: "2025-11-19", modifier: "inpainting", files: [[177, 5], [178, 4]], requires: [175, 176], modes: ["image2video"] }, { id: "chronoedit-14b", rubric: "community", name: "ChronoEdit 14B", family: "wan_v2.1_14b", since: "2025-11-19", modifier: "inpainting", files: [[179, 5], [180, 4]], requires: [181, 175, 176], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "wan-v2.2-a14b-hne-t2v-lightning-250928", rubric: "community", name: "Wan v2.2 High Noise Expert T2V A14B Lightning 250928", family: "wan_v2.1_14b", since: "2025-10-06", variant: "turbo", files: [[182, 5], [183, 4]], requires: [175, 176], modes: ["text2video"], recommended: { source: "note", params: { steps: 4, guidance_scale: 1 } } }, { id: "qwen-image-edit-2509-bf-exact", rubric: "community", name: "Qwen Image Edit 2509 (BF16, Exact)", family: "qwen_image", since: "2025-10-02", modifier: "qwenimage_edit_plus", files: [[184, 11]], requires: [152, 157, 47], modes: ["edit"], modesUncertain: true }, { id: "qwen-image-edit-2509-exact", rubric: "community", name: "Qwen Image Edit 2509 (Exact)", family: "qwen_image", since: "2025-10-02", modifier: "qwenimage_edit_plus", files: [[185, 11]], requires: [152, 157, 47], modes: ["edit"], modesUncertain: true }, { id: "qwen_image_1.0_bf16", rubric: "official", name: "Qwen Image 1.0 (BF16, 6-bit)", family: "qwen_image", since: "2025-09-30", files: [[186, 4]], requires: [148, 47], modes: ["text2image"] }, { id: "qwen_image_edit_2509_bf16", rubric: "official", name: "Qwen Image Edit 2509 (BF16, 6-bit)", family: "qwen_image", since: "2025-09-30", modifier: "qwenimage_edit_plus", files: [[187, 4]], requires: [148, 157, 47], modes: ["edit"], modesUncertain: true }, { id: "qwen_image_edit_2509", rubric: "official", name: "Qwen Image Edit 2509", family: "qwen_image", since: "2025-09-25", modifier: "qwenimage_edit_plus", files: [[188, 5], [189, 5], [190, 4]], requires: [148, 157, 47], modes: ["edit"], modesUncertain: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 2, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: " " } }, { id: "wan_v2.2_5b_ti2v", rubric: "official", name: "Wan 2.2 TI2V 5B", family: "wan_v2.2_5b", since: "2025-09-23", files: [[191, 11], [192, 5]], requires: [175, 193], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "qwen_image_edit_1.0", rubric: "official", name: "Qwen Image Edit 1.0", family: "qwen_image", since: "2025-08-20", modifier: "kontext", files: [[194, 5], [195, 4]], requires: [148, 157, 47], modes: ["edit"], modesUncertain: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 2, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: " " } }, { id: "qwen-image-1.0-bf-exact", rubric: "community", name: "Qwen Image 1.0 (BF16, Exact)", family: "qwen_image", since: "2025-08-13", files: [[196, 11]], requires: [152, 47], modes: ["text2image"] }, { id: "qwen-image-1.0-exact", rubric: "community", name: "Qwen Image 1.0 (Exact)", family: "qwen_image", since: "2025-08-13", files: [[197, 11]], requires: [152, 47], modes: ["text2image"] }, { id: "chroma-1-hd", rubric: "community", name: "Chroma1 HD", family: "flux1", since: "2025-08-13", files: [[198, 5], [199, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "qwen_image_1.0", rubric: "official", name: "Qwen Image 1.0", family: "qwen_image", since: "2025-08-11", files: [[202, 5], [203, 5], [204, 4]], requires: [148, 47], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 2, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: " " } }, { id: "flux-1-krea-dev", rubric: "community", name: "FLUX.1 Krea [dev]", family: "flux1", since: "2025-07-31", variant: "dev", files: [[205, 5], [206, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "wan_v2.2_a14b_hne_i2v", rubric: "official", name: "Wan 2.2 High Noise Expert I2V A14B", family: "wan_v2.1_14b", since: "2025-07-30", modifier: "inpainting", files: [[207, 10], [208, 5], [209, 4]], requires: [175, 176], modes: ["image2video"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 448, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 3.5, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, width: 832, refiner_model: "wan_v2.2_a14b_lne_i2v_q6p_svd.ckpt", refiner_start: 0.1, steps: 30, num_frames: 81, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: "\u8272\u8C03\u8273\u4E3D\uFF0C\u8FC7\u66DD\uFF0C\u9759\u6001\uFF0C\u7EC6\u8282\u6A21\u7CCA\u4E0D\u6E05\uFF0C\u5B57\u5E55\uFF0C\u98CE\u683C\uFF0C\u4F5C\u54C1\uFF0C\u753B\u4F5C\uFF0C\u753B\u9762\uFF0C\u9759\u6B62\uFF0C\u6574\u4F53\u53D1\u7070\uFF0C\u6700\u5DEE\u8D28\u91CF\uFF0C\u4F4E\u8D28\u91CF\uFF0CJPEG\u538B\u7F29\u6B8B\u7559\uFF0C\u4E11\u964B\u7684\uFF0C\u6B8B\u7F3A\u7684\uFF0C\u591A\u4F59\u7684\u624B\u6307\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u624B\u90E8\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u8138\u90E8\uFF0C\u7578\u5F62\u7684\uFF0C\u6BC1\u5BB9\u7684\uFF0C\u5F62\u6001\u7578\u5F62\u7684\u80A2\u4F53\uFF0C\u624B\u6307\u878D\u5408\uFF0C\u9759\u6B62\u4E0D\u52A8\u7684\u753B\u9762\uFF0C\u6742\u4E71\u7684\u80CC\u666F\uFF0C\u4E09\u6761\u817F\uFF0C\u80CC\u666F\u4EBA\u5F88\u591A\uFF0C\u5012\u7740\u8D70" } }, { id: "wan_v2.2_a14b_lne_i2v", rubric: "official", name: "Wan 2.2 Low Noise Expert I2V A14B", family: "wan_v2.1_14b", since: "2025-07-30", modifier: "inpainting", files: [[210, 10], [211, 5], [212, 4]], requires: [175, 176], modes: ["image2video"] }, { id: "chroma-v48-detail-calibrated", rubric: "community", name: "Chroma v48 Detail Calibrated", family: "flux1", since: "2025-07-30", files: [[213, 5], [214, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "wan_v2.2_a14b_hne_t2v", rubric: "official", name: "Wan 2.2 High Noise Expert T2V A14B", family: "wan_v2.1_14b", since: "2025-07-29", files: [[215, 10], [216, 5], [217, 4]], requires: [175, 176], modes: ["text2video"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 448, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 8, preserve_original_after_inpaint: true, width: 832, refiner_model: "wan_v2.2_a14b_lne_t2v_q6p_svd.ckpt", refiner_start: 0.125, steps: 30, num_frames: 81, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: "\u8272\u8C03\u8273\u4E3D\uFF0C\u8FC7\u66DD\uFF0C\u9759\u6001\uFF0C\u7EC6\u8282\u6A21\u7CCA\u4E0D\u6E05\uFF0C\u5B57\u5E55\uFF0C\u98CE\u683C\uFF0C\u4F5C\u54C1\uFF0C\u753B\u4F5C\uFF0C\u753B\u9762\uFF0C\u9759\u6B62\uFF0C\u6574\u4F53\u53D1\u7070\uFF0C\u6700\u5DEE\u8D28\u91CF\uFF0C\u4F4E\u8D28\u91CF\uFF0CJPEG\u538B\u7F29\u6B8B\u7559\uFF0C\u4E11\u964B\u7684\uFF0C\u6B8B\u7F3A\u7684\uFF0C\u591A\u4F59\u7684\u624B\u6307\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u624B\u90E8\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u8138\u90E8\uFF0C\u7578\u5F62\u7684\uFF0C\u6BC1\u5BB9\u7684\uFF0C\u5F62\u6001\u7578\u5F62\u7684\u80A2\u4F53\uFF0C\u624B\u6307\u878D\u5408\uFF0C\u9759\u6B62\u4E0D\u52A8\u7684\u753B\u9762\uFF0C\u6742\u4E71\u7684\u80CC\u666F\uFF0C\u4E09\u6761\u817F\uFF0C\u80CC\u666F\u4EBA\u5F88\u591A\uFF0C\u5012\u7740\u8D70" } }, { id: "wan_v2.2_a14b_lne_t2v", rubric: "official", name: "Wan 2.2 Low Noise Expert T2V A14B", family: "wan_v2.1_14b", since: "2025-07-29", files: [[218, 10], [219, 5], [220, 4]], requires: [175, 176], modes: ["text2video"] }, { id: "chroma-v47-detail-calibrated", rubric: "community", name: "Chroma v47 Detail Calibrated", family: "flux1", since: "2025-07-25", files: [[221, 5], [222, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "hidream_e1_1", rubric: "official", name: "HiDream E1-1", family: "hidream_i1", since: "2025-07-17", modifier: "editing", files: [[223, 5], [224, 3]], requires: [115, 225, 226, 201], modes: ["edit"], modesUncertain: true }, { id: "hidream-e1-1-exact", rubric: "community", name: "HiDream E1-1 (Exact)", family: "hidream_i1", since: "2025-07-17", modifier: "editing", files: [[227, 11]], requires: [115, 228, 226, 229, 230], modes: ["edit"], modesUncertain: true }, { id: "flux-1-kontext-dev", rubric: "community", name: "FLUX.1 Kontext [dev]", family: "flux1", since: "2025-06-26", variant: "dev", modifier: "kontext", files: [[231, 5], [232, 3]], requires: [200, 115, 201], modes: ["edit"], modesUncertain: true }, { id: "flux-1-kontext-dev-exact", rubric: "community", name: "FLUX.1 Kontext [dev] (Exact)", family: "flux1", since: "2025-06-26", variant: "dev", modifier: "kontext", files: [[233, 11]], requires: [200, 115, 230], modes: ["edit"], modesUncertain: true }, { id: "wan-2.1-14b-t2v-fusionx", rubric: "community", name: "Wan 2.1 14B T2V FusionX", family: "wan_v2.1_14b", since: "2025-06-22", files: [[234, 5], [235, 4]], requires: [175, 176], modes: ["text2video"] }, { id: "wan-2.1-14b-i2v-fusionx", rubric: "community", name: "Wan 2.1 14B I2V FusionX", family: "wan_v2.1_14b", since: "2025-06-22", modifier: "inpainting", files: [[236, 5], [237, 4]], requires: [181, 175, 176], modes: ["image2video"] }, { id: "rayflux-v3.0", rubric: "community", name: "RayFLUX v3.0", family: "flux1", since: "2025-06-19", files: [[238, 5], [239, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "pixelwave-flux-1-schnell-04", rubric: "community", name: "PixelWave FLUX.1 Schnell 04", family: "flux1", since: "2025-05-13", variant: "turbo", files: [[240, 5], [241, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "juggernaut-xl-ragnarok", rubric: "community", name: "Juggernaut XL Ragnarok", family: "sdxl_base_v0.9", since: "2025-05-13", files: [[242, 11], [243, 5]], requires: [244, 245, 246], modes: ["text2image"] }, { id: "hidream_e1_full", rubric: "official", name: "HiDream E1 [full]", family: "hidream_i1", since: "2025-04-28", modifier: "editing", files: [[247, 5], [248, 3]], requires: [115, 225, 226, 201], modes: ["edit"], modesUncertain: true }, { id: "wan-2.1-14b-v1.1-fun-inp", rubric: "community", name: "Wan 2.1 14B v1.1 Fun InP", family: "wan_v2.1_14b", since: "2025-04-26", modifier: "inpainting", files: [[249, 5], [250, 4]], requires: [181, 175, 176], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "wan-2.1-1.3b-v1.1-fun-inp", rubric: "community", name: "Wan 2.1 1.3B v1.1 Fun InP", family: "wan_v2.1_1.3b", since: "2025-04-26", modifier: "inpainting", files: [[251, 11], [252, 5]], requires: [181, 175, 176], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "skyreels-v2-14b-i2v-540p", rubric: "community", name: "SkyReels v2 I2V 14B 540p", family: "wan_v2.1_14b", since: "2025-04-25", modifier: "inpainting", files: [[253, 5], [254, 4]], requires: [181, 175, 176], modes: ["image2video"] }, { id: "skyreels-v2-14b-i2v-720p", rubric: "community", name: "SkyReels v2 I2V 14B 720p", family: "wan_v2.1_14b", since: "2025-04-25", modifier: "inpainting", files: [[255, 5], [256, 4]], requires: [181, 175, 176], modes: ["image2video"] }, { id: "skyreels-v2-14b-t2v-540p", rubric: "community", name: "SkyReels v2 T2V 14B 540p", family: "wan_v2.1_14b", since: "2025-04-25", files: [[181, 11], [257, 5], [258, 4]], requires: [181, 175, 176], modes: ["text2video"] }, { id: "skyreels-v2-14b-t2v-720p", rubric: "community", name: "SkyReels v2 T2V 14B 720p", family: "wan_v2.1_14b", since: "2025-04-25", files: [[181, 11], [259, 5], [260, 4]], requires: [181, 175, 176], modes: ["text2video"] }, { id: "hidream-i1-dev-exact", rubric: "community", name: "HiDream I1 [dev] (Exact)", family: "hidream_i1", since: "2025-04-24", variant: "dev", files: [[261, 11]], requires: [115, 228, 226, 229, 230], modes: ["text2image"] }, { id: "hidream-i1-full-exact", rubric: "community", name: "HiDream I1 [full] (Exact)", family: "hidream_i1", since: "2025-04-24", files: [[262, 11]], requires: [115, 228, 226, 229, 230], modes: ["text2image"] }, { id: "hidream-i1-fast-exact", rubric: "community", name: "HiDream I1 [fast] (Exact)", family: "hidream_i1", since: "2025-04-24", variant: "turbo", files: [[263, 11]], requires: [115, 228, 226, 229, 230], modes: ["text2image"] }, { id: "skyreels-v2-1.3b-i2v-540p", rubric: "community", name: "SkyReels v2 I2V 1.3B 540p", family: "wan_v2.1_1.3b", since: "2025-04-24", modifier: "inpainting", files: [[264, 11], [265, 5]], requires: [181, 175, 176], modes: ["image2video"] }, { id: "hidream_i1_fast", rubric: "official", name: "HiDream I1 [fast]", family: "hidream_i1", since: "2025-04-22", variant: "turbo", files: [[266, 10], [267, 5], [268, 3]], requires: [115, 225, 226, 201], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 1, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "EulerATrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, separate_t5: false, sharpness: 0, shift: 3, steps: 16, strength: 1, tea_cache: false, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024 } } }, { id: "hidream_i1_full", rubric: "official", name: "HiDream I1 [full]", family: "hidream_i1", since: "2025-04-22", files: [[269, 10], [270, 5], [271, 3]], requires: [115, 225, 226, 201], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 5, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "EulerATrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, separate_t5: false, sharpness: 0, shift: 3, steps: 40, strength: 1, tea_cache: false, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.25, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "hidream_i1_dev", rubric: "official", name: "HiDream I1 [dev]", family: "hidream_i1", since: "2025-04-21", variant: "dev", files: [[272, 10], [273, 5], [274, 3]], requires: [115, 225, 226, 201], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 1, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "EulerATrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, separate_t5: false, sharpness: 0, shift: 6, steps: 28, strength: 1, tea_cache: false, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024 } } }, { id: "wan-2.1-14b-fun-inp", rubric: "community", name: "Wan 2.1 14B Fun InP", family: "wan_v2.1_14b", since: "2025-03-28", modifier: "inpainting", files: [[275, 5], [276, 4]], requires: [181, 175, 176], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "wan-2.1-1.3b-fun-inp", rubric: "community", name: "Wan 2.1 1.3B Fun InP", family: "wan_v2.1_1.3b", since: "2025-03-27", modifier: "inpainting", files: [[277, 11], [278, 5]], requires: [181, 175, 176], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "wan_v2.1_14b_i2v_480p", rubric: "official", name: "Wan 2.1 I2V 14B 480p", family: "wan_v2.1_14b", since: "2025-03-20", modifier: "inpainting", files: [[279, 5], [280, 4]], requires: [181, 175, 176], modes: ["image2video"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 448, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 5, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 3, preserve_original_after_inpaint: true, width: 832, steps: 30, num_frames: 81, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0 }, negative_prompt: "\u8272\u8C03\u8273\u4E3D\uFF0C\u8FC7\u66DD\uFF0C\u9759\u6001\uFF0C\u7EC6\u8282\u6A21\u7CCA\u4E0D\u6E05\uFF0C\u5B57\u5E55\uFF0C\u98CE\u683C\uFF0C\u4F5C\u54C1\uFF0C\u753B\u4F5C\uFF0C\u753B\u9762\uFF0C\u9759\u6B62\uFF0C\u6574\u4F53\u53D1\u7070\uFF0C\u6700\u5DEE\u8D28\u91CF\uFF0C\u4F4E\u8D28\u91CF\uFF0CJPEG\u538B\u7F29\u6B8B\u7559\uFF0C\u4E11\u964B\u7684\uFF0C\u6B8B\u7F3A\u7684\uFF0C\u591A\u4F59\u7684\u624B\u6307\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u624B\u90E8\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u8138\u90E8\uFF0C\u7578\u5F62\u7684\uFF0C\u6BC1\u5BB9\u7684\uFF0C\u5F62\u6001\u7578\u5F62\u7684\u80A2\u4F53\uFF0C\u624B\u6307\u878D\u5408\uFF0C\u9759\u6B62\u4E0D\u52A8\u7684\u753B\u9762\uFF0C\u6742\u4E71\u7684\u80CC\u666F\uFF0C\u4E09\u6761\u817F\uFF0C\u80CC\u666F\u4EBA\u5F88\u591A\uFF0C\u5012\u7740\u8D70" } }, { id: "wan_v2.1_14b_i2v_720p", rubric: "official", name: "Wan 2.1 I2V 14B 720p", family: "wan_v2.1_14b", since: "2025-03-20", modifier: "inpainting", files: [[281, 5], [282, 4]], requires: [181, 175, 176], modes: ["image2video"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 768, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 5, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, width: 1280, steps: 30, num_frames: 81, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0 }, negative_prompt: "\u8272\u8C03\u8273\u4E3D\uFF0C\u8FC7\u66DD\uFF0C\u9759\u6001\uFF0C\u7EC6\u8282\u6A21\u7CCA\u4E0D\u6E05\uFF0C\u5B57\u5E55\uFF0C\u98CE\u683C\uFF0C\u4F5C\u54C1\uFF0C\u753B\u4F5C\uFF0C\u753B\u9762\uFF0C\u9759\u6B62\uFF0C\u6574\u4F53\u53D1\u7070\uFF0C\u6700\u5DEE\u8D28\u91CF\uFF0C\u4F4E\u8D28\u91CF\uFF0CJPEG\u538B\u7F29\u6B8B\u7559\uFF0C\u4E11\u964B\u7684\uFF0C\u6B8B\u7F3A\u7684\uFF0C\u591A\u4F59\u7684\u624B\u6307\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u624B\u90E8\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u8138\u90E8\uFF0C\u7578\u5F62\u7684\uFF0C\u6BC1\u5BB9\u7684\uFF0C\u5F62\u6001\u7578\u5F62\u7684\u80A2\u4F53\uFF0C\u624B\u6307\u878D\u5408\uFF0C\u9759\u6B62\u4E0D\u52A8\u7684\u753B\u9762\uFF0C\u6742\u4E71\u7684\u80CC\u666F\uFF0C\u4E09\u6761\u817F\uFF0C\u80CC\u666F\u4EBA\u5F88\u591A\uFF0C\u5012\u7740\u8D70" } }, { id: "wan_v2.1_14b_720p", rubric: "official", name: "Wan 2.1 T2V 14B", family: "wan_v2.1_14b", since: "2025-03-12", files: [[283, 5], [284, 4], [285, 3]], requires: [175, 176], modes: ["text2video", "image2video"], modesUncertain: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 448, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 5, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, width: 832, steps: 30, num_frames: 81, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: "\u8272\u8C03\u8273\u4E3D\uFF0C\u8FC7\u66DD\uFF0C\u9759\u6001\uFF0C\u7EC6\u8282\u6A21\u7CCA\u4E0D\u6E05\uFF0C\u5B57\u5E55\uFF0C\u98CE\u683C\uFF0C\u4F5C\u54C1\uFF0C\u753B\u4F5C\uFF0C\u753B\u9762\uFF0C\u9759\u6B62\uFF0C\u6574\u4F53\u53D1\u7070\uFF0C\u6700\u5DEE\u8D28\u91CF\uFF0C\u4F4E\u8D28\u91CF\uFF0CJPEG\u538B\u7F29\u6B8B\u7559\uFF0C\u4E11\u964B\u7684\uFF0C\u6B8B\u7F3A\u7684\uFF0C\u591A\u4F59\u7684\u624B\u6307\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u624B\u90E8\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u8138\u90E8\uFF0C\u7578\u5F62\u7684\uFF0C\u6BC1\u5BB9\u7684\uFF0C\u5F62\u6001\u7578\u5F62\u7684\u80A2\u4F53\uFF0C\u624B\u6307\u878D\u5408\uFF0C\u9759\u6B62\u4E0D\u52A8\u7684\u753B\u9762\uFF0C\u6742\u4E71\u7684\u80CC\u666F\uFF0C\u4E09\u6761\u817F\uFF0C\u80CC\u666F\u4EBA\u5F88\u591A\uFF0C\u5012\u7740\u8D70" } }, { id: "wan_v2.1_1.3b_480p", rubric: "official", name: "Wan 2.1 T2V 1.3B", family: "wan_v2.1_1.3b", since: "2025-03-11", files: [[286, 11], [287, 5]], requires: [175, 176], modes: ["text2video", "image2video"], modesUncertain: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 448, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 5, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, width: 832, steps: 30, num_frames: 81, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.15, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: "\u8272\u8C03\u8273\u4E3D\uFF0C\u8FC7\u66DD\uFF0C\u9759\u6001\uFF0C\u7EC6\u8282\u6A21\u7CCA\u4E0D\u6E05\uFF0C\u5B57\u5E55\uFF0C\u98CE\u683C\uFF0C\u4F5C\u54C1\uFF0C\u753B\u4F5C\uFF0C\u753B\u9762\uFF0C\u9759\u6B62\uFF0C\u6574\u4F53\u53D1\u7070\uFF0C\u6700\u5DEE\u8D28\u91CF\uFF0C\u4F4E\u8D28\u91CF\uFF0CJPEG\u538B\u7F29\u6B8B\u7559\uFF0C\u4E11\u964B\u7684\uFF0C\u6B8B\u7F3A\u7684\uFF0C\u591A\u4F59\u7684\u624B\u6307\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u624B\u90E8\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u8138\u90E8\uFF0C\u7578\u5F62\u7684\uFF0C\u6BC1\u5BB9\u7684\uFF0C\u5F62\u6001\u7578\u5F62\u7684\u80A2\u4F53\uFF0C\u624B\u6307\u878D\u5408\uFF0C\u9759\u6B62\u4E0D\u52A8\u7684\u753B\u9762\uFF0C\u6742\u4E71\u7684\u80CC\u666F\uFF0C\u4E09\u6761\u817F\uFF0C\u80CC\u666F\u4EBA\u5F88\u591A\uFF0C\u5012\u7740\u8D70" } }, { id: "skyreels-v1-hunyuan-t2v-544p", rubric: "community", name: "SkyReels v1 Hunyuan T2V 544p", family: "hunyuan_video", since: "2025-02-22", files: [[288, 5], [289, 3]], requires: [200, 290, 291], modes: ["text2video"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_embed: 1, guidance_scale: 6, height: 512, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 7, speed_up_with_guidance_embed: false, steps: 30, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 960, num_frames: 97 }, negative_prompt: "Aerial view, aerial view, overexposed, low quality, deformation, a poor composition, bad hands, bad teeth, bad eyes, bad limbs, distortion" } }, { id: "skyreels-v1-hunyuan-i2v-544p", rubric: "community", name: "SkyReels v1 Hunyuan I2V 544p", family: "hunyuan_video", since: "2025-02-22", modifier: "inpainting", files: [[292, 5], [293, 3]], requires: [200, 290, 291], modes: ["image2video"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_embed: 1, guidance_scale: 6, height: 960, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 7, speed_up_with_guidance_embed: false, steps: 30, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 512, num_frames: 97 }, negative_prompt: "Aerial view, aerial view, overexposed, low quality, deformation, a poor composition, bad hands, bad teeth, bad eyes, bad limbs, distortion" } }, { id: "devmode-v0.3-turbo", rubric: "community", name: "devMODE v0.3 Turbo", family: "flux1", since: "2025-02-12", variant: "turbo", files: [[294, 5], [295, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "shuttle-v3.1-aesthetic", rubric: "community", name: "Shuttle v3.1 Aesthetic", family: "flux1", since: "2025-02-11", files: [[296, 5], [297, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "shuttle-jaguar", rubric: "community", name: "Shuttle Jaguar", family: "flux1", since: "2025-02-11", files: [[298, 5], [299, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "schnellmode-v3.3", rubric: "community", name: "schnellMODE v3.3", family: "flux1", since: "2025-02-11", files: [[300, 5], [301, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "artsy-vibe-v1", rubric: "community", name: "Artsy Vibe v1", family: "flux1", since: "2025-02-11", files: [[302, 5], [303, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "hunyuan-video-t2v-720p", rubric: "community", name: "Hunyuan Video T2V 720p", family: "hunyuan_video", since: "2025-01-30", files: [[304, 5], [305, 3]], requires: [200, 290, 291], modes: ["text2video"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_embed: 6, guidance_scale: 6, height: 512, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 7, speed_up_with_guidance_embed: true, steps: 30, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 960, num_frames: 129, tea_cache_threshold: 0.15, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "flux-1-canny-dev", rubric: "community", name: "FLUX.1 Canny [dev]", family: "flux1", since: "2024-11-22", variant: "dev", modifier: "canny", files: [[306, 5], [307, 3]], requires: [200, 115, 201], modes: ["control-model"] }, { id: "flux-1-dev-de-distill", rubric: "community", name: "FLUX.1 [dev] De-distill", family: "flux1", since: "2024-11-22", variant: "dev", files: [[308, 5], [309, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "flux-1-fill-dev", rubric: "community", name: "FLUX.1 Fill [dev]", family: "flux1", since: "2024-11-21", variant: "dev", modifier: "inpainting", files: [[310, 5], [311, 3]], requires: [200, 115, 201], modes: ["inpaint-model"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_embed: 50, guidance_scale: 50, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: true, sampler: "EulerATrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 1, speed_up_with_guidance_embed: true, steps: 28, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024 } } }, { id: "flux-1-depth-dev", rubric: "community", name: "FLUX.1 Depth [dev]", family: "flux1", since: "2024-11-21", variant: "dev", modifier: "depth", files: [[312, 5], [313, 3]], requires: [200, 115, 201], modes: ["control-model"] }, { id: "sd3-medium-3.5", rubric: "community", name: "SD3 Medium 3.5", family: "sd3", since: "2024-11-10", files: [[314, 11], [315, 5]], requires: [200, 316, 317, 201], modes: ["text2image"] }, { id: "sd3-large-turbo-3.5", rubric: "community", name: "SD3 Large Turbo 3.5", family: "sd3_large", since: "2024-10-22", variant: "turbo", files: [[318, 5], [319, 4]], requires: [200, 316, 317, 201], modes: ["text2image"] }, { id: "sd3-large-3.5", rubric: "community", name: "SD3 Large 3.5", family: "sd3_large", since: "2024-10-22", files: [[320, 5], [321, 4]], requires: [200, 316, 317, 201], modes: ["text2image"] }, { id: "sd3-large-3.5-exact", rubric: "community", name: "SD3 Large 3.5 (Exact)", family: "sd3_large", since: "2024-10-22", files: [[322, 11]], requires: [200, 316, 317, 201], modes: ["text2image"] }, { id: "ootd-vton-upper-body-v1", rubric: "community", name: "Outfitting Fusion Virtual Try-on (Upper-Body)", family: "v1", since: "2024-08-26", modifier: "double", files: [[323, 11]], requires: [200, 324], modes: ["edit"], modesUncertain: true }, { id: "ootd-vton-full-body-v1", rubric: "community", name: "Outfitting Fusion Virtual Try-on (Full-Body)", family: "v1", since: "2024-08-26", modifier: "double", files: [[325, 11]], requires: [200, 324], modes: ["edit"], modesUncertain: true }, { id: "flux-1-dev-exact", rubric: "community", name: "FLUX.1 [dev] (Exact)", family: "flux1", since: "2024-08-17", variant: "dev", files: [[326, 11]], requires: [200, 115, 230], modes: ["text2image"] }, { id: "flux-1-dev", rubric: "community", name: "FLUX.1 [dev]", family: "flux1", since: "2024-08-05", variant: "dev", files: [[327, 5], [328, 3]], requires: [200, 115, 201], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_embed: 4.5, guidance_scale: 4.5, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: true, sampler: "EulerATrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 1, speed_up_with_guidance_embed: true, steps: 28, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "flux_1_schnell", rubric: "official", name: "FLUX.1 [schnell]", family: "flux1", since: "2024-08-02", variant: "turbo", files: [[329, 5], [330, 3]], requires: [200, 115, 201], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_embed: 3.5, guidance_scale: 4.5, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "EulerATrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 1, speed_up_with_guidance_embed: true, steps: 4, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024 } } }, { id: "auraflow_v0.2", rubric: "official", name: "AuraFlow v0.2", family: "auraflow", since: "2024-07-29", files: [[331, 5], [332, 3]], requires: [333, 246], modes: ["text2image"] }, { id: "kwai-kolors-inpainting-1.0", rubric: "community", name: "Kwai Kolors Inpainting 1.0", family: "sdxl_base_v0.9", since: "2024-07-26", modifier: "inpainting", files: [[334, 11], [335, 5]], requires: [336, 246], modes: ["inpaint-model"] }, { id: "auraflow_v0.1", rubric: "official", name: "AuraFlow v0.1", family: "auraflow", since: "2024-07-20", files: [[337, 5], [338, 3]], requires: [333, 246], modes: ["text2image"], deprecated: true }, { id: "kwai-kolors-1.0", rubric: "community", name: "Kwai Kolors 1.0", family: "sdxl_base_v0.9", since: "2024-07-15", files: [[339, 11], [340, 5]], requires: [336, 246], modes: ["text2image"] }, { id: "pixart_sigma_xl_2_512_ms", rubric: "official", name: "PixArt Sigma XL 512", family: "pixart", since: "2024-06-29", files: [[341, 11], [342, 5]], requires: [246, 201], modes: ["text2image"] }, { id: "svd-xt-v1.1", rubric: "community", name: "Stable Video Diffusion I2V XT v1.1", family: "svd_i2v", since: "2024-06-29", files: [[343, 11], [344, 5]], requires: [345], modes: ["image2video"] }, { id: "svd-v1.0", rubric: "community", name: "Stable Video Diffusion I2V v1.0", family: "svd_i2v", since: "2024-06-29", files: [[346, 11], [347, 5]], requires: [345], modes: ["image2video"] }, { id: "pixart_sigma_xl_2_1024_ms", rubric: "official", name: "PixArt Sigma XL 1K", family: "pixart", since: "2024-06-27", files: [[348, 11], [349, 5]], requires: [246, 201], modes: ["text2image"] }, { id: "stable-cascade", rubric: "community", name: "Stable Cascade (W\xFCrstchen v3.0)", family: "wurstchen_v3.0_stage_c", since: "2024-06-21", files: [[350, 11], [351, 11], [352, 5], [353, 5]], requires: [316, 354, 350, 352], modes: ["text2image"] }, { id: "sd3-medium", rubric: "community", name: "SD3 Medium", family: "sd3", since: "2024-06-21", files: [[355, 11], [356, 5]], requires: [200, 316, 317, 201], modes: ["text2image"] }, { id: "sdxl-turbo", rubric: "community", name: "SDXL Turbo", family: "sdxl_base_v0.9", since: "2024-06-21", variant: "turbo", files: [[357, 11], [358, 5]], requires: [200, 316, 246], modes: ["text2image"] }, { id: "colorfulxl-v6.0", rubric: "community", name: "ColorfulXL v6.0", family: "sdxl_base_v0.9", since: "2024-06-21", files: [[359, 11], [360, 5]], requires: [361, 362, 246], modes: ["text2image"] }, { id: "proteus-v0.3", rubric: "community", name: "Proteus v0.3", family: "sdxl_base_v0.9", since: "2024-06-21", files: [[363, 11], [364, 5]], requires: [365, 366, 246], modes: ["text2image"] }, { id: "icatcher-realistic", rubric: "community", name: "iCatcher Realistic", family: "sdxl_base_v0.9", since: "2024-06-17", files: [[367, 11], [368, 5]], requires: [369, 370, 246], modes: ["text2image"] }, { id: "icatcher-cartoon", rubric: "community", name: "iCatcher Cartoon", family: "sdxl_base_v0.9", since: "2024-06-17", files: [[371, 11], [372, 5]], requires: [373, 374, 246], modes: ["text2image"] }, { id: "realvisxl-v4.0", rubric: "community", name: "RealVisXL v4.0", family: "sdxl_base_v0.9", since: "2024-06-14", files: [[375, 11], [376, 5]], requires: [377, 378, 246], modes: ["text2image"] }, { id: "pixelwave-v10", rubric: "community", name: "PixelWave 10", family: "sdxl_base_v0.9", since: "2024-06-02", files: [[379, 11], [380, 5]], requires: [381, 382, 246], modes: ["text2image"] }, { id: "juggernaut-xl-v9", rubric: "community", name: "Juggernaut XL v9", family: "sdxl_base_v0.9", since: "2024-04-20", files: [[383, 11], [384, 5]], requires: [385, 386, 246], modes: ["text2image"] }, { id: "pixelwave-v9", rubric: "community", name: "PixelWave v9", family: "sdxl_base_v0.9", since: "2024-04-20", files: [[387, 11], [388, 5]], requires: [389, 390, 246], modes: ["text2image"] }, { id: "juggernaut-xl-x", rubric: "community", name: "Juggernaut XL X", family: "sdxl_base_v0.9", since: "2024-04-20", files: [[391, 11], [392, 5]], requires: [393, 394, 246], modes: ["text2image"] }, { id: "animatelcm-svd-xt-v1.1", rubric: "community", name: "AnimateLCM SVD XT v1.1", family: "svd_i2v", since: "2024-04-01", files: [[395, 11], [396, 5]], requires: [345, 397], modes: ["image2video"] }, { id: "dreamshaper-xl-v2.1-turbo", rubric: "community", name: "DreamShaper XL v2.1 Turbo", family: "sdxl_base_v0.9", since: "2024-03-31", variant: "turbo", files: [[398, 11], [399, 5]], requires: [400, 401, 246], modes: ["text2image"] }, { id: "juggernaut-xl-v9-lightning", rubric: "community", name: "Juggernaut XL v9 Lightning", family: "sdxl_base_v0.9", since: "2024-03-31", variant: "turbo", files: [[402, 11], [403, 5]], requires: [404, 405, 246], modes: ["text2image"] }, { id: "rev-animated-v1.22", rubric: "community", name: "Rev Animated v1.22", family: "v1", since: "2024-03-31", files: [[406, 11], [407, 5]], requires: [408], modes: ["text2image"] }, { id: "realistic-vision-v5.1", rubric: "community", name: "Realistic Vision v5.1", family: "v1", since: "2024-03-30", files: [[409, 11], [410, 5]], requires: [411], modes: ["text2image"] }, { id: "dreamshaper-v8", rubric: "community", name: "DreamShaper v8", family: "v1", since: "2024-03-30", files: [[412, 11], [413, 5]], requires: [414], modes: ["text2image"] }, { id: "counterfeit-v3.0", rubric: "community", name: "Counterfeit v3.0", family: "v1", since: "2024-03-30", files: [[415, 11], [416, 5]], requires: [417], modes: ["text2image"] }, { id: "majicmix-realistic-v7", rubric: "community", name: "MajicMIX Realistic v7", family: "v1", since: "2024-03-30", files: [[418, 11], [419, 5]], requires: [420], modes: ["text2image"] }, { id: "animagine-xl", rubric: "community", name: "Animagine XL v3.1", family: "sdxl_base_v0.9", since: "2024-03-29", files: [[421, 11], [422, 5]], requires: [423, 424, 246], modes: ["text2image"] }, { id: "juggernaut-reborn", rubric: "community", name: "Juggernaut Reborn", family: "v1", since: "2024-03-29", files: [[425, 11], [426, 5]], requires: [427], modes: ["text2image"] }, { id: "playground-v2", rubric: "community", name: "Playground v2", family: "sdxl_base_v0.9", since: "2024-03-28", files: [[428, 11], [429, 5]], requires: [200, 316, 246], modes: ["text2image"] }, { id: "playground-v2.5", rubric: "community", name: "Playground v2.5", family: "sdxl_base_v0.9", since: "2024-03-26", files: [[430, 11], [431, 5]], requires: [200, 316, 246], modes: ["text2image"] }, { id: "ssd-1b", rubric: "community", name: "SSD 1B (Segmind SDXL)", family: "ssd_1b", since: "2024-03-26", files: [[432, 11], [433, 5]], requires: [200, 316, 246], modes: ["text2image"] }, { id: "disney-pixar-cartoon-type-b", rubric: "community", name: "Disney Pixar Cartoon Type B (8-bit)", family: "v1", since: "2024-03-26", files: [[434, 5]], requires: [435], modes: ["text2image"] }, { id: "waifu-diffusion-v1.3", rubric: "community", name: "Anime (Waifu Diffusion v1.3)", family: "v1", since: "2024-03-26", files: [[436, 11]], modes: ["text2image"] }, { id: "multi-style-nitro-diffusion-v1", rubric: "community", name: "Multi-Style (Nitro Diffusion v1)", family: "v1", since: "2024-03-26", files: [[437, 11]], requires: [438], modes: ["text2image"] }, { id: "cyberpunk-anime", rubric: "community", name: "Cyberpunk Anime", family: "v1", since: "2024-03-26", files: [[439, 11]], requires: [440], modes: ["text2image"] }, { id: "redshift-v1", rubric: "community", name: "3D Model (Redshift v1)", family: "v1", since: "2024-03-26", files: [[441, 11]], requires: [442], modes: ["text2image"] }, { id: "readshift-768", rubric: "community", name: "3D Model 768 (Redshift 768)", family: "v2", since: "2024-03-26", files: [[443, 11]], requires: [444], modes: ["text2image"] }, { id: "dungeons-and-diffusion-30000", rubric: "community", name: "Dungeons and Diffusion (30000)", family: "v1", since: "2024-03-26", files: [[445, 11]], requires: [446], modes: ["text2image"] }, { id: "tron-legacy", rubric: "community", name: "Tron Legacy", family: "v1", since: "2024-03-26", files: [[447, 11]], requires: [448], modes: ["text2image"] }, { id: "openjourney", rubric: "community", name: "Openjourney", family: "v1", since: "2024-03-26", files: [[449, 11]], requires: [450], modes: ["text2image"] }, { id: "anything-v3", rubric: "community", name: "Anime (Anything v3)", family: "v1", since: "2024-03-26", files: [[451, 11]], requires: [452, 453], modes: ["text2image"] }, { id: "classic-animation-v1", rubric: "community", name: "Classic Animation (v1)", family: "v1", since: "2024-03-26", files: [[454, 11]], requires: [455], modes: ["text2image"] }, { id: "modern-disney-v1", rubric: "community", name: "Modern Disney (v1)", family: "v1", since: "2024-03-26", files: [[456, 11]], requires: [457], modes: ["text2image"] }, { id: "arcane-v3", rubric: "community", name: "Arcane (v3)", family: "v1", since: "2024-03-26", files: [[458, 11]], requires: [459], modes: ["text2image"] }, { id: "hassanblend-v1.5.1.2", rubric: "community", name: "Hassanblend (v1.5.1.2)", family: "v1", since: "2024-03-26", files: [[460, 11]], requires: [461], modes: ["text2image"] }, { id: "van-gogh-style-lvngvncnt-v2", rubric: "community", name: "Van Gogh Style (Lvngvncnt v2)", family: "v1", since: "2024-03-26", files: [[462, 11]], requires: [463], modes: ["text2image"] }, { id: "spider-verse-v1", rubric: "community", name: "Spider-Verse (v1)", family: "v1", since: "2024-03-26", files: [[464, 11]], requires: [465], modes: ["text2image"] }, { id: "elden-ring-v3", rubric: "community", name: "Elden Ring (v3)", family: "v1", since: "2024-03-26", files: [[466, 11]], requires: [467], modes: ["text2image"] }, { id: "paper-cut-v1", rubric: "community", name: "Paper Cut (v1)", family: "v1", since: "2024-03-26", files: [[468, 11]], requires: [469], modes: ["text2image"] }, { id: "voxelart-v1", rubric: "community", name: "VoxelArt (v1)", family: "v1", since: "2024-03-26", files: [[470, 11]], requires: [471], modes: ["text2image"] }, { id: "balloon-art-v1", rubric: "community", name: "Balloon Art (v1)", family: "v1", since: "2024-03-26", files: [[472, 11]], requires: [473], modes: ["text2image"] }, { id: "f222", rubric: "community", name: "F222", family: "v1", since: "2024-03-26", files: [[474, 11]], modes: ["text2image"] }, { id: "super-mario-nation-v2", rubric: "community", name: "Super Mario Nation (v2)", family: "v1", since: "2024-03-26", files: [[475, 11]], requires: [476], modes: ["text2image"] }, { id: "inkpunk-v2", rubric: "community", name: "Inkpunk (v2)", family: "v1", since: "2024-03-26", files: [[477, 11]], requires: [478], modes: ["text2image"] }, { id: "samdoesart-v3", rubric: "community", name: "SamDoesArt (v3)", family: "v1", since: "2024-03-26", files: [[479, 11]], requires: [480], modes: ["text2image"] }, { id: "ghibli-v1", rubric: "community", name: "Ghibli (v1)", family: "v1", since: "2024-03-26", files: [[481, 11]], requires: [482], modes: ["text2image"] }, { id: "analog-v1", rubric: "community", name: "Analog (v1)", family: "v1", since: "2024-03-26", files: [[483, 11]], requires: [484], modes: ["text2image"] }, { id: "dnd-classes-and-species", rubric: "community", name: "DnD Classes and Species", family: "v1", since: "2024-03-26", files: [[485, 11]], requires: [486], modes: ["text2image"] }, { id: "aloeveras-simpmaker-3k1", rubric: "community", name: "AloeVera's SimpMaker 3K1", family: "v1", since: "2024-03-26", files: [[487, 11]], modes: ["text2image"] }, { id: "ha-3dkx-1.1", rubric: "community", name: "H&A's 3DKX 1.1", family: "v1", since: "2024-03-26", files: [[488, 11]], requires: [489], modes: ["text2image"] }, { id: "seek.art-mega-v1", rubric: "community", name: "seek.art MEGA (v1)", family: "v1", since: "2024-03-26", files: [[490, 11]], requires: [491], modes: ["text2image"] }, { id: "deliberate-v2.0", rubric: "community", name: "Deliberate v2.0 (8-bit)", family: "v1", since: "2024-03-26", files: [[492, 5]], requires: [493], modes: ["text2image"] }, { id: "sd_xl_base_1.0", rubric: "official", name: "SDXL Base (v1.0)", family: "sdxl_base_v0.9", since: "2024-03-24", variant: "base", files: [[494, 11]], requires: [200, 316, 246], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 5, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "DPMPP2MAYS", seed_mode: 2, sharpness: 0, shift: 1, steps: 16, strength: 1, tea_cache: false, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, aesthetic_score: 6, target_image_width: 1024, crop_left: 0, crop_top: 0, negative_original_image_height: 512, target_image_height: 1024, original_image_height: 1024, negative_aesthetic_score: 2.5, original_image_width: 1024, zero_negative_prompt: true, negative_original_image_width: 512 } } }, { id: "sd_xl_base_1.0_q6p", rubric: "official", name: "SDXL Base v1.0 (8-bit)", family: "sdxl_base_v0.9", since: "2024-03-24", variant: "base", files: [[495, 5]], requires: [200, 316, 246], modes: ["text2image"] }, { id: "sd_xl_refiner_1.0", rubric: "official", name: "SDXL Refiner (v1.0)", family: "sdxl_refiner_v0.9", since: "2024-03-24", files: [[496, 11]], requires: [200, 316, 246], modes: ["text2image"] }, { id: "sd_xl_refiner_1.0_q6p", rubric: "official", name: "SDXL Refiner v1.0 (8-bit)", family: "sdxl_refiner_v0.9", since: "2024-03-24", files: [[497, 5]], requires: [200, 316, 246], modes: ["text2image"] }, { id: "sd_xl_base_0.9", rubric: "official", name: "SDXL Base (v0.9)", family: "sdxl_base_v0.9", since: "2024-03-24", variant: "base", files: [[498, 11]], requires: [200, 316, 499], modes: ["text2image"], deprecated: true }, { id: "sd_xl_refiner_0.9", rubric: "official", name: "SDXL Refiner (v0.9)", family: "sdxl_refiner_v0.9", since: "2024-03-24", files: [[500, 11]], requires: [200, 316, 499], modes: ["text2image"], deprecated: true }, { id: "fooocus_inpaint_sd_xl_v2.6", rubric: "official", name: "Fooocus Inpaint SDXL v2.6", family: "sdxl_base_v0.9", since: "2024-03-24", modifier: "inpainting", files: [[501, 11]], requires: [200, 316, 246], modes: ["inpaint-model"] }, { id: "fooocus_inpaint_sd_xl_v2.6_q6p", rubric: "official", name: "Fooocus Inpaint SDXL v2.6 (8-bit)", family: "sdxl_base_v0.9", since: "2024-03-24", modifier: "inpainting", files: [[502, 5]], requires: [200, 316, 246], modes: ["inpaint-model"] }, { id: "sd_v1.4", rubric: "official", name: "Stable Diffusion v1.4", family: "v1", since: "2024-03-24", files: [[503, 11]], modes: ["text2image"], deprecated: true }, { id: "sd_v1.5", rubric: "official", name: "Stable Diffusion v1.5", family: "v1", since: "2024-03-24", files: [[504, 11]], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 1, controls: [], guidance_scale: 5, height: 512, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "DPMPP2MAYS", seed_mode: 2, sharpness: 0, shift: 1, steps: 16, strength: 1, tea_cache: false, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 512 } } }, { id: "sd_v1.5_inpainting", rubric: "official", name: "Stable Diffusion v1.5 Inpainting", family: "v1", since: "2024-03-24", modifier: "inpainting", files: [[505, 11]], modes: ["inpaint-model"] }, { id: "sd_v2.0", rubric: "official", name: "Stable Diffusion v2.0", family: "v2", since: "2024-03-24", files: [[506, 11]], requires: [507], modes: ["text2image"], deprecated: true }, { id: "sd_v2.0_768_v", rubric: "official", name: "Stable Diffusion v2.0 768-v", family: "v2", since: "2024-03-24", files: [[508, 11]], requires: [507], modes: ["text2image"], deprecated: true }, { id: "sd_v2.0_inpainting", rubric: "official", name: "Stable Diffusion v2.0 Inpainting", family: "v2", since: "2024-03-24", modifier: "inpainting", files: [[509, 11]], requires: [507], modes: ["inpaint-model"] }, { id: "sd_v2.0_depth", rubric: "official", name: "Stable Diffusion v2.0 Depth", family: "v2", since: "2024-03-24", modifier: "depth", files: [[510, 11]], requires: [507], modes: ["control-model"] }, { id: "sd_v2.1", rubric: "official", name: "Stable Diffusion v2.1", family: "v2", since: "2024-03-24", files: [[511, 11]], requires: [507], modes: ["text2image"] }, { id: "sd_v2.1_768_v", rubric: "official", name: "Stable Diffusion v2.1 768-v", family: "v2", since: "2024-03-24", files: [[512, 11]], requires: [507], modes: ["text2image"] }, { id: "kandinsky", rubric: "official", name: "Kandinsky v2.1", family: "kandinsky2.1", since: "2024-03-24", files: [[513, 11]], requires: [200, 514, 515], modes: ["text2image"], deprecated: true }, { id: "svd_i2v_xt_1.0", rubric: "official", name: "Stable Video Diffusion I2V XT v1.0", family: "svd_i2v", since: "2024-03-24", files: [[516, 11]], requires: [345], modes: ["image2video"], deprecated: true }, { id: "svd_i2v_xt_1.0_q6p", rubric: "official", name: "Stable Video Diffusion I2V XT 1.0 (8-bit)", family: "svd_i2v", since: "2024-03-24", files: [[517, 5]], requires: [345], modes: ["image2video"], deprecated: true }, { id: "minisd_v1.4", rubric: "official", name: "MiniSD v1.4", family: "v1", since: "2024-03-24", files: [[518, 11]], modes: ["text2image"], deprecated: true }, { id: "instruct_pix2pix_22000", rubric: "official", name: "Instruct Pix2Pix", family: "v1", since: "2024-03-24", modifier: "editing", files: [[519, 11]], modes: ["edit"], modesUncertain: true, deprecated: true }, { id: "2DN", rubric: "uncurated", name: "2DN", family: "sdxl_base_v0.9", files: [[520, 11]], requires: [521, 522, 246], modes: ["text2image"] }, { id: "8Steps_Creart_Hyper_Flux_creart_Ultimate", rubric: "uncurated", name: "8Steps_Creart_Hyper_Flux_creart_Ultimate", family: "flux1", files: [[523, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "8Steps_Creart_Hyper_Flux_v24Hyper_Dev_Fp8Unet", rubric: "uncurated", name: "8Steps_Creart_Hyper_Flux_v24Hyper_Dev_Fp8Unet", family: "flux1", variant: "dev", files: [[524, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "8Steps_Creart_Hyper_Flux_v26Hyper_Dev_Fp8Unet", rubric: "uncurated", name: "8Steps_Creart_Hyper_Flux_v26Hyper_Dev_Fp8Unet", family: "flux1", variant: "dev", files: [[525, 11], [526, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "8Steps_Creart_Hyper_Flux_v30Hyper_Dev_Fp8Unet", rubric: "uncurated", name: "8Steps_Creart_Hyper_Flux_v30Hyper_Dev_Fp8Unet", family: "flux1", variant: "dev", files: [[527, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "8Steps_Creart_Hyper_Flux_v40Hyper_Dev_Fp8Unet", rubric: "uncurated", name: "8Steps_Creart_Hyper_Flux_v40Hyper_Dev_Fp8Unet", family: "flux1", variant: "dev", files: [[528, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Acorn_Is_Spinning_FLUX_ais_Flux_De_Distilled", rubric: "uncurated", name: "Acorn_Is_Spinning_FLUX_ais_Flux_De_Distilled", family: "flux1", variant: "turbo", files: [[529, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Acorn_Is_Spinning_FLUX_ais_Flux_V15", rubric: "uncurated", name: "Acorn_Is_Spinning_FLUX_ais_Flux_V15", family: "flux1", files: [[530, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Acorn_Is_Spinning_FLUX_aisf_De_Distilled_V15", rubric: "uncurated", name: "Acorn_Is_Spinning_FLUX_aisf_De_Distilled_V15", family: "flux1", variant: "turbo", files: [[531, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Acorn_Is_Spinning_FLUX_aisf_Hyper8Step_V15", rubric: "uncurated", name: "Acorn_Is_Spinning_FLUX_aisf_Hyper8Step_V15", family: "flux1", files: [[532, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Acorn_Is_Spinning_FLUX_aisf_V169", rubric: "uncurated", name: "Acorn_Is_Spinning_FLUX_aisf_V169", family: "flux1", files: [[533, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Acorn_Is_Spinning_FLUX_aisf11H8stp_Chinfx", rubric: "uncurated", name: "Acorn_Is_Spinning_FLUX_aisf11H8stp_Chinfx", family: "flux1", files: [[534, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Agflux_Fill_NSFWFp8", rubric: "uncurated", name: "Agflux_Fill_NSFWFp8_agflux_Fill_NSFWV17Fp8", family: "flux1", modifier: "inpainting", files: [[535, 5]], requires: [200, 115, 201], modes: ["inpaint-model"] }, { id: "Agflux_Schnell_V10Fp8", rubric: "uncurated", name: "Agflux_Schnell_V10Fp8", family: "flux1", variant: "turbo", files: [[536, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Agflux_V10Fp8", rubric: "uncurated", name: "Agflux_V10Fp8", family: "flux1", files: [[537, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Agflux_V21Fp8", rubric: "uncurated", name: "Agflux_V21Fp8", family: "flux1", files: [[538, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Agflux_V3Fp8", rubric: "uncurated", name: "Agflux_V3Fp8", family: "flux1", files: [[539, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "AGGAs-Utopia-_illustrious-SDXL", rubric: "uncurated", name: "AGGAs-Utopia-_illustrious-SDXL", family: "sdxl_base_v0.9", files: [[540, 11]], requires: [541, 542, 246], modes: ["text2image"] }, { id: "Amanatsu-Illustrious", rubric: "uncurated", name: "Amanatsu-Illustrious", family: "sdxl_base_v0.9", files: [[543, 11]], requires: [544, 545, 246], modes: ["text2image"] }, { id: "Anillustrious", rubric: "uncurated", name: "Anillustrious", family: "sdxl_base_v0.9", files: [[546, 11]], requires: [547, 548, 246], modes: ["text2image"] }, { id: "Animij", rubric: "uncurated", name: "Animij", family: "sdxl_base_v0.9", files: [[549, 11]], requires: [550, 551, 246], modes: ["text2image"] }, { id: "anisora-v2-i2v-wan-2.1-14b", rubric: "uncurated", name: "AniSora v2 I2V Wan 2.1 14B", family: "wan_v2.1_14b", modifier: "inpainting", files: [[552, 5], [553, 4]], requires: [181, 175, 176], modes: ["image2video"] }, { id: "anisora-v3.1-i2v-wan-2.1-14b", rubric: "uncurated", name: "AniSora v3.1 I2V Wan 2.1 14B", family: "wan_v2.1_14b", modifier: "inpainting", files: [[554, 5], [555, 4]], requires: [181, 175, 176], modes: ["image2video"] }, { id: "Artofura-Furry-mix", rubric: "uncurated", name: "Artofura-Furry-mix", family: "sdxl_base_v0.9", files: [[556, 11]], requires: [557, 558, 246], modes: ["text2image"] }, { id: "Artsy_Dream_v1FP16", rubric: "uncurated", name: "Artsy_Dream_v1FP16", family: "flux1", files: [[559, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v1FP8", rubric: "uncurated", name: "Artsy_Dream_v1FP8", family: "flux1", files: [[560, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v2FP16", rubric: "uncurated", name: "Artsy_Dream_v2FP16", family: "flux1", files: [[561, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v2FP8", rubric: "uncurated", name: "Artsy_Dream_v2FP8", family: "flux1", files: [[562, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v3FP16", rubric: "uncurated", name: "Artsy_Dream_v3FP16", family: "flux1", files: [[563, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v3FP8", rubric: "uncurated", name: "Artsy_Dream_v3FP8", family: "flux1", files: [[564, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v4FP16", rubric: "uncurated", name: "Artsy_Dream_v4FP16", family: "flux1", files: [[565, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v4FP8", rubric: "uncurated", name: "Artsy_Dream_v4FP8", family: "flux1", files: [[566, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v5FP16", rubric: "uncurated", name: "Artsy_Dream_v5FP16", family: "flux1", files: [[567, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v5FP8", rubric: "uncurated", name: "Artsy_Dream_v5FP8", family: "flux1", files: [[568, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v6FP16", rubric: "uncurated", name: "Artsy_Dream_v6FP16", family: "flux1", files: [[569, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v6FP8", rubric: "uncurated", name: "Artsy_Dream_v6FP8", family: "flux1", files: [[570, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Vibe_v1FP16", rubric: "uncurated", name: "Artsy_Vibe_v1FP16", family: "flux1", files: [[571, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Vibe_v1FP8", rubric: "uncurated", name: "Artsy_Vibe_v1FP8", family: "flux1", files: [[572, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Vibe_v2FP16", rubric: "uncurated", name: "Artsy_Vibe_v2FP16", family: "flux1", files: [[573, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Vibe_v2FP8", rubric: "uncurated", name: "Artsy_Vibe_v2FP8", family: "flux1", files: [[574, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Asian-Realism-By-Stable-Yogi-PONY", rubric: "uncurated", name: "Asian-Realism-By-Stable-Yogi-PONY", family: "sdxl_base_v0.9", files: [[575, 11]], requires: [576, 577, 246], modes: ["text2image"] }, { id: "Atomix_FLUXUnet_v10", rubric: "uncurated", name: "Atomix_FLUXUnet_v10", family: "flux1", files: [[578, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Aungir_Aungir_T6A4_1405004", rubric: "uncurated", name: "Aungir_Aungir_T6A4_1405004", family: "sdxl_base_v0.9", files: [[579, 11]], requires: [580, 581, 246], modes: ["text2image"] }, { id: "Aungir_Aungir_T6AO4.5_1723632", rubric: "uncurated", name: "Aungir_Aungir_T6AO4.5_1723632", family: "sdxl_base_v0.9", files: [[582, 11]], requires: [583, 584, 246], modes: ["text2image"] }, { id: "Big-Love", rubric: "uncurated", name: "Big-Love", family: "sdxl_base_v0.9", files: [[585, 11]], requires: [586, 587, 246], modes: ["text2image"] }, { id: "Bismuth-Illustrious-Mix", rubric: "uncurated", name: "Bismuth-Illustrious-Mix", family: "sdxl_base_v0.9", files: [[588, 11]], requires: [589, 590, 246], modes: ["text2image"] }, { id: "BlenderMix", rubric: "uncurated", name: "BlenderMix", family: "sdxl_base_v0.9", files: [[591, 11]], requires: [592, 593, 246], modes: ["text2image"] }, { id: "Blue_Pencil_Flux1_v010", rubric: "uncurated", name: "Blue_Pencil_Flux1_v010", family: "flux1", files: [[594, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Blue_Pencil_Flux1_v021", rubric: "uncurated", name: "Blue_Pencil_Flux1_v021", family: "flux1", files: [[595, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "boleromixillustrious", rubric: "uncurated", name: "boleromixillustrious", family: "sdxl_base_v0.9", files: [[596, 11]], requires: [597, 598, 246], modes: ["text2image"] }, { id: "C4pacitor_a_V2Alpha", rubric: "uncurated", name: "C4pacitor_a_V2Alpha", family: "flux1", files: [[599, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "C4pacitor_a_V2Beta", rubric: "uncurated", name: "C4pacitor_a_V2Beta", family: "flux1", files: [[600, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "C4pacitor_d_V1", rubric: "uncurated", name: "C4pacitor_d_V1", family: "flux1", files: [[601, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "C4pacitor_d_V11", rubric: "uncurated", name: "C4pacitor_d_V11", family: "flux1", files: [[602, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "C4pacitor_d_V2", rubric: "uncurated", name: "C4pacitor_d_V2", family: "flux1", files: [[603, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "C4pacitor_d_V3Alpha", rubric: "uncurated", name: "C4pacitor_d_V3Alpha", family: "flux1", files: [[604, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "C4pacitor_s_V11", rubric: "uncurated", name: "C4pacitor_s_V11", family: "flux1", files: [[605, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "C4pacitor_s_V2Alpha", rubric: "uncurated", name: "C4pacitor_s_V2Alpha", family: "flux1", files: [[606, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Candied-Anime-IllustriousXL", rubric: "uncurated", name: "Candied-Anime-IllustriousXL", family: "sdxl_base_v0.9", files: [[607, 11]], requires: [608, 609, 246], modes: ["text2image"] }, { id: "Centerfold_Flux_v35FP8E54Steps", rubric: "uncurated", name: "Centerfold_Flux_v35FP8E54Steps", family: "flux1", files: [[610, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Centerfold_Flux_v40Fp8E5m2", rubric: "uncurated", name: "Centerfold_Flux_v40Fp8E5m2", family: "flux1", files: [[611, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-1-hd-annealed", rubric: "uncurated", name: "Chroma1 HD Annealed", family: "flux1", files: [[612, 5], [613, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v38-detail-calibrated", rubric: "uncurated", name: "Chroma v38 Detail Calibrated", family: "flux1", files: [[614, 5], [615, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v39-detail-calibrated", rubric: "uncurated", name: "Chroma v39 Detail Calibrated", family: "flux1", files: [[616, 5], [617, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v40-detail-calibrated", rubric: "uncurated", name: "Chroma v40 Detail Calibrated", family: "flux1", files: [[618, 5], [619, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v41-detail-calibrated", rubric: "uncurated", name: "Chroma v41 Detail Calibrated", family: "flux1", files: [[620, 5], [621, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v42-detail-calibrated", rubric: "uncurated", name: "Chroma v42 Detail Calibrated", family: "flux1", files: [[622, 5], [623, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v43-detail-calibrated", rubric: "uncurated", name: "Chroma v43 Detail Calibrated", family: "flux1", files: [[624, 5], [625, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v44-detail-calibrated", rubric: "uncurated", name: "Chroma v44 Detail Calibrated", family: "flux1", files: [[626, 5], [627, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v45-detail-calibrated", rubric: "uncurated", name: "Chroma v45 Detail Calibrated", family: "flux1", files: [[628, 5], [629, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v46-detail-calibrated", rubric: "uncurated", name: "Chroma v46 Detail Calibrated", family: "flux1", files: [[630, 5], [631, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "CircusMix", rubric: "uncurated", name: "CircusMix", family: "sdxl_base_v0.9", files: [[632, 11]], requires: [633, 634, 246], modes: ["text2image"] }, { id: "Colorfulasiangirl_Flux_beta", rubric: "uncurated", name: "Colorfulasiangirl_Flux_beta", family: "flux1", files: [[635, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_21De_Distilled_AIOExp", rubric: "uncurated", name: "Colossus_Project_Flux_21De_Distilled_AIOExp", family: "flux1", variant: "turbo", files: [[636, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v10AIOFP8", rubric: "uncurated", name: "Colossus_Project_Flux_v10AIOFP8", family: "flux1", files: [[637, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v10All_In_One_Fp8", rubric: "uncurated", name: "Colossus_Project_Flux_v10All_In_One_Fp8", family: "flux1", files: [[638, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v10b_FP8AIOBOBFP8", rubric: "uncurated", name: "Colossus_Project_Flux_v10b_FP8AIOBOBFP8", family: "flux1", files: [[639, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v10Behemoth_AIOFP16", rubric: "uncurated", name: "Colossus_Project_Flux_v10Behemoth_AIOFP16", family: "flux1", files: [[640, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v10FP16UNETONLY", rubric: "uncurated", name: "Colossus_Project_Flux_v10FP16UNETONLY", family: "flux1", files: [[641, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v10UNETOnly_FP16", rubric: "uncurated", name: "Colossus_Project_Flux_v10UNETOnly_FP16", family: "flux1", files: [[642, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v10UNETOnly_FP8", rubric: "uncurated", name: "Colossus_Project_Flux_v10UNETOnly_FP8", family: "flux1", files: [[643, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v20All_In_One_Exp", rubric: "uncurated", name: "Colossus_Project_Flux_v20All_In_One_Exp", family: "flux1", files: [[644, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v42AIO", rubric: "uncurated", name: "Colossus_Project_Flux_v42AIO", family: "flux1", files: [[645, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v44AIO", rubric: "uncurated", name: "Colossus_Project_Flux_v44AIO", family: "flux1", files: [[646, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v50AIO", rubric: "uncurated", name: "Colossus_Project_Flux_v50AIO", family: "flux1", files: [[647, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v50AIOBehemoth", rubric: "uncurated", name: "Colossus_Project_Flux_v50AIOBehemoth", family: "flux1", files: [[648, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v50FP8UNET", rubric: "uncurated", name: "Colossus_Project_Flux_v50FP8UNET", family: "flux1", files: [[649, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v90AIO", rubric: "uncurated", name: "Colossus_Project_Flux_v90AIO", family: "flux1", files: [[650, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_fluxreal_Fast", rubric: "uncurated", name: "Copax_Timeless_fluxreal_Fast", family: "flux1", variant: "turbo", files: [[651, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_stylemix1Flux_Dev_FP16", rubric: "uncurated", name: "Copax_Timeless_stylemix1Flux_Dev_FP16", family: "flux1", variant: "dev", files: [[652, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_stylemix1Fp8", rubric: "uncurated", name: "Copax_Timeless_stylemix1Fp8", family: "flux1", files: [[653, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_stylemix2", rubric: "uncurated", name: "Copax_Timeless_stylemix2", family: "flux1", files: [[654, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_Cartoon", rubric: "uncurated", name: "Copax_Timeless_xplus_Cartoon", family: "flux1", files: [[655, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_MIX1", rubric: "uncurated", name: "Copax_Timeless_xplus_MIX1", family: "flux1", files: [[656, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_MIX1FP8", rubric: "uncurated", name: "Copax_Timeless_xplus_MIX1FP8", family: "flux1", files: [[657, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_MIX2", rubric: "uncurated", name: "Copax_Timeless_xplus_MIX2", family: "flux1", files: [[658, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_MIX3", rubric: "uncurated", name: "Copax_Timeless_xplus_MIX3", family: "flux1", files: [[659, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_MIX3Dark", rubric: "uncurated", name: "Copax_Timeless_xplus_MIX3Dark", family: "flux1", files: [[660, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_MIX4", rubric: "uncurated", name: "Copax_Timeless_xplus_MIX4", family: "flux1", files: [[661, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_Poses", rubric: "uncurated", name: "Copax_Timeless_xplus_Poses", family: "flux1", files: [[662, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_Unreal_Fast", rubric: "uncurated", name: "Copax_Timeless_xplus_Unreal_Fast", family: "flux1", variant: "turbo", files: [[663, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus1", rubric: "uncurated", name: "Copax_Timeless_xplus1", family: "flux1", files: [[664, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus2", rubric: "uncurated", name: "Copax_Timeless_xplus2", family: "flux1", files: [[665, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus2Base_Train", rubric: "uncurated", name: "Copax_Timeless_xplus2Base_Train", family: "flux1", files: [[666, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax-Pony-XL", rubric: "uncurated", name: "Copax-Pony-XL", family: "sdxl_base_v0.9", files: [[667, 11]], requires: [668, 669, 246], modes: ["text2image"] }, { id: "Crow-Pony-qp", rubric: "uncurated", name: "Crow-Pony-qp", family: "sdxl_base_v0.9", files: [[670, 11]], requires: [671, 672, 246], modes: ["text2image"] }, { id: "CyberIllustrious-CyberRealistic", rubric: "uncurated", name: "CyberIllustrious-CyberRealistic", family: "sdxl_base_v0.9", files: [[673, 11]], requires: [674, 675, 246], modes: ["text2image"] }, { id: "CyberRealistic", rubric: "uncurated", name: "CyberRealistic", family: "v1", files: [[676, 11]], requires: [677], modes: ["text2image"] }, { id: "CyberRealistic_Pony_v8_1346181", rubric: "uncurated", name: "CyberRealistic_Pony_v8_1346181", family: "sdxl_base_v0.9", files: [[678, 11]], requires: [679, 680, 246], modes: ["text2image"] }, { id: "CyberRealistic_Pony_v8.5_1478064", rubric: "uncurated", name: "CyberRealistic_Pony_v8.5_1478064", family: "sdxl_base_v0.9", files: [[681, 11]], requires: [682, 683, 246], modes: ["text2image"] }, { id: "CyberRealistic_Pony_v9.0_Alt_1_1691220", rubric: "uncurated", name: "CyberRealistic_Pony_v9.0_Alt_1_1691220", family: "sdxl_base_v0.9", files: [[684, 11]], requires: [685, 686, 246], modes: ["text2image"] }, { id: "cyberrealistic-flux-v2-5", rubric: "uncurated", name: "CyberRealistic Flux v2.5", family: "flux1", files: [[687, 11], [688, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "CyberRealistic-Pony-Catalyst", rubric: "uncurated", name: "CyberRealistic-Pony-Catalyst", family: "sdxl_base_v0.9", files: [[689, 11]], requires: [690, 691, 246], modes: ["text2image"] }, { id: "CyberRealistic-Pony-Semi-Realistic", rubric: "uncurated", name: "CyberRealistic-Pony-Semi-Realistic", family: "sdxl_base_v0.9", files: [[692, 11]], requires: [693, 694, 246], modes: ["text2image"] }, { id: "CyberRealistic-XL", rubric: "uncurated", name: "CyberRealistic-XL", family: "sdxl_base_v0.9", files: [[695, 11]], requires: [696, 697, 246], modes: ["text2image"] }, { id: "Demon_CORESFWNSFW_flux_V13", rubric: "uncurated", name: "Demon_CORESFWNSFW_flux_V13", family: "flux1", files: [[698, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Demon_CORESFWNSFW_v25Helheim_Project_AIO", rubric: "uncurated", name: "Demon_CORESFWNSFW_v25Helheim_Project_AIO", family: "flux1", files: [[699, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "DHXL-v1.0", rubric: "uncurated", name: "DHXL-v1.0", family: "sdxl_base_v0.9", files: [[700, 11]], requires: [701, 702, 246], modes: ["text2image"] }, { id: "Dixar", rubric: "uncurated", name: "Dixar", family: "sdxl_base_v0.9", files: [[703, 11]], requires: [704, 705, 246], modes: ["text2image"] }, { id: "Dreamisoa-remix", rubric: "uncurated", name: "Dreamisoa-remix", family: "sdxl_base_v0.9", files: [[706, 11]], requires: [707, 708, 246], modes: ["text2image"] }, { id: "DucHaiten_Pony_XL_no_score_v5.2_706363", rubric: "uncurated", name: "DucHaiten_Pony_XL_no_score_v5.2_706363", family: "sdxl_base_v0.9", files: [[709, 11]], requires: [710, 711, 246], modes: ["text2image"] }, { id: "DucHaiten_Pony_XL_no_score_v6.0_817261", rubric: "uncurated", name: "DucHaiten_Pony_XL_no_score_v6.0_817261", family: "sdxl_base_v0.9", files: [[712, 11]], requires: [713, 714, 246], modes: ["text2image"] }, { id: "DucHaiten-Cool-Age", rubric: "uncurated", name: "DucHaiten-Cool-Age", family: "sdxl_base_v0.9", files: [[715, 11]], requires: [716, 717, 246], modes: ["text2image"] }, { id: "DucHaiten-NoobAI", rubric: "uncurated", name: "DucHaiten-NoobAI", family: "sdxl_base_v0.9", files: [[718, 11]], requires: [719, 720, 246], modes: ["text2image"] }, { id: "DucHaiten-NoobAI-Cinematic", rubric: "uncurated", name: "DucHaiten-NoobAI-Cinematic", family: "sdxl_base_v0.9", files: [[721, 11]], requires: [722, 723, 246], modes: ["text2image"] }, { id: "DucHaiten-Pony-Real", rubric: "uncurated", name: "DucHaiten-Pony-Real", family: "sdxl_base_v0.9", files: [[724, 11]], requires: [725, 726, 246], modes: ["text2image"] }, { id: "Edge_Of_Reality_32Beyond_Reality", rubric: "uncurated", name: "Edge_Of_Reality_32Beyond_Reality", family: "flux1", files: [[727, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Edge_Of_Reality_v30", rubric: "uncurated", name: "Edge_Of_Reality_v30", family: "flux1", files: [[728, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Editijon-K-POP", rubric: "uncurated", name: "Editijon-K-POP", family: "sdxl_base_v0.9", files: [[729, 11]], requires: [730, 731, 246], modes: ["text2image"] }, { id: "epiCRealism-XL", rubric: "uncurated", name: "epiCRealism-XL", family: "sdxl_base_v0.9", files: [[732, 11]], requires: [733, 734, 246], modes: ["text2image"] }, { id: "Eri-LumenVeil-V1-Illustrious-NAI", rubric: "uncurated", name: "Eri-LumenVeil-V1-Illustrious-NAI", family: "sdxl_base_v0.9", files: [[735, 11]], requires: [736, 737, 246], modes: ["text2image"] }, { id: "Fantasm-Pony-XL", rubric: "uncurated", name: "Fantasm-Pony-XL", family: "sdxl_base_v0.9", files: [[738, 11]], requires: [739, 740, 246], modes: ["text2image"] }, { id: "Fenrisxl_Flux_fenris_Flux_V1FP8", rubric: "uncurated", name: "Fenrisxl_Flux_fenris_Flux_V1FP8", family: "flux1", files: [[741, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Five_Stars_Illustrious_1.0_1398525", rubric: "uncurated", name: "Five_Stars_Illustrious_1.0_1398525", family: "sdxl_base_v0.9", files: [[742, 11]], requires: [743, 744, 246], modes: ["text2image"] }, { id: "Five_Stars_Illustrious_4.0_1657020", rubric: "uncurated", name: "Five_Stars_Illustrious_4.0_1657020", family: "sdxl_base_v0.9", files: [[745, 11]], requires: [746, 747, 246], modes: ["text2image"] }, { id: "Flux_Realistic_flux_Realistic_Samay_V2", rubric: "uncurated", name: "Flux_Realistic_flux_Realistic_Samay_V2", family: "flux1", files: [[748, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Flux1_v10Fp8", rubric: "uncurated", name: "Flux1_v10Fp8", family: "flux1", files: [[749, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Flux1_v10Fp8Schnell", rubric: "uncurated", name: "Flux1_v10Fp8Schnell", family: "flux1", files: [[750, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Flux1_v20Fp8", rubric: "uncurated", name: "Flux1_v20Fp8", family: "flux1", files: [[751, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Flux1_v30Fp8", rubric: "uncurated", name: "Flux1_v30Fp8", family: "flux1", files: [[752, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Flux1_v30PAPFp8", rubric: "uncurated", name: "Flux1_v30PAPFp8", family: "flux1", files: [[753, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Flux1Dev_Asian_v10FP16", rubric: "uncurated", name: "Flux1Dev_Asian_v10FP16", family: "flux1", files: [[754, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Flux1east_Fp8_canny", rubric: "uncurated", name: "Flux1east_Fp8_canny", family: "flux1", modifier: "depth", files: [[755, 5]], requires: [200, 115, 201], modes: ["control-model"] }, { id: "Flux1east_Fp8_depth", rubric: "uncurated", name: "Flux1east_Fp8_depth", family: "flux1", modifier: "depth", files: [[756, 5]], requires: [200, 115, 201], modes: ["control-model"] }, { id: "Flux1east_Fp8_dev", rubric: "uncurated", name: "Flux1east_Fp8_dev", family: "flux1", variant: "dev", files: [[757, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Flux1east_Fp8_fill", rubric: "uncurated", name: "Flux1east_Fp8_fill", family: "flux1", modifier: "inpainting", files: [[758, 5]], requires: [200, 115, 201], modes: ["inpaint-model"] }, { id: "Fluxed_Up_Flux_NSFW_10", rubric: "uncurated", name: "Fluxed_Up_Flux_NSFW_10", family: "flux1", files: [[759, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxed_Up_Flux_NSFW_21", rubric: "uncurated", name: "Fluxed_Up_Flux_NSFW_21", family: "flux1", files: [[760, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxed_Up_Flux_NSFW_22", rubric: "uncurated", name: "Fluxed_Up_Flux_NSFW_22", family: "flux1", files: [[761, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxed_Up_Flux_NSFW_24", rubric: "uncurated", name: "Fluxed_Up_Flux_NSFW_24", family: "flux1", files: [[762, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxed_Up_Flux_NSFW_25", rubric: "uncurated", name: "Fluxed_Up_Flux_NSFW_25", family: "flux1", files: [[763, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxed_Up_Flux_NSFW_40Dev_Fp8", rubric: "uncurated", name: "Fluxed_Up_Flux_NSFW_40Dev_Fp8", family: "flux1", files: [[764, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxed_Up_Flux_NSFW_41", rubric: "uncurated", name: "Fluxed_Up_Flux_NSFW_41", family: "flux1", files: [[765, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxmania_i", rubric: "uncurated", name: "Fluxmania_i", family: "flux1", files: [[766, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxmania_iv", rubric: "uncurated", name: "Fluxmania_iv", family: "flux1", files: [[767, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxmania_legacy", rubric: "uncurated", name: "Fluxmania_legacy", family: "flux1", files: [[768, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxmania_v", rubric: "uncurated", name: "Fluxmania_v", family: "flux1", files: [[769, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "FurryToonMix", rubric: "uncurated", name: "FurryToonMix", family: "sdxl_base_v0.9", files: [[770, 11]], requires: [771, 772, 246], modes: ["text2image"] }, { id: "Genova_APEX_1618Experiment", rubric: "uncurated", name: "Genova_APEX_1618Experiment", family: "flux1", files: [[773, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Genova_APEX_genova_V2", rubric: "uncurated", name: "Genova_APEX_genova_V2", family: "flux1", files: [[774, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Genova_APEX_plus", rubric: "uncurated", name: "Genova_APEX_plus", family: "flux1", files: [[775, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Genova_APEX_real", rubric: "uncurated", name: "Genova_APEX_real", family: "flux1", files: [[776, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Genova_APEX_s", rubric: "uncurated", name: "Genova_APEX_s", family: "flux1", files: [[777, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "getphat-flux-reality-nsfw", rubric: "uncurated", name: "getphat FLUX Reality NSFW v11 Softcore", family: "flux1", files: [[778, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Gonzalomo_XLFlux_Pony_v03Fluxity_Fp8", rubric: "uncurated", name: "Gonzalomo_XLFlux_Pony_v03Fluxity_Fp8", family: "flux1", files: [[779, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Gonzalomo_XLFlux_Pony_v10Fluxity_Fp8", rubric: "uncurated", name: "Gonzalomo_XLFlux_Pony_v10Fluxity_Fp8", family: "flux1", files: [[780, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "HomoSimile-XL-Pony_-Illustrious_-NoobAI", rubric: "uncurated", name: "HomoSimile-XL-Pony_-Illustrious_-NoobAI", family: "sdxl_base_v0.9", files: [[781, 11]], requires: [782, 783, 246], modes: ["text2image"] }, { id: "Hoseki-LustrousMix-IllustriousXL", rubric: "uncurated", name: "Hoseki-LustrousMix-IllustriousXL", family: "sdxl_base_v0.9", files: [[784, 11]], requires: [785, 786, 246], modes: ["text2image"] }, { id: "Hoseki-LustrousMix-Pony-XL", rubric: "uncurated", name: "Hoseki-LustrousMix-Pony-XL", family: "sdxl_base_v0.9", files: [[787, 11]], requires: [788, 789, 246], modes: ["text2image"] }, { id: "Hs-UltraHD-CG", rubric: "uncurated", name: "Hs-UltraHD-CG", family: "sdxl_base_v0.9", files: [[790, 11]], requires: [791, 792, 246], modes: ["text2image"] }, { id: "Hyper_Flux_Dedistilled_hyper16Steps_FP8", rubric: "uncurated", name: "Hyper_Flux_Dedistilled_hyper16Steps_FP8", family: "flux1", files: [[793, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Hyper_Flux_Dedistilled_hyper8Steps_FP8", rubric: "uncurated", name: "Hyper_Flux_Dedistilled_hyper8Steps_FP8", family: "flux1", files: [[794, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "IcedCoffeeIL", rubric: "uncurated", name: "IcedCoffeeIL", family: "sdxl_base_v0.9", files: [[795, 11]], requires: [796, 797, 246], modes: ["text2image"] }, { id: "IffyMix-XL", rubric: "uncurated", name: "IffyMix-XL", family: "sdxl_base_v0.9", files: [[798, 11]], requires: [799, 800, 246], modes: ["text2image"] }, { id: "IllumiYume-XL-Illustrious", rubric: "uncurated", name: "IllumiYume-XL-Illustrious", family: "sdxl_base_v0.9", files: [[801, 11]], requires: [802, 803, 246], modes: ["text2image"] }, { id: "Illustration_Juaner_Ghibli_v10", rubric: "uncurated", name: "Illustration_Juaner_Ghibli_v10", family: "flux1", files: [[804, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Illustration_Juaner_Ghibli_v20", rubric: "uncurated", name: "Illustration_Juaner_Ghibli_v20", family: "flux1", files: [[805, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Illustrij", rubric: "uncurated", name: "Illustrij", family: "sdxl_base_v0.9", files: [[806, 11]], requires: [807, 808, 246], modes: ["text2image"] }, { id: "illustrij-gen-v1", rubric: "uncurated", name: "Illustrij-GENv1", family: "sdxl_base_v0.9", files: [[809, 11], [810, 5]], requires: [811, 812, 246], modes: ["text2image"] }, { id: "Illustrious-Black-Magic-Illustrious-Noob-More", rubric: "uncurated", name: "Illustrious-Black-Magic-Illustrious-Noob-More", family: "sdxl_base_v0.9", files: [[813, 11]], requires: [814, 815, 246], modes: ["text2image"] }, { id: "Illustrious-Gehenna-Illustrious-Checkpoint", rubric: "uncurated", name: "Illustrious-Gehenna-Illustrious-Checkpoint", family: "sdxl_base_v0.9", files: [[816, 11]], requires: [817, 818, 246], modes: ["text2image"] }, { id: "Illustrious-Realism-by-klaabu", rubric: "uncurated", name: "Illustrious-Realism-by-klaabu", family: "sdxl_base_v0.9", files: [[819, 11]], requires: [820, 821, 246], modes: ["text2image"] }, { id: "Illustrious-XL", rubric: "uncurated", name: "Illustrious-XL", family: "sdxl_base_v0.9", files: [[822, 11]], requires: [823, 824, 246], modes: ["text2image"] }, { id: "Illustrious-XL-personal-merge-noob-v-pred0.5-test-merge-updated", rubric: "uncurated", name: "Illustrious-XL-personal-merge-noob-v-pred0.5-test-merge-updated", family: "sdxl_base_v0.9", files: [[825, 11]], requires: [826, 827, 246], modes: ["text2image"] }, { id: "inbetweij-no04", rubric: "uncurated", name: "Inbetweij \u2014 No.04", family: "sdxl_base_v0.9", files: [[828, 11], [829, 5]], requires: [830, 831, 246], modes: ["text2image"] }, { id: "Indigo_Void_Furry_Fused_XL_Furry_NoobAI_NoobAI_v1.7_1569147", rubric: "uncurated", name: "Indigo_Void_Furry_Fused_XL_Furry_NoobAI_NoobAI_v1.7_1569147", family: "sdxl_base_v0.9", files: [[832, 11]], requires: [833, 834, 246], modes: ["text2image"] }, { id: "Indigo_Void_Furry_Fused_XL_Furry_NoobAI_NoobAI_v1.8_1731573", rubric: "uncurated", name: "Indigo_Void_Furry_Fused_XL_Furry_NoobAI_NoobAI_v1.8_1731573", family: "sdxl_base_v0.9", files: [[835, 11]], requires: [836, 837, 246], modes: ["text2image"] }, { id: "Indigo-Furry-Mix-XL", rubric: "uncurated", name: "Indigo-Furry-Mix-XL", family: "sdxl_base_v0.9", files: [[838, 11]], requires: [839, 840, 246], modes: ["text2image"] }, { id: "Indigo-Void-Furry-Vpred-Furry-NoobAI-V-pred", rubric: "uncurated", name: "Indigo-Void-Furry-Vpred-Furry-NoobAI-V-pred", family: "sdxl_base_v0.9", files: [[841, 11]], requires: [842, 843, 246], modes: ["text2image"] }, { id: "Iniverse_Mix_SFWNSFW_f1d_Real_Guofeng_Fp8V20", rubric: "uncurated", name: "Iniverse_Mix_SFWNSFW_f1d_Real_Guofeng_Fp8V20", family: "flux1", files: [[844, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Iniverse_Mix_SFWNSFW_f1d_Realnsfw_Guofeng_V2", rubric: "uncurated", name: "Iniverse_Mix_SFWNSFW_f1d_Realnsfw_Guofeng_V2", family: "flux1", files: [[845, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Iniverse_Mix_SFWNSFW_flux1DNsfw_Fp16V12", rubric: "uncurated", name: "Iniverse_Mix_SFWNSFW_flux1DNsfw_Fp16V12", family: "flux1", files: [[846, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Iniverse_Mix_SFWNSFW_flux1DNsfw_Fp8V10", rubric: "uncurated", name: "Iniverse_Mix_SFWNSFW_flux1DNsfw_Fp8V10", family: "flux1", files: [[847, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ionsyx", rubric: "uncurated", name: "Ionsyx", family: "sdxl_base_v0.9", files: [[848, 11]], requires: [849, 850, 246], modes: ["text2image"] }, { id: "Isenganmix_Flux_v_B", rubric: "uncurated", name: "Isenganmix_Flux_v_B", family: "flux1", files: [[851, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib_Mix_Flux_fp16V1", rubric: "uncurated", name: "Jib_Mix_Flux_fp16V1", family: "flux1", files: [[852, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib_Mix_Flux_fp8V2Electric", rubric: "uncurated", name: "Jib_Mix_Flux_fp8V2Electric", family: "flux1", files: [[853, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib_Mix_Flux_fp8V4Canvas_Galore", rubric: "uncurated", name: "Jib_Mix_Flux_fp8V4Canvas_Galore", family: "flux1", files: [[854, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib_Mix_Flux_v72Pixel_Heaven", rubric: "uncurated", name: "Jib_Mix_Flux_v72Pixel_Heaven", family: "flux1", files: [[855, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib_Mix_Flux_v78Clear_Text_Focus", rubric: "uncurated", name: "Jib_Mix_Flux_v78Clear_Text_Focus", family: "flux1", files: [[856, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib_Mix_Flux_v7Pixel_Heaven_Beta", rubric: "uncurated", name: "Jib_Mix_Flux_v7Pixel_Heaven_Beta", family: "flux1", files: [[857, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib_Mix_Flux_v85Consisteight", rubric: "uncurated", name: "Jib_Mix_Flux_v85Consisteight", family: "flux1", files: [[858, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib_Mix_Flux_v8Accentueight_Now", rubric: "uncurated", name: "Jib_Mix_Flux_v8Accentueight_Now", family: "flux1", files: [[859, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib-Mix-Pony-Realistic", rubric: "uncurated", name: "Jib-Mix-Pony-Realistic", family: "sdxl_base_v0.9", files: [[860, 11]], requires: [861, 862, 246], modes: ["text2image"] }, { id: "Jib-Mix-Realistic-XL", rubric: "uncurated", name: "Jib-Mix-Realistic-XL", family: "sdxl_base_v0.9", files: [[863, 11]], requires: [864, 865, 246], modes: ["text2image"] }, { id: "JujuMix", rubric: "uncurated", name: "JujuMix", family: "sdxl_base_v0.9", files: [[866, 11]], requires: [867, 868, 246], modes: ["text2image"] }, { id: "Kageillustrious-Illustrious-XL", rubric: "uncurated", name: "Kageillustrious-Illustrious-XL", family: "sdxl_base_v0.9", files: [[869, 11]], requires: [870, 871, 246], modes: ["text2image"] }, { id: "KantanMIX-XLIllustrious", rubric: "uncurated", name: "KantanMIX-XLIllustrious", family: "sdxl_base_v0.9", files: [[872, 11]], requires: [873, 874, 246], modes: ["text2image"] }, { id: "KFT-Requiem-Fur-a-Dream-Illustrious-Semi-Real-Checkpoint", rubric: "uncurated", name: "KFT-Requiem-Fur-a-Dream-Illustrious-Semi-Real-Checkpoint", family: "sdxl_base_v0.9", files: [[875, 11]], requires: [876, 877, 246], modes: ["text2image"] }, { id: "KonanMix-NoobAI-XL-IllustriousXL", rubric: "uncurated", name: "KonanMix-NoobAI-XL-IllustriousXL", family: "sdxl_base_v0.9", files: [[878, 11]], requires: [879, 880, 246], modes: ["text2image"] }, { id: "koronemix-illustrious", rubric: "uncurated", name: "koronemix-illustrious", family: "sdxl_base_v0.9", files: [[881, 11]], requires: [882, 883, 246], modes: ["text2image"] }, { id: "Lah_Mysterious_Flux_flux_Alpha", rubric: "uncurated", name: "Lah_Mysterious_Flux_flux_Alpha", family: "flux1", files: [[884, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Like-Reality-Pony-by-Ethanar", rubric: "uncurated", name: "Like-Reality-Pony-by-Ethanar", family: "sdxl_base_v0.9", files: [[885, 11]], requires: [886, 887, 246], modes: ["text2image"] }, { id: "Lox_s-Souls-Mix-Prisma-", rubric: "uncurated", name: "Lox_s-Souls-Mix-Prisma-", family: "sdxl_base_v0.9", files: [[888, 11]], requires: [889, 890, 246], modes: ["text2image"] }, { id: "LunarGrapeMix-Illustrious", rubric: "uncurated", name: "LunarGrapeMix-Illustrious", family: "sdxl_base_v0.9", files: [[891, 11]], requires: [892, 893, 246], modes: ["text2image"] }, { id: "Lyh_Anime_Flux_delete", rubric: "uncurated", name: "Lyh_Anime_Flux_delete", family: "flux1", files: [[894, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Madly-Mix-ver-NightNoob", rubric: "uncurated", name: "Madly-Mix-ver-NightNoob", family: "sdxl_base_v0.9", files: [[895, 11]], requires: [896, 897, 246], modes: ["text2image"] }, { id: "Majicflus_v10", rubric: "uncurated", name: "Majicflus_v10", family: "flux1", files: [[898, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "MeichiDarkMix-Reload", rubric: "uncurated", name: "MeichiDarkMix-Reload", family: "sdxl_base_v0.9", files: [[899, 11]], requires: [900, 901, 246], modes: ["text2image"] }, { id: "miruku", rubric: "uncurated", name: "miruku", family: "sdxl_base_v0.9", files: [[902, 11]], requires: [903, 904, 246], modes: ["text2image"] }, { id: "Mistoon-Anime", rubric: "uncurated", name: "Mistoon-Anime", family: "sdxl_base_v0.9", files: [[905, 11]], requires: [906, 907, 246], modes: ["text2image"] }, { id: "Mol-Keun-Mix", rubric: "uncurated", name: "Mol-Keun-Mix", family: "sdxl_base_v0.9", files: [[908, 11]], requires: [909, 910, 246], modes: ["text2image"] }, { id: "MolcajeteMix-NoobIL", rubric: "uncurated", name: "MolcajeteMix-NoobIL", family: "sdxl_base_v0.9", files: [[911, 11]], requires: [912, 913, 246], modes: ["text2image"] }, { id: "Moxie_Flux1DS_flux1D8Step", rubric: "uncurated", name: "Moxie_Flux1DS_flux1D8Step", family: "flux1", files: [[914, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Flux1DS_flux1S8Step", rubric: "uncurated", name: "Moxie_Flux1DS_flux1S8Step", family: "flux1", files: [[915, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Flux1DS_v138Step", rubric: "uncurated", name: "Moxie_Flux1DS_v138Step", family: "flux1", files: [[916, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Flux1DS_v14", rubric: "uncurated", name: "Moxie_Flux1DS_v14", family: "flux1", files: [[917, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Flux1DS_v16D", rubric: "uncurated", name: "Moxie_Flux1DS_v16D", family: "flux1", files: [[918, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Flux1DS_v17S", rubric: "uncurated", name: "Moxie_Flux1DS_v17S", family: "flux1", files: [[919, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_17D", rubric: "uncurated", name: "Moxie_Fusion_Flux_17D", family: "flux1", files: [[920, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v1318step", rubric: "uncurated", name: "Moxie_Fusion_Flux_v1318step", family: "flux1", files: [[921, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v132", rubric: "uncurated", name: "Moxie_Fusion_Flux_v132", family: "flux1", files: [[922, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v1328step", rubric: "uncurated", name: "Moxie_Fusion_Flux_v1328step", family: "flux1", files: [[923, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v1338step", rubric: "uncurated", name: "Moxie_Fusion_Flux_v1338step", family: "flux1", files: [[924, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v134", rubric: "uncurated", name: "Moxie_Fusion_Flux_v134", family: "flux1", files: [[925, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v1348step", rubric: "uncurated", name: "Moxie_Fusion_Flux_v1348step", family: "flux1", files: [[926, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v135", rubric: "uncurated", name: "Moxie_Fusion_Flux_v135", family: "flux1", files: [[927, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v141D", rubric: "uncurated", name: "Moxie_Fusion_Flux_v141D", family: "flux1", files: [[928, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v141S", rubric: "uncurated", name: "Moxie_Fusion_Flux_v141S", family: "flux1", files: [[929, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v15S", rubric: "uncurated", name: "Moxie_Fusion_Flux_v15S", family: "flux1", files: [[930, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v16S", rubric: "uncurated", name: "Moxie_Fusion_Flux_v16S", family: "flux1", files: [[931, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v17S", rubric: "uncurated", name: "Moxie_Fusion_Flux_v17S", family: "flux1", files: [[932, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ms_Flux_SFWNSFWV3_v3", rubric: "uncurated", name: "Ms_Flux_SFWNSFWV3_v3", family: "flux1", files: [[933, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Myhuman_Flux_12Train", rubric: "uncurated", name: "Myhuman_Flux_12Train", family: "flux1", files: [[934, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Myhuman_Flux_myh11", rubric: "uncurated", name: "Myhuman_Flux_myh11", family: "flux1", files: [[935, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Myhuman_Flux_myh13", rubric: "uncurated", name: "Myhuman_Flux_myh13", family: "flux1", files: [[936, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Myhuman_Flux_myh13Fp8", rubric: "uncurated", name: "Myhuman_Flux_myh13Fp8", family: "flux1", files: [[937, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Nepotism_x_Dit", rubric: "uncurated", name: "Nepotism_x_Dit", family: "flux1", files: [[938, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Nepotism_xi_Dit", rubric: "uncurated", name: "Nepotism_xi_Dit", family: "flux1", files: [[939, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Nevolution_SDXL_v2_anim_1733673", rubric: "uncurated", name: "Nevolution_SDXL_v2_anim_1733673", family: "sdxl_base_v0.9", files: [[940, 11]], requires: [941, 942, 246], modes: ["text2image"] }, { id: "Nevolution_SDXL_v2_base_1645671", rubric: "uncurated", name: "Nevolution_SDXL_v2_base_1645671", family: "sdxl_base_v0.9", variant: "base", files: [[943, 11]], requires: [944, 945, 246], modes: ["text2image"] }, { id: "NoobAI-XL-NAI-XL", rubric: "uncurated", name: "NoobAI-XL-NAI-XL", family: "sdxl_base_v0.9", files: [[946, 11]], requires: [947, 948, 246], modes: ["text2image"] }, { id: "NostraMix", rubric: "uncurated", name: "NostraMix", family: "sdxl_base_v0.9", files: [[949, 11]], requires: [950, 951, 246], modes: ["text2image"] }, { id: "Nova_Animal_XL_Illustrious_v3.0_1634769", rubric: "uncurated", name: "Nova_Animal_XL_Illustrious_v3.0_1634769", family: "sdxl_base_v0.9", files: [[952, 11]], requires: [953, 954, 246], modes: ["text2image"] }, { id: "Nova_Animal_XL_v4.0_1028888", rubric: "uncurated", name: "Nova_Animal_XL_v4.0_1028888", family: "sdxl_base_v0.9", files: [[955, 11]], requires: [956, 957, 246], modes: ["text2image"] }, { id: "Nova_Furry_XL_Illustrious_v6A_1625975", rubric: "uncurated", name: "Nova_Furry_XL_Illustrious_v6A_1625975", family: "sdxl_base_v0.9", files: [[958, 11]], requires: [959, 960, 246], modes: ["text2image"] }, { id: "Nova_Furry_XL_Illustrious_v6B_1626156", rubric: "uncurated", name: "Nova_Furry_XL_Illustrious_v6B_1626156", family: "sdxl_base_v0.9", files: [[961, 11]], requires: [962, 963, 246], modes: ["text2image"] }, { id: "Nova_Furry_XL_Illustrious_v7A_1759909", rubric: "uncurated", name: "Nova_Furry_XL_Illustrious_v7A_1759909", family: "sdxl_base_v0.9", files: [[964, 11]], requires: [965, 966, 246], modes: ["text2image"] }, { id: "Nova_Furry_XL_Illustrious_v7B_1760102", rubric: "uncurated", name: "Nova_Furry_XL_Illustrious_v7B_1760102", family: "sdxl_base_v0.9", files: [[967, 11]], requires: [968, 969, 246], modes: ["text2image"] }, { id: "Nova_Orange_XL_v7.0_1525944", rubric: "uncurated", name: "Nova_Orange_XL_v7.0_1525944", family: "sdxl_base_v0.9", files: [[970, 11]], requires: [971, 972, 246], modes: ["text2image"] }, { id: "Nova_Orange_XL_v9.0_1701002", rubric: "uncurated", name: "Nova_Orange_XL_v9.0_1701002", family: "sdxl_base_v0.9", files: [[973, 11]], requires: [974, 975, 246], modes: ["text2image"] }, { id: "Nova-3DCG-XL", rubric: "uncurated", name: "Nova-3DCG-XL", family: "sdxl_base_v0.9", files: [[976, 11]], requires: [977, 978, 246], modes: ["text2image"] }, { id: "Nova-Anime-XL", rubric: "uncurated", name: "Nova-Anime-XL", family: "sdxl_base_v0.9", files: [[979, 11]], requires: [980, 981, 246], modes: ["text2image"] }, { id: "Nova-Anime3D-XL", rubric: "uncurated", name: "Nova-Anime3D-XL", family: "sdxl_base_v0.9", files: [[982, 11]], requires: [983, 984, 246], modes: ["text2image"] }, { id: "Nova-Asian-XL", rubric: "uncurated", name: "Nova-Asian-XL", family: "sdxl_base_v0.9", files: [[985, 11]], requires: [986, 987, 246], modes: ["text2image"] }, { id: "Nova-Cross-XL", rubric: "uncurated", name: "Nova-Cross-XL", family: "sdxl_base_v0.9", files: [[988, 11]], requires: [989, 990, 246], modes: ["text2image"] }, { id: "Nova-Flat-XL", rubric: "uncurated", name: "Nova-Flat-XL", family: "sdxl_base_v0.9", files: [[991, 11]], requires: [992, 993, 246], modes: ["text2image"] }, { id: "Nova-Reality-XL", rubric: "uncurated", name: "Nova-Reality-XL", family: "sdxl_base_v0.9", files: [[994, 11]], requires: [995, 996, 246], modes: ["text2image"] }, { id: "Nova-Unreal-XL", rubric: "uncurated", name: "Nova-Unreal-XL", family: "sdxl_base_v0.9", files: [[997, 11]], requires: [998, 999, 246], modes: ["text2image"] }, { id: "ONE-FOR-ALL-Pony-Fantasy-DPOVAE", rubric: "uncurated", name: "ONE-FOR-ALL-Pony-Fantasy-DPOVAE", family: "sdxl_base_v0.9", files: [[1e3, 11]], requires: [1001, 1002, 246], modes: ["text2image"] }, { id: "Oops-All-Toons-Illustrious-v1.0", rubric: "uncurated", name: "Oops-All-Toons-Illustrious-v1.0", family: "sdxl_base_v0.9", files: [[1003, 11]], requires: [1004, 1005, 246], modes: ["text2image"] }, { id: "Oops-All-vpred-NoobAI-Western-2D-furry-toon", rubric: "uncurated", name: "Oops-All-vpred-NoobAI-Western-2D-furry-toon", family: "sdxl_base_v0.9", files: [[1006, 11]], requires: [1007, 1008, 246], modes: ["text2image"] }, { id: "Origin_By_N0utis_flux_FP8V1", rubric: "uncurated", name: "Origin_By_N0utis_flux_FP8V1", family: "flux1", files: [[1009, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Photonic-Fusion-SDXL", rubric: "uncurated", name: "Photonic-Fusion-SDXL", family: "sdxl_base_v0.9", files: [[1010, 11]], requires: [1011, 1012, 246], modes: ["text2image"] }, { id: "pikon-reality_v2_alt", rubric: "uncurated", name: "Pikon_Realism_v2_alt", family: "sdxl_base_v0.9", files: [[1013, 11], [1014, 5]], requires: [1015, 1016, 246], modes: ["text2image"] }, { id: "Pixelwave_flux1Dev02", rubric: "uncurated", name: "Pixelwave_flux1Dev02", family: "flux1", files: [[1017, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Pixelwave_flux1Dev03", rubric: "uncurated", name: "Pixelwave_flux1Dev03", family: "flux1", files: [[1018, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Pixelwave_flux1Schnell03", rubric: "uncurated", name: "Pixelwave_flux1Schnell03", family: "flux1", files: [[1019, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Plant_Milk_Model_Suite_Flax_1331188", rubric: "uncurated", name: "Plant_Milk_Model_Suite_Flax_1331188", family: "sdxl_base_v0.9", files: [[1020, 11]], requires: [1021, 1022, 246], modes: ["text2image"] }, { id: "Plant_Milk_Model_Suite_Hemp_II_1714314", rubric: "uncurated", name: "Plant_Milk_Model_Suite_Hemp_II_1714314", family: "sdxl_base_v0.9", files: [[1023, 11]], requires: [1024, 1025, 246], modes: ["text2image"] }, { id: "Pony_Realism_v2.1_534642", rubric: "uncurated", name: "Pony_Realism_v2.1_534642", family: "sdxl_base_v0.9", files: [[1026, 11]], requires: [1027, 1028, 246], modes: ["text2image"] }, { id: "Pony_Realism_v2.2_914390", rubric: "uncurated", name: "Pony_Realism_v2.2_914390", family: "sdxl_base_v0.9", files: [[1029, 11]], requires: [1030, 1031, 246], modes: ["text2image"] }, { id: "Praeclarus-IllustriousXL", rubric: "uncurated", name: "Praeclarus-IllustriousXL", family: "sdxl_base_v0.9", files: [[1032, 11]], requires: [1033, 1034, 246], modes: ["text2image"] }, { id: "Prefect_illustrious_XL_v1.0_1379960", rubric: "uncurated", name: "Prefect_illustrious_XL_v1.0_1379960", family: "sdxl_base_v0.9", files: [[1035, 11]], requires: [1036, 1037, 246], modes: ["text2image"] }, { id: "Prefect_illustrious_XL_v1.5_1731647", rubric: "uncurated", name: "Prefect_illustrious_XL_v1.5_1731647", family: "sdxl_base_v0.9", files: [[1038, 11]], requires: [1039, 1040, 246], modes: ["text2image"] }, { id: "Prefect-Pony-XL", rubric: "uncurated", name: "Prefect-Pony-XL", family: "sdxl_base_v0.9", files: [[1041, 11]], requires: [1042, 1043, 246], modes: ["text2image"] }, { id: "Project_Gaia_Flux1D_v10UNET", rubric: "uncurated", name: "Project_Gaia_Flux1D_v10UNET", family: "flux1", files: [[1044, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_real1sm_FP16", rubric: "uncurated", name: "Project0_real1sm_FP16", family: "flux1", files: [[1045, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_real1sm_V2FP16", rubric: "uncurated", name: "Project0_real1sm_V2FP16", family: "flux1", files: [[1046, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_real1sm_V2FP8", rubric: "uncurated", name: "Project0_real1sm_V2FP8", family: "flux1", files: [[1047, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_real1sm_V3FP16", rubric: "uncurated", name: "Project0_real1sm_V3FP16", family: "flux1", files: [[1048, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_real1sm_V3FP8AIO", rubric: "uncurated", name: "Project0_real1sm_V3FP8AIO", family: "flux1", files: [[1049, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_v10FP8Unet_Only", rubric: "uncurated", name: "Project0_v10FP8Unet_Only", family: "flux1", files: [[1050, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_v20FP16", rubric: "uncurated", name: "Project0_v20FP16", family: "flux1", files: [[1051, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_v20FP8", rubric: "uncurated", name: "Project0_v20FP8", family: "flux1", files: [[1052, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_v30Art_FP8", rubric: "uncurated", name: "Project0_v30Art_FP8", family: "flux1", files: [[1053, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ratatoskr_Animal_Creature_v29", rubric: "uncurated", name: "Ratatoskr_Animal_Creature_v29", family: "flux1", files: [[1054, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ratatoskr_Animal_Creature_v40FP8", rubric: "uncurated", name: "Ratatoskr_Animal_Creature_v40FP8", family: "flux1", files: [[1055, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ratatoskr_Animal_Creature_v41", rubric: "uncurated", name: "Ratatoskr_Animal_Creature_v41", family: "flux1", files: [[1056, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ratatoskr_Animal_Creature_v594FP8Dev1Hybrid", rubric: "uncurated", name: "Ratatoskr_Animal_Creature_v594FP8Dev1Hybrid", family: "flux1", files: [[1057, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ratatoskr_Animal_Creature_v667FP16", rubric: "uncurated", name: "Ratatoskr_Animal_Creature_v667FP16", family: "flux1", files: [[1058, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ratatoskr_Animal_Creature_v667FP8", rubric: "uncurated", name: "Ratatoskr_Animal_Creature_v667FP8", family: "flux1", files: [[1059, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ratatoskr-Animal_-Creature-and-Furry-", rubric: "uncurated", name: "Ratatoskr-Animal_-Creature-and-Furry-", family: "sdxl_base_v0.9", files: [[1060, 11]], requires: [1061, 1062, 246], modes: ["text2image"] }, { id: "Rayflux_v10", rubric: "uncurated", name: "Rayflux_v10", family: "flux1", files: [[1063, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Rayflux_v30AIO", rubric: "uncurated", name: "Rayflux_v30AIO", family: "flux1", files: [[1064, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Real_Dream_flux1V1", rubric: "uncurated", name: "Real_Dream_flux1V1", family: "flux1", files: [[1065, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "RealCartoon-XL", rubric: "uncurated", name: "RealCartoon-XL", family: "sdxl_base_v0.9", files: [[1066, 11]], requires: [1067, 1068, 246], modes: ["text2image"] }, { id: "Realflux10b_10b_Compact_Schnell", rubric: "uncurated", name: "Realflux10b_10b_Compact_Schnell", family: "flux1", variant: "turbo", files: [[1069, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Realflux10b_10b_Transformer", rubric: "uncurated", name: "Realflux10b_10b_Transformer", family: "flux1", files: [[1070, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Realflux10b_10b_Transformer_Dev", rubric: "uncurated", name: "Realflux10b_10b_Transformer_Dev", family: "flux1", variant: "dev", files: [[1071, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Realism_By_Stable_Yogi_Pony_V3_VAE_992946", rubric: "uncurated", name: "Realism_By_Stable_Yogi_Pony_V3_VAE_992946", family: "sdxl_base_v0.9", files: [[1072, 11]], requires: [1073, 1074, 246], modes: ["text2image"] }, { id: "Realism_By_Stable_Yogi_v4.0_FP16_1422871", rubric: "uncurated", name: "Realism_By_Stable_Yogi_v4.0_FP16_1422871", family: "sdxl_base_v0.9", files: [[1075, 11]], requires: [1076, 1077, 246], modes: ["text2image"] }, { id: "Realism-SDXL-By-Stable-Yogi", rubric: "uncurated", name: "Realism-SDXL-By-Stable-Yogi", family: "sdxl_base_v0.9", files: [[1078, 11]], requires: [1079, 1080, 246], modes: ["text2image"] }, { id: "Realistic-Blend-XL", rubric: "uncurated", name: "Realistic-Blend-XL", family: "sdxl_base_v0.9", files: [[1081, 11]], requires: [1082, 1083, 246], modes: ["text2image"] }, { id: "Red_Blue_Fantasy_fluxv10", rubric: "uncurated", name: "Red_Blue_Fantasy_fluxv10", family: "flux1", files: [[1084, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_f1Fill_NSFW", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_f1Fill_NSFW", family: "flux1", modifier: "inpainting", files: [[1085, 5]], requires: [200, 115, 201], modes: ["inpaint-model"] }, { id: "Redcraft_CADSUpdated_JUN1_new_REVEAL", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_new_REVEAL", family: "flux1", files: [[1086, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_rasch1Forge", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_rasch1Forge", family: "flux1", files: [[1087, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_rasch2", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_rasch2", family: "flux1", files: [[1088, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_rasch3RUSHReveal", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_rasch3RUSHReveal", family: "flux1", files: [[1089, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_realreveal5", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_realreveal5", family: "flux1", files: [[1090, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_red_Edit_Icedit11", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_red_Edit_Icedit11", family: "flux1", modifier: "inpainting", files: [[1091, 5]], requires: [200, 115, 201], modes: ["inpaint-model"] }, { id: "Redcraft_CADSUpdated_JUN1_red_OMNIFlux1Dreamo", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_red_OMNIFlux1Dreamo", family: "flux1", files: [[1092, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_reveal_NSFW", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_reveal_NSFW", family: "flux1", files: [[1093, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_reveal_ULTRAV35", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_reveal_ULTRAV35", family: "flux1", files: [[1094, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_reveal5SFWULTRA", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_reveal5SFWULTRA", family: "flux1", files: [[1095, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_turbo_Reveal_Hotfix21", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_turbo_Reveal_Hotfix21", family: "flux1", variant: "turbo", files: [[1096, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "RedCraft-CADS-UPdated-May4-Commercial-_-Advertising-Design-System", rubric: "uncurated", name: "RedCraft-CADS-UPdated-May4-Commercial-_-Advertising-Design-System", family: "sdxl_base_v0.9", files: [[1097, 11]], requires: [1098, 1099, 246], modes: ["text2image"] }, { id: "richyrichMixIXL", rubric: "uncurated", name: "richyrichMixIXL", family: "sdxl_base_v0.9", files: [[1100, 11]], requires: [1101, 1102, 246], modes: ["text2image"] }, { id: "Rillusm-Realistic-IL", rubric: "uncurated", name: "Rillusm-Realistic-IL", family: "sdxl_base_v0.9", files: [[1103, 11]], requires: [1104, 1105, 246], modes: ["text2image"] }, { id: "Sdvn11Ghibli_Flux_fp8Hyper", rubric: "uncurated", name: "Sdvn11Ghibli_Flux_fp8Hyper", family: "flux1", files: [[1106, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "SilvermoonMix-Illustrious-Evolved", rubric: "uncurated", name: "SilvermoonMix-Illustrious-Evolved", family: "sdxl_base_v0.9", files: [[1107, 11]], requires: [246, 1108, 1109], modes: ["text2image"] }, { id: "SinGlo-illustrious", rubric: "uncurated", name: "SinGlo-illustrious", family: "sdxl_base_v0.9", files: [[1110, 11]], requires: [246, 1111, 1112], modes: ["text2image"] }, { id: "SkibidiMix", rubric: "uncurated", name: "SkibidiMix", family: "sdxl_base_v0.9", files: [[1113, 11]], requires: [246, 1114, 1115], modes: ["text2image"] }, { id: "Smooth_Mix_NoobAI_Illustrious_Pony_Illustrious_v.2_1401686", rubric: "uncurated", name: "Smooth_Mix_NoobAI_Illustrious_Pony_Illustrious_v.2_1401686", family: "sdxl_base_v0.9", files: [[1116, 11]], requires: [246, 1117, 1118], modes: ["text2image"] }, { id: "Smooth_Mix_NoobAI_Illustrious_Pony_Illustrious_v.3_1470541", rubric: "uncurated", name: "Smooth_Mix_NoobAI_Illustrious_Pony_Illustrious_v.3_1470541", family: "sdxl_base_v0.9", files: [[1119, 11]], requires: [246, 1120, 1121], modes: ["text2image"] }, { id: "Smooth_Mix_NoobAI_Illustrious_Pony_NoobAI_v2.0_1629718", rubric: "uncurated", name: "Smooth_Mix_NoobAI_Illustrious_Pony_NoobAI_v2.0_1629718", family: "sdxl_base_v0.9", files: [[1122, 11]], requires: [246, 1123, 1124], modes: ["text2image"] }, { id: "Smooth_Mix_NoobAI_Illustrious_Pony_Pony_v.3_997031", rubric: "uncurated", name: "Smooth_Mix_NoobAI_Illustrious_Pony_Pony_v.3_997031", family: "sdxl_base_v0.9", files: [[1125, 11]], requires: [246, 1126, 1127], modes: ["text2image"] }, { id: "Smooth_Mix_NoobAI_Illustrious_Pony_Realism_1675843", rubric: "uncurated", name: "Smooth_Mix_NoobAI_Illustrious_Pony_Realism_1675843", family: "sdxl_base_v0.9", files: [[1128, 11]], requires: [246, 1129, 1130], modes: ["text2image"] }, { id: "SnowPony", rubric: "uncurated", name: "SnowPony", family: "sdxl_base_v0.9", files: [[1131, 11]], requires: [246, 1132, 1133], modes: ["text2image"] }, { id: "SteinIllustrious", rubric: "uncurated", name: "SteinIllustrious", family: "sdxl_base_v0.9", files: [[1134, 11]], requires: [246, 1135, 1136], modes: ["text2image"] }, { id: "Stoiqo_Newreality_FLUXSD35_F1DAlpha", rubric: "uncurated", name: "Stoiqo_Newreality_FLUXSD35_F1DAlpha", family: "flux1", files: [[1137, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Stoiqo_Newreality_FLUXSD35_f1DAlpha_Two", rubric: "uncurated", name: "Stoiqo_Newreality_FLUXSD35_f1DAlpha_Two", family: "flux1", files: [[1138, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "STOIQOAfrodite_FLUXXL_F1DAlpha", rubric: "uncurated", name: "STOIQOAfrodite_FLUXXL_F1DAlpha", family: "flux1", files: [[1139, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "The_Araminta_Experiment_flux1A1", rubric: "uncurated", name: "The_Araminta_Experiment_flux1A1", family: "flux1", files: [[1140, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Throwing-Pasta-MIX-Spaghetti", rubric: "uncurated", name: "Throwing-Pasta-MIX-Spaghetti", family: "sdxl_base_v0.9", files: [[1141, 11]], requires: [246, 1142, 1143], modes: ["text2image"] }, { id: "Toonify_Toonify_Illustrious_1495132", rubric: "uncurated", name: "Toonify_Toonify_Illustrious_1495132", family: "sdxl_base_v0.9", files: [[1144, 11]], requires: [246, 1145, 1146], modes: ["text2image"] }, { id: "Toonify_Toonify_PonyDiffusionXL_410539", rubric: "uncurated", name: "Toonify_Toonify_PonyDiffusionXL_410539", family: "sdxl_base_v0.9", files: [[1147, 11]], requires: [246, 1148, 1149], modes: ["text2image"] }, { id: "tt-animerge", rubric: "uncurated", name: "tt-animerge", family: "v1", files: [[1150, 11]], requires: [1151], modes: ["text2image"] }, { id: "Ultra-Realistic-By-Stable-Yogi-Pony", rubric: "uncurated", name: "Ultra-Realistic-By-Stable-Yogi-Pony", family: "sdxl_base_v0.9", files: [[1152, 11]], requires: [246, 1153, 1154], modes: ["text2image"] }, { id: "Ultrareal_Fine_Tune_v1", rubric: "uncurated", name: "Ultrareal_Fine_Tune_v1", family: "flux1", files: [[1155, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ultrareal_Fine_Tune_v10", rubric: "uncurated", name: "Ultrareal_Fine_Tune_v10", family: "flux1", files: [[1156, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ultrareal_Fine_Tune_v20", rubric: "uncurated", name: "Ultrareal_Fine_Tune_v20", family: "flux1", files: [[1157, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ultrareal_Fine_Tune_v4", rubric: "uncurated", name: "Ultrareal_Fine_Tune_v4", family: "flux1", files: [[1158, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "UmbroxPonyXL", rubric: "uncurated", name: "UmbroxPonyXL", family: "sdxl_base_v0.9", files: [[1159, 11]], requires: [246, 1160, 1161], modes: ["text2image"] }, { id: "Uncanny-valley", rubric: "uncurated", name: "Uncanny-valley", family: "sdxl_base_v0.9", files: [[1162, 11]], requires: [246, 1163, 1164], modes: ["text2image"] }, { id: "untitled-pony", rubric: "uncurated", name: "untitled-pony", family: "sdxl_base_v0.9", files: [[1165, 11]], requires: [246, 1166, 1167], modes: ["text2image"] }, { id: "Verus_Vision10b_10b_Transformer", rubric: "uncurated", name: "Verus_Vision10b_10b_Transformer", family: "flux1", files: [[1168, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Virtual-Diffusion-Pony-XL-2025", rubric: "uncurated", name: "Virtual-Diffusion-Pony-XL-2025", family: "sdxl_base_v0.9", files: [[1169, 11]], requires: [246, 1170, 1171], modes: ["text2image"] }, { id: "Vixons-Dream-Weave", rubric: "uncurated", name: "Vixon_s-Dream-Weave", family: "sdxl_base_v0.9", files: [[1172, 11], [1173, 11]], requires: [246, 1174, 1172, 1175], modes: ["text2image"] }, { id: "WAI-SHUFFLE-NOOB", rubric: "uncurated", name: "WAI-SHUFFLE-NOOB", family: "sdxl_base_v0.9", files: [[1176, 11]], requires: [246, 1177, 1178], modes: ["text2image"] }, { id: "Whiteflux1_v10", rubric: "uncurated", name: "Whiteflux1_v10", family: "flux1", files: [[1179, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Xe_Hentai_Anime_FLUX_03", rubric: "uncurated", name: "Xe_Hentai_Anime_FLUX_03", family: "flux1", files: [[1180, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Xe_Hentai_Anime_FLUX_04", rubric: "uncurated", name: "Xe_Hentai_Anime_FLUX_04", family: "flux1", files: [[1181, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Xuer_One_Cyan_Ten_Color_flux_V10", rubric: "uncurated", name: "Xuer_One_Cyan_Ten_Color_flux_V10", family: "flux1", files: [[1182, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "ZavyChromaXL", rubric: "uncurated", name: "ZavyChromaXL", family: "sdxl_base_v0.9", files: [[1183, 11]], requires: [246, 1184, 1185], modes: ["text2image"] }, { id: "ZEP9", rubric: "uncurated", name: "ZEP9", family: "sdxl_base_v0.9", files: [[1186, 11]], requires: [246, 1187, 1188], modes: ["text2image"] }] };
// src/services/modelInventory.ts
var runtimeCatalog = modelZoo_runtime_default;
var asRecord = (v) => v && typeof v === "object" ? v : {};
function decodeJsonBytes(buf) {
if (!buf) return [];
if (Array.isArray(buf)) return buf;
try {
const parsed = JSON.parse(Buffer.from(buf).toString("utf8") || "[]");
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function parseEchoResponse(resp) {
const r = asRecord(resp);
const files = Array.isArray(r.files) ? r.files.filter((f) => typeof f === "string") : [];
const models = decodeJsonBytes(asRecord(r.override).models).map(asRecord).filter((m) => typeof m.file === "string");
return { files, models };
}
var LINE_DROP = /* @__PURE__ */ new Set(["turbo", "fast", "instant", "distilled", "lightning", "schnell", "base", "raw", "exact", "dev", "bf", "bf16", "f16"]);
function modelLine(id) {
return id.toLowerCase().replace(/_/g, "-").split("-").filter((t) => t && !LINE_DROP.has(t)).join("-");
}
function buildInventory(echo, catalog = runtimeCatalog) {
const files = new Set(echo.files);
const specByFile = new Map(echo.models.map((m) => [m.file, m]));
const catalogFiles = /* @__PURE__ */ new Set();
const installed = [];
const byFile = /* @__PURE__ */ new Map();
for (const [rank, m] of catalog.models.entries()) {
const names = m.files.map(([i]) => catalog.files[i]);
names.forEach((n) => catalogFiles.add(n));
const present = names.filter((n) => files.has(n));
if (!present.length) continue;
const precisionRank = Math.max(...m.files.filter(([i]) => files.has(catalog.files[i])).map(([, r]) => r ?? -1));
const missing = (m.requires ?? []).map((i) => catalog.files[i]).filter((n) => !files.has(n));
const entry = {
id: m.id,
rubric: m.rubric,
name: m.name,
family: m.family,
kind: catalog.families[m.family]?.kind ?? "image",
modes: m.modes,
modesUncertain: !!m.modesUncertain,
file: present[0],
installedFiles: present,
missing,
ready: missing.length === 0,
specKnown: present.some((n) => specByFile.has(n)),
deprecated: !!m.deprecated,
rank,
line: modelLine(m.id),
variant: m.variant,
precisionRank,
hasRecommendation: !!m.recommended || !!catalog.families[m.family]?.fallback
};
installed.push(entry);
present.forEach((n) => byFile.set(n, entry));
}
const custom = [];
const customByFile = /* @__PURE__ */ new Map();
for (const spec of echo.models) {
if (catalogFiles.has(spec.file)) continue;
const missing = [spec.text_encoder, spec.autoencoder].filter((n) => typeof n === "string" && n.endsWith(".ckpt") && !files.has(n));
const entry = { name: spec.name ?? spec.file, file: spec.file, family: spec.version ?? "unknown", modifier: spec.modifier, missing, ready: missing.length === 0 };
custom.push(entry);
customByFile.set(spec.file, entry);
}
installed.sort((a, b) => a.family.localeCompare(b.family) || a.id.localeCompare(b.id));
custom.sort((a, b) => a.file.localeCompare(b.file));
const hash = [
...installed.map((m) => `${m.id}|${m.file}|${m.ready ? 1 : 0}|${m.specKnown ? 1 : 0}`),
...custom.map((m) => `custom|${m.file}|${m.ready ? 1 : 0}`)
].join("\n");
return { files, installed, custom, byFile, customByFile, hash };
}
var MODE_TO_CATALOG = {
text2image: "text2image",
txt2img: "text2image",
image2image: "text2image",
img2img: "text2image",
edit: "edit",
inpaint: "edit",
outpaint: "edit",
text2video: "text2video",
txt2vid: "text2video",
image2video: "image2video",
img2vid: "image2video"
};
function catalogModelById(id) {
return runtimeCatalog.models.find((m) => m.id === id);
}
function catalogModeFor(mode) {
return MODE_TO_CATALOG[mode] ?? mode;
}
function supportsMode(modes, mode) {
const wanted = catalogModeFor(mode);
if (modes.includes(wanted)) return true;
return wanted === "text2image" && IMAGE2IMAGE_MODES.has(mode) && modes.includes("edit");
}
var IMAGE2IMAGE_MODES = /* @__PURE__ */ new Set(["image2image", "img2img"]);
function listAvailable(inv, mode) {
return inv.installed.filter((m) => m.ready && supportsMode(m.modes, mode));
}
var SPEED_RANK = { turbo: 3, dev: 2, base: 1 };
function pickFallbackModel(inv, mode, opts = {}) {
const eligible = inv.installed.filter(
(m) => m.ready && !m.deprecated && m.rubric !== "uncurated" && m.hasRecommendation && supportsMode(m.modes, mode) && (!opts.family || m.family === opts.family) && (!opts.accept || opts.accept(m))
);
if (!eligible.length) return null;
const newest = eligible.reduce((a, b) => b.rank < a.rank ? b : a);
const speed = (m) => SPEED_RANK[m.variant ?? ""] ?? 2;
const model = eligible.filter((m) => m.family === newest.family && m.line === newest.line).reduce((a, b) => (speed(b) - speed(a) || b.precisionRank - a.precisionRank || a.rank - b.rank) > 0 ? b : a);
return { model, notes: [] };
}
function stateOfFile(inv, file) {
const model = inv.byFile.get(file);
if (model) return model.ready ? { state: "ready", model } : { state: "requires-missing", model, missing: model.missing };
const custom = inv.customByFile.get(file);
if (custom) return { state: "custom", model: custom };
return { state: "not-installed" };
}
var fileIndex = null;
function catalogModelOfFile(file) {
if (!fileIndex) {
fileIndex = /* @__PURE__ */ new Map();
for (const m of runtimeCatalog.models) for (const [i] of m.files) fileIndex.set(runtimeCatalog.files[i], m);
}
return fileIndex.get(file);
}
function explainFile(inv, file, mode) {
const s = stateOfFile(inv, file);
if (s.state === "not-installed") {
const sibling = catalogModelOfFile(file);
const other = sibling && inv.installed.find((m) => m.id === sibling.id)?.installedFiles[0];
return other ? `'${file}' is not installed (another precision of the same model is: ${other}).` : `'${file}' is not installed.`;
}
if (s.state === "requires-missing") return `'${file}' is installed, but required files are missing: ${s.missing.join(", ")}.`;
if (s.state === "custom") return s.model.ready ? `'${file}' is a custom model (${s.model.family}).` : `'${file}' is a custom model, but required files are missing: ${s.model.missing.join(", ")}.`;
if (mode && !supportsMode(s.model.modes, mode)) {
const alt = listAvailable(inv, mode).slice(0, 3).map((m) => m.id);
return `'${s.model.name}' does not support mode '${mode}' (supports: ${s.model.modes.join(", ")}).${alt.length ? ` Installed alternatives: ${alt.join(", ")}.` : ""}`;
}
return `'${file}' is ready.`;
}
function createInventoryProvider(opts) {
const ttlMs = opts.ttlMs ?? 45e3;
const timeoutMs = opts.timeoutMs ?? 2e3;
const now = opts.now ?? Date.now;
let last = null;
let inflight = null;
const readSnapshot = () => {
if (!opts.snapshotPath) return null;
try {
const raw = JSON.parse(fs2.readFileSync(opts.snapshotPath, "utf8"));
return buildInventory({ files: raw.files ?? [], models: raw.models ?? [] }, opts.catalog);
} catch {
return null;
}
};
const writeSnapshot = (echo) => {
if (!opts.snapshotPath) return;
try {
const models = echo.models.map(({ file, name, version, modifier, text_encoder, autoencoder }) => ({ file, name, version, modifier, text_encoder, autoencoder }));
fs2.mkdirSync(path2.dirname(opts.snapshotPath), { recursive: true });
fs2.writeFileSync(opts.snapshotPath, JSON.stringify({ files: echo.files, models }));
} catch {
}
};
const refresh = async () => {
const started = now();
let timer;
try {
const echo = await Promise.race([
opts.fetchEcho(),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error("inventory timeout")), timeoutMs);
})
]);
const inventory = buildInventory(echo, opts.catalog);
const durationMs = now() - started;
last = { at: now(), inventory, durationMs };
writeSnapshot(echo);
return { inventory, source: "live", stale: false, durationMs };
} catch {
const snap = last?.inventory ?? readSnapshot();
return { inventory: snap, source: snap ? "snapshot" : "none", stale: true, durationMs: null };
} finally {
if (timer) clearTimeout(timer);
}
};
return {
prime(echo, durationMs = 0) {
const inventory = buildInventory(echo, opts.catalog);
last = { at: now(), inventory, durationMs };
writeSnapshot(echo);
return inventory;
},
peek() {
return last?.inventory ?? null;
},
async get() {
if (last && now() - last.at < ttlMs) return { inventory: last.inventory, source: "cache", stale: false, durationMs: last.durationMs };
inflight ??= refresh().finally(() => {
inflight = null;
});
return inflight;
}
};
}
// src/services/modelInventoryRuntime.ts
import path5 from "node:path";
// src/helpers/paths.ts
import fs3 from "fs";
import path3 from "path";
function resolveProjectRootFrom(startDir) {
try {
{
let dir = startDir;
for (let i = 0; i < 50; i++) {
try {
if (fs3.existsSync(path3.join(dir, "manifest.json"))) return dir;
} catch {
}
const parent = path3.dirname(dir);
if (parent === dir) break;
dir = parent;
}
}
{
let dir = startDir;
for (let i = 0; i < 50; i++) {
try {
if (fs3.existsSync(path3.join(dir, "package.json"))) return dir;
} catch {
}
const parent = path3.dirname(dir);
if (parent === dir) break;
dir = parent;
}
}
{
let dir = startDir;
for (let i = 0; i < 30; i++) {
const base = path3.basename(dir);
if (base === "dist" || base === "src") return path3.dirname(dir);
const parent = path3.dirname(dir);
if (parent === dir) break;
dir = parent;
}
}
} catch {
}
return startDir;
}
function getProjectRoot() {
try {
if (fs3.existsSync(path3.join(process.cwd(), "manifest.json"))) {
return process.cwd();
}
} catch {
}
try {
const filePath = typeof __filename !== "undefined" && __filename ? __filename : process.argv && process.argv[1] ? process.argv[1] : process.cwd();
const moduleDir = path3.dirname(filePath);
return resolveProjectRootFrom(moduleDir);
} catch {
return resolveProjectRootFrom(process.cwd());
}
}
function getLogsDir() {
return path3.join(getProjectRoot(), "logs");
}
var cachedPluginLogFilename;
function getPluginLogFilename() {
if (cachedPluginLogFilename !== void 0) return cachedPluginLogFilename;
try {
const raw = fs3.readFileSync(path3.join(getProjectRoot(), "manifest.json"), "utf-8");
const name = JSON.parse(raw)?.name;
if (typeof name === "string" && name.trim()) {
cachedPluginLogFilename = `${name.trim()}-plugin.log`;
return cachedPluginLogFilename;
}
} catch {
}
cachedPluginLogFilename = "generate-image-plugin.log";
return cachedPluginLogFilename;
}
function ensureLogsDir() {
const dir = getLogsDir();
try {
if (!fs3.existsSync(dir)) fs3.mkdirSync(dir, { recursive: true });
} catch {
}
}
// src/services/catalogParams.ts
var RECOMMENDED_KEYS = ["steps", "guidance_scale", "shift", "sampler", "resolution_dependent_shift", "clip_skip"];
function recommendedParamsFor(model) {
const own = model.recommended;
const fallback = runtimeCatalog.families[model.family]?.fallback;
const src = own ? { params: own.params, source: own.source } : fallback ? { params: fallback.params, source: "family-fallback" } : null;
if (!src) return null;
const params = {};
for (const k of RECOMMENDED_KEYS) if (src.params[k] !== void 0) params[k] = src.params[k];
return Object.keys(params).length ? { params, source: src.source } : null;
}
var loraFiles = (overlay) => (Array.isArray(overlay.loras) ? overlay.loras : []).map((l) => l?.file).filter((f) => typeof f === "string" && !!f);
function loraFallbackOverlay(overlay, inv) {
const loras = loraFiles(overlay);
const main = overlay.model;
if (!inv || !loras.length || typeof main !== "string" || !inv.files.has(main)) return null;
const missing = loras.filter((f) => !inv.files.has(f));
const model = catalogModelOfFile(main);
const rec = model && recommendedParamsFor(model);
if (!missing.length || !rec) return null;
const params = { ...overlay, loras: [] };
for (const k of RECOMMENDED_KEYS) delete params[k];
Object.assign(params, rec.params);
const steps = typeof rec.params.steps === "number" ? `, ${rec.params.steps} steps` : "";
return { params, note: `LoRA '${missing[0]}' is not installed; using the model's recommended settings (${rec.source}${steps}) instead of the tuned turbo settings. Expect slower rendering.` };
}
function catalogOverlayFor(key, inv) {
const model = catalogModelById(key) ?? catalogModelOfFile(key);
if (!model) {
const custom = inv?.customByFile.get(key);
return custom ? { params: { model: key }, note: `Custom model '${custom.name}': no recommended settings, engine defaults apply.` } : null;
}
const installed = inv?.installed.find((m) => m.id === model.id);
const file = key.endsWith(".ckpt") && model.files.some(([i]) => runtimeCatalog.files[i] === key) ? key : installed?.file ?? runtimeCatalog.files[model.files[0][0]];
const rec = recommendedParamsFor(model);
return {
params: { model: file, ...rec?.params ?? {} },
note: rec ? `No tuned preset for '${model.id}'; using its recommended settings (${rec.source}).` : `No tuned preset or recommended settings for '${model.id}'; using engine defaults.`
};
}
var OVERLAY_MODE = {
text2image: "txt2img",
image2image: "img2img",
edit: "edit",
inpaint: "edit",
outpaint: "edit",
text2video: "txt2vid",
image2video: "img2vid"
};
function toOverlayMode(mode) {
return OVERLAY_MODE[mode] ?? null;
}
function installedFileOf(file, inv) {
if (!file || !inv || inv.files.has(file)) return { file, substituted: false };
const model = catalogModelOfFile(file);
const installed = model && inv.installed.find((m) => m.id === model.id && m.ready);
return installed ? { file: installed.file, substituted: true } : { file, substituted: false };
}
function withInstalledPrecision(overlay, inv) {
const model = overlay.model;
if (typeof model !== "string") return overlay;
const { file, substituted } = installedFileOf(model, inv);
return substituted ? { ...overlay, model: file } : overlay;
}
function tunedPresetFor(modelId, mode, inv, onlyFile) {
const overlayMode = toOverlayMode(mode) ?? mode;
const model = runtimeCatalog.models.find((m) => m.id === modelId);
const files = new Set(model?.files.map(([i]) => runtimeCatalog.files[i]));
for (const id of MODEL_IDS) {
if (id === "auto" || id === "custom") continue;
const file = getModelFilename(id, overlayMode);
if (!file || !files.has(file)) continue;
const effective = onlyFile ? file === onlyFile ? file : null : installedFileOf(file, inv).file;
if (effective && inv.files.has(effective)) return id;
}
return null;
}
function officialNameFor(name) {
if (name === "auto" || name === "custom") return name;
for (const mode of ["txt2img", "edit", "txt2vid", "img2img", "img2vid"]) {
const file = getModelFilename(name, mode);
const model = file ? catalogModelOfFile(file) : void 0;
if (model) return model.family;
}
return name;
}
// src/catalog/modelAliases.generated.json
var modelAliases_generated_default = {
schema: "dtc.model-aliases.generated.v1",
comment: "Generated by scripts/build-model-catalog.mjs from the public catalog (tag and label of every family). Do not edit; manual additions belong in modelAliases.manual.json.",
sources: {
drawThingsCommunity: "db37e657ad329dd16c2f1200bb47f940369cd9f4",
communityModels: "e9851164709187e7249471701708301842f9f222"
},
aliases: {
auraflow: [
"auraflow"
],
cosmos: [
"cosmos2.5_2b"
],
"cosmos-2-5": [
"cosmos2.5_2b"
],
"cosmos-2-5-2b": [
"cosmos2.5_2b"
],
"cosmos2-5": [
"cosmos2.5_2b"
],
"cosmos2-5-2b": [
"cosmos2.5_2b"
],
ernie: [
"ernie_image"
],
"ernie-image": [
"ernie_image"
],
flux: [
"flux1",
"flux2",
"flux2_4b",
"flux2_9b",
"flux3_5b"
],
"flux-1": [
"flux1"
],
"flux-2": [
"flux2",
"flux2_4b",
"flux2_9b"
],
"flux-2-4b": [
"flux2_4b"
],
"flux-2-9b": [
"flux2_9b"
],
"flux-3": [
"flux3_5b"
],
"flux-3-5b": [
"flux3_5b"
],
flux1: [
"flux1"
],
flux2: [
"flux2",
"flux2_4b",
"flux2_9b"
],
"flux2-4b": [
"flux2_4b"
],
"flux2-9b": [
"flux2_9b"
],
flux3: [
"flux3_5b"
],
"flux3-5b": [
"flux3_5b"
],
hidream: [
"hidream_i1"
],
"hidream-i1": [
"hidream_i1"
],
hunyuan: [
"hunyuan_video"
],
"hunyuan-video": [
"hunyuan_video"
],
ideogram: [
"ideogram_4"
],
"ideogram-4": [
"ideogram_4"
],
kandinsky: [
"kandinsky2.1"
],
"kandinsky-v2-1": [
"kandinsky2.1"
],
"kandinsky2-1": [
"kandinsky2.1"
],
krea: [
"krea_2"
],
"krea-2": [
"krea_2"
],
ltx: [
"ltx2",
"ltx2.3"
],
"ltx-2": [
"ltx2"
],
"ltx-2-3": [
"ltx2.3"
],
ltx2: [
"ltx2"
],
"ltx2-3": [
"ltx2.3"
],
minimax: [
"minimax_h3"
],
"minimax-h3": [
"minimax_h3"
],
moss: [
"moss_image"
],
"moss-image": [
"moss_image"
],
pixart: [
"pixart"
],
"pixart-sigma": [
"pixart"
],
qwen: [
"qwen_image",
"qwen_image_2.1"
],
"qwen-image": [
"qwen_image",
"qwen_image_2.1"
],
"qwen-image-2-1": [
"qwen_image_2.1"
],
sd3: [
"sd3",
"sd3_large"
],
"sd3-large": [
"sd3_large"
],
sdxl: [
"sdxl_base_v0.9",
"sdxl_refiner_v0.9"
],
"sdxl-base": [
"sdxl_base_v0.9"
],
"sdxl-base-v0-9": [
"sdxl_base_v0.9"
],
"sdxl-refiner": [
"sdxl_refiner_v0.9"
],
"sdxl-refiner-v0-9": [
"sdxl_refiner_v0.9"
],
seedvr: [
"seedvr2_3b",
"seedvr2_7b"
],
seedvr2: [
"seedvr2_3b",
"seedvr2_7b"
],
"seedvr2-3b": [
"seedvr2_3b"
],
"seedvr2-7b": [
"seedvr2_7b"
],
segmind: [
"ssd_1b"
],
"segmind-stable": [
"ssd_1b"
],
"segmind-stable-diffusion": [
"ssd_1b"
],
"segmind-stable-diffusion-xl": [
"ssd_1b"
],
"segmind-stable-diffusion-xl-1b": [
"ssd_1b"
],
ssd: [
"ssd_1b"
],
"ssd-1b": [
"ssd_1b"
],
"stable-cascade": [
"wurstchen_v3.0_stage_c"
],
"stable-cascade-w-rstchen": [
"wurstchen_v3.0_stage_c"
],
"stable-cascade-w-rstchen-v3-0": [
"wurstchen_v3.0_stage_c"
],
"stable-diffusion-3": [
"sd3",
"sd3_large"
],
"stable-diffusion-3-large": [
"sd3_large"
],
"stable-diffusion-3-medium": [
"sd3"
],
"stable-diffusion-v1": [
"v1"
],
"stable-diffusion-v2": [
"v2"
],
"stable-diffusion-xl": [
"sdxl_base_v0.9",
"sdxl_refiner_v0.9"
],
"stable-diffusion-xl-base": [
"sdxl_base_v0.9"
],
"stable-diffusion-xl-refiner": [
"sdxl_refiner_v0.9"
],
"stable-video": [
"svd_i2v"
],
"stable-video-diffusion": [
"svd_i2v"
],
svd: [
"svd_i2v"
],
"svd-i2v": [
"svd_i2v"
],
wan: [
"wan_v2.1_1.3b",
"wan_v2.1_14b",
"wan_v2.2_5b"
],
"wan-v2-1": [
"wan_v2.1_1.3b",
"wan_v2.1_14b"
],
"wan-v2-1-1-3b": [
"wan_v2.1_1.3b"
],
"wan-v2-1-14b": [
"wan_v2.1_14b"
],
"wan-v2-2": [
"wan_v2.2_5b"
],
"wan-v2-2-5b": [
"wan_v2.2_5b"
],
"wan-v2-x": [
"wan_v2.1_14b"
],
"wan-v2-x-14b": [
"wan_v2.1_14b"
],
wurstchen: [
"wurstchen_v3.0_stage_c"
],
"wurstchen-v3-0": [
"wurstchen_v3.0_stage_c"
],
"wurstchen-v3-0-stage": [
"wurstchen_v3.0_stage_c"
],
"wurstchen-v3-0-stage-c": [
"wurstchen_v3.0_stage_c"
],
"z-image": [
"z_image"
]
},
agentNames: [
{
name: "AuraFlow",
kind: "family",
scope: "families",
families: [
"auraflow"
],
models: [
"auraflow_v0.2"
],
modes: [
"text2image"
],
keys: [
"auraflow"
]
},
{
name: "Cosmos 2.5",
kind: "family",
scope: "families",
families: [
"cosmos2.5_2b"
],
models: [
"anima-aesthetic-1.1",
"anima-base-1.0",
"anima-turbo-1.0"
],
modes: [
"text2image"
],
keys: [
"cosmos-2-5",
"cosmos2-5"
]
},
{
name: "ERNIE Image",
kind: "family",
scope: "families",
families: [
"ernie_image"
],
models: [
"ernie-image-1.0-exact",
"ernie-image-turbo-1.0-exact",
"ernie_image",
"ernie_image_turbo"
],
modes: [
"text2image"
],
keys: [
"ernie-image"
]
},
{
name: "FLUX.1",
kind: "family",
scope: "families",
families: [
"flux1"
],
models: [
"artsy-vibe-v1",
"chroma-1-hd",
"chroma-v47-detail-calibrated",
"chroma-v48-detail-calibrated",
"devmode-v0.3-turbo",
"flux-1-canny-dev",
"flux-1-depth-dev",
"flux-1-dev",
"flux-1-dev-de-distill",
"flux-1-dev-exact",
"flux-1-fill-dev",
"flux-1-kontext-dev",
"flux-1-kontext-dev-exact",
"flux-1-krea-dev",
"pixelwave-flux-1-schnell-04",
"rayflux-v3.0",
"schnellmode-v3.3",
"shuttle-jaguar",
"shuttle-v3.1-aesthetic",
"flux_1_schnell"
],
modes: [
"text2image",
"edit"
],
keys: [
"flux-1",
"flux1"
]
},
{
name: "FLUX.2",
kind: "family",
scope: "families",
families: [
"flux2",
"flux2_4b",
"flux2_9b"
],
models: [
"flux-2-dev",
"flux-2-dev-exact",
"flux-2-klein-4b-exact",
"flux-2-klein-base-4b-exact",
"flux_2_klein_4b",
"flux_2_klein_base_4b",
"flux-2-klein-9b",
"flux-2-klein-9b-exact",
"flux-2-klein-9b-kv",
"flux-2-klein-9b-kv-exact",
"flux-2-klein-base-9b",
"flux-2-klein-base-9b-exact"
],
modes: [
"text2image",
"image2image",
"edit"
],
keys: [
"flux-2",
"flux2"
]
},
{
name: "FLUX.3",
kind: "family",
scope: "families",
families: [
"flux3_5b"
],
models: [
"flux-3-klein",
"flux-3-klein-base",
"flux-3-klein-base-exact",
"flux-3-klein-exact"
],
modes: [
"text2image",
"edit"
],
keys: [
"flux-3",
"flux3"
]
},
{
name: "HiDream I1",
kind: "family",
scope: "families",
families: [
"hidream_i1"
],
models: [
"hidream-e1-1-exact",
"hidream-i1-dev-exact",
"hidream-i1-fast-exact",
"hidream-i1-full-exact",
"hidream_e1_1",
"hidream_e1_full",
"hidream_i1_dev",
"hidream_i1_fast",
"hidream_i1_full"
],
modes: [
"text2image",
"edit"
],
keys: [
"hidream-i1"
]
},
{
name: "Hunyuan Video",
kind: "family",
scope: "families",
families: [
"hunyuan_video"
],
models: [
"hunyuan-video-t2v-720p",
"skyreels-v1-hunyuan-i2v-544p",
"skyreels-v1-hunyuan-t2v-544p"
],
modes: [
"text2video",
"image2video"
],
keys: [
"hunyuan-video"
]
},
{
name: "Ideogram 4",
kind: "family",
scope: "families",
families: [
"ideogram_4"
],
models: [
"ideogram-4",
"ideogram-4-fast",
"ideogram-4-instant"
],
modes: [
"text2image"
],
keys: [
"ideogram-4",
"ideogram4"
]
},
{
name: "Krea 2",
kind: "family",
scope: "families",
families: [
"krea_2"
],
models: [
"krea-2-raw",
"krea-2-turbo"
],
modes: [
"text2image",
"image2image"
],
keys: [
"krea-2",
"krea2"
]
},
{
name: "LTX-2",
kind: "family",
scope: "families",
families: [
"ltx2"
],
models: [
"ltx_2_19b_dev",
"ltx_2_19b_distilled"
],
modes: [
"text2video",
"image2video"
],
keys: [
"ltx-2",
"ltx2"
]
},
{
name: "LTX-2.3",
kind: "family",
scope: "families",
families: [
"ltx2.3"
],
models: [
"ltx-2.3-22b-dev-exact",
"ltx-2.3-22b-distilled-exact",
"ltx_2.3_22b_dev",
"ltx_2.3_22b_distilled_1.1"
],
modes: [
"text2video",
"image2video"
],
keys: [
"ltx-2-3",
"ltx2-3"
]
},
{
name: "MOSS Image",
kind: "family",
scope: "families",
families: [
"moss_image"
],
models: [
"moss_image_base",
"moss_image_sft"
],
modes: [
"text2image"
],
keys: [
"moss-image"
]
},
{
name: "PixArt Sigma",
kind: "family",
scope: "families",
families: [
"pixart"
],
models: [
"pixart_sigma_xl_2_1024_ms",
"pixart_sigma_xl_2_512_ms"
],
modes: [
"text2image"
],
keys: [
"pixart-sigma"
]
},
{
name: "Qwen Image",
kind: "family",
scope: "families",
families: [
"qwen_image"
],
models: [
"qwen-image-1.0-bf-exact",
"qwen-image-1.0-exact",
"qwen-image-2512-bf-exact",
"qwen-image-edit-2509-bf-exact",
"qwen-image-edit-2509-exact",
"qwen_image_1.0",
"qwen_image_1.0_bf16",
"qwen_image_2512",
"qwen_image_2512_bf16",
"qwen_image_edit_1.0",
"qwen_image_edit_2509",
"qwen_image_edit_2509_bf16",
"qwen_image_edit_2511",
"qwen_image_edit_2511_bf16",
"qwen_image_layered_1.0",
"qwen_image_layered_1.0_bf16"
],
modes: [
"text2image",
"image2image",
"edit"
],
keys: [
"qwen-image"
]
},
{
name: "Qwen Image 2.1",
kind: "family",
scope: "families",
families: [
"qwen_image_2.1"
],
models: [
"qwen-image-2.1",
"qwen-image-2.1-exact",
"qwen-image-2.1-turbo",
"qwen-image-2.1-turbo-exact"
],
modes: [
"text2image",
"edit"
],
keys: [
"qwen-image-2-1"
]
},
{
name: "Stable Diffusion 3 Medium",
kind: "family",
scope: "families",
families: [
"sd3"
],
models: [
"sd3-medium",
"sd3-medium-3.5"
],
modes: [
"text2image"
],
keys: [
"stable-diffusion-3-medium"
]
},
{
name: "Stable Diffusion 3 Large",
kind: "family",
scope: "families",
families: [
"sd3_large"
],
models: [
"sd3-large-3.5",
"sd3-large-3.5-exact",
"sd3-large-turbo-3.5"
],
modes: [
"text2image"
],
keys: [
"stable-diffusion-3-large"
]
},
{
name: "Stable Diffusion XL Base",
kind: "family",
scope: "families",
families: [
"sdxl_base_v0.9"
],
models: [
"animagine-xl",
"colorfulxl-v6.0",
"dreamshaper-xl-v2.1-turbo",
"icatcher-cartoon",
"icatcher-realistic",
"juggernaut-xl-ragnarok",
"juggernaut-xl-v9",
"juggernaut-xl-v9-lightning",
"juggernaut-xl-x",
"kwai-kolors-1.0",
"kwai-kolors-inpainting-1.0",
"pixelwave-v10",
"pixelwave-v9",
"playground-v2",
"playground-v2.5",
"proteus-v0.3",
"realvisxl-v4.0",
"sdxl-turbo",
"fooocus_inpaint_sd_xl_v2.6",
"fooocus_inpaint_sd_xl_v2.6_q6p",
"sd_xl_base_1.0",
"sd_xl_base_1.0_q6p"
],
modes: [
"text2image"
],
keys: [
"stable-diffusion-xl-base"
]
},
{
name: "Stable Diffusion XL Refiner",
kind: "family",
scope: "families",
families: [
"sdxl_refiner_v0.9"
],
models: [
"sd_xl_refiner_1.0",
"sd_xl_refiner_1.0_q6p"
],
modes: [
"text2image"
],
keys: [
"stable-diffusion-xl-refiner"
]
},
{
name: "Segmind Stable Diffusion XL",
kind: "family",
scope: "families",
families: [
"ssd_1b"
],
models: [
"ssd-1b"
],
modes: [
"text2image"
],
keys: [
"segmind-stable-diffusion-xl"
]
},
{
name: "Stable Video Diffusion",
kind: "family",
scope: "families",
families: [
"svd_i2v"
],
models: [
"animatelcm-svd-xt-v1.1",
"svd-v1.0",
"svd-xt-v1.1"
],
modes: [
"image2video"
],
keys: [
"stable-video-diffusion"
]
},
{
name: "Stable Diffusion v1",
kind: "family",
scope: "families",
families: [
"v1"
],
models: [
"aloeveras-simpmaker-3k1",
"analog-v1",
"anything-v3",
"arcane-v3",
"balloon-art-v1",
"classic-animation-v1",
"counterfeit-v3.0",
"cyberpunk-anime",
"deliberate-v2.0",
"disney-pixar-cartoon-type-b",
"dnd-classes-and-species",
"dreamshaper-v8",
"dungeons-and-diffusion-30000",
"elden-ring-v3",
"f222",
"ghibli-v1",
"ha-3dkx-1.1",
"hassanblend-v1.5.1.2",
"inkpunk-v2",
"juggernaut-reborn",
"majicmix-realistic-v7",
"modern-disney-v1",
"multi-style-nitro-diffusion-v1",
"ootd-vton-full-body-v1",
"ootd-vton-upper-body-v1",
"openjourney",
"paper-cut-v1",
"realistic-vision-v5.1",
"redshift-v1",
"rev-animated-v1.22",
"samdoesart-v3",
"seek.art-mega-v1",
"spider-verse-v1",
"super-mario-nation-v2",
"tron-legacy",
"van-gogh-style-lvngvncnt-v2",
"voxelart-v1",
"waifu-diffusion-v1.3",
"sd_v1.5",
"sd_v1.5_inpainting"
],
modes: [
"text2image",
"edit"
],
keys: [
"stable-diffusion-v1"
]
},
{
name: "Stable Diffusion v2",
kind: "family",
scope: "families",
families: [
"v2"
],
models: [
"readshift-768",
"sd_v2.0_depth",
"sd_v2.0_inpainting",
"sd_v2.1",
"sd_v2.1_768_v"
],
modes: [
"text2image"
],
keys: [
"stable-diffusion-v2"
]
},
{
name: "Wan v2.1",
kind: "family",
scope: "families",
families: [
"wan_v2.1_1.3b"
],
models: [
"skyreels-v2-1.3b-i2v-540p",
"wan-2.1-1.3b-fun-inp",
"wan-2.1-1.3b-v1.1-fun-inp",
"wan_v2.1_1.3b_480p"
],
modes: [
"text2video",
"image2video"
],
keys: [
"wan-v2-1"
]
},
{
name: "Wan v2.x",
kind: "family",
scope: "families",
families: [
"wan_v2.1_14b"
],
models: [
"anisora-v3.2-i2v-wan-2.2-a14b-hne",
"anisora-v3.2-i2v-wan-2.2-a14b-lne",
"chronoedit-14b",
"skyreels-v2-14b-i2v-540p",
"skyreels-v2-14b-i2v-720p",
"skyreels-v2-14b-t2v-540p",
"skyreels-v2-14b-t2v-720p",
"wan-2.1-14b-fun-inp",
"wan-2.1-14b-i2v-fusionx",
"wan-2.1-14b-t2v-fusionx",
"wan-2.1-14b-v1.1-fun-inp",
"wan-v2.2-a14b-hne-t2v-lightning-250928",
"wan_v2.1_14b_720p",
"wan_v2.1_14b_i2v_480p",
"wan_v2.1_14b_i2v_720p",
"wan_v2.2_a14b_hne_i2v",
"wan_v2.2_a14b_hne_t2v",
"wan_v2.2_a14b_lne_i2v",
"wan_v2.2_a14b_lne_t2v"
],
modes: [
"text2video",
"image2video"
],
keys: [
"wan-v2-x"
]
},
{
name: "Wan v2.2",
kind: "family",
scope: "families",
families: [
"wan_v2.2_5b"
],
models: [
"wan_v2.2_5b_ti2v"
],
modes: [
"text2video",
"image2video"
],
keys: [
"wan-v2-2"
]
},
{
name: "Stable Cascade (W\xFCrstchen v3.0)",
kind: "family",
scope: "families",
families: [
"wurstchen_v3.0_stage_c"
],
models: [
"stable-cascade"
],
modes: [
"text2image"
],
keys: [
"stable-cascade-w-rstchen-v3-0"
]
},
{
name: "Z Image",
kind: "family",
scope: "families",
families: [
"z_image"
],
models: [
"z-image-1.0-exact",
"z-image-turbo-1.0-exact",
"z_image_1.0",
"z_image_turbo_1.0"
],
modes: [
"text2image",
"image2image"
],
keys: [
"z-image"
]
},
{
name: "MiniMax H3",
kind: "family",
scope: "models",
families: [
"minimax_h3"
],
models: [
"minimax-h3-fl2va"
],
modes: [
"text2video",
"image2video"
],
keys: [
"minimax-h3"
]
},
{
name: "MiniMax H3 [ref2va]",
kind: "family",
scope: "models",
families: [
"minimax_h3"
],
models: [
"minimax-h3-ref2va"
],
modes: [
"text2video",
"image2video"
],
keys: [
"minimax-h3-ref2va"
]
},
{
name: "Qwen Image Edit",
kind: "supplement",
scope: "models",
families: [],
models: [
"qwen_image_edit_2511",
"qwen_image_edit_2509"
],
modes: [
"image2image",
"edit"
],
keys: [
"qwen-image-edit"
]
}
]
};
// src/catalog/modelAliases.manual.json
var modelAliases_manual_default = {
schema: "dtc.model-aliases.manual.v1",
comment: 'Our additions, NOT from public sources. Edited by hand; scripts/build-model-catalog.mjs never writes this file. An entry wins over a generated alias with the same normalized name. `kind`: `spelling` = another spelling or legacy name of something the public catalog already names (the official name is taken from the catalog; no `label` allowed). `supplement` = closes a gap in the public catalog and needs a plain-text `label`, like an official family has. `families` are family tags (ModelZoo `version`), `models` are catalog model ids. `legacy: true` = accepted, but never named in lists or error answers for the agent. `agentNames` overrides the name the agent is told when the official name is unusable or one family must be split: [{ "name": "Wan 2.x", "families": ["wan_v2.1_14b"] }] renames a family, [{ "name": "MiniMax H3", "models": ["minimax-h3-fl2va"] }] names single models (a family with model-level names is described by those names only). By default the official name without a trailing size is used. An entry may list several spellings in `aliases` instead of one `alias`. Spec: draw-things-chat/instructions/development/model-used-family-resolution_v3.md',
agentNames: [
{ name: "MiniMax H3", models: ["minimax-h3-fl2va"], note: "ModelZoo has one family `minimax_h3`; fl2va and ref2va differ functionally, so the agent gets them separately. Other models of the family (FastH3 Omni) stay reachable by name or file." },
{ name: "MiniMax H3 [ref2va]", tag: "minimax_h3_ref2va", models: ["minimax-h3-ref2va"], note: "Our own tag: the overlay is named after it (minimax_h3_ref2vaParamsDrawThings.ts)." }
],
aliases: [
{
alias: "flux",
kind: "spelling",
families: ["flux3_5b", "flux2_9b", "flux2_4b", "flux2"],
legacy: true,
note: "FLUX.3 first, then FLUX.2 klein, then FLUX.2 dev. Excludes flux1 (Chroma and FLUX.1 fine-tunes), which the generated alias would include. Until 2026-11 `flux` meant FLUX.2 [klein] 9B."
},
{
alias: "flux-3-klein",
kind: "spelling",
families: ["flux3_5b"],
legacy: true,
note: "Old preset name."
},
{
alias: "krea2",
kind: "spelling",
families: ["krea_2"],
legacy: true,
note: "Old preset name."
},
{
alias: "qwen-image-2.1-turbo",
kind: "spelling",
models: ["qwen-image-2.1-turbo"],
legacy: true,
note: "Old preset name for the Turbo model of Qwen Image 2.1."
},
{
alias: "qwen-edit",
kind: "supplement",
label: "Qwen Image Edit",
models: ["qwen_image_edit_2511", "qwen_image_edit_2509"],
legacy: true,
note: "Not a family in ModelZoo: Qwen Image Edit is a model of `qwen_image`. Without this entry qwen_image_edit_2511_q6p.ckpt is hard to reach by name."
},
{
aliases: ["minimax", "minimax-h3", "minimax-h3-fl", "minimax-fl", "minimax-fl2va", "minimax-h3-fl2va"],
kind: "spelling",
models: ["minimax-h3-fl2va"],
legacy: true,
note: "MiniMax H3 (first/last-frame variant, fl2va). `minimax` is the old preset name; `minimax-h3` would otherwise mean the whole family."
},
{
aliases: ["minimax-h3-ref", "minimax-ref", "minimax-ref2va", "minimax-h3-ref2va"],
kind: "spelling",
models: ["minimax-h3-ref2va"],
legacy: true,
note: "MiniMax H3 [ref2va] (reference-image variant). `minimax-ref` is the old preset name."
}
]
};
// src/services/modelAliases.ts
var normalizeModelName = (s) => s.toLowerCase().replace(/\.ckpt$/, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
var generated = modelAliases_generated_default;
var manual = modelAliases_manual_default;
var AGENT_NAMES = generated.agentNames;
var manualIndex = null;
var agentIndex = null;
var familyNames = null;
var modelNames = null;
function buildIndexes() {
manualIndex = /* @__PURE__ */ new Map();
for (const a of manual.aliases) {
for (const alias of [a.alias, ...a.aliases ?? []]) {
if (!alias) continue;
manualIndex.set(normalizeModelName(alias), { label: alias, families: a.families ?? [], models: a.models ?? [], legacy: !!a.legacy });
}
}
agentIndex = /* @__PURE__ */ new Map();
familyNames = /* @__PURE__ */ new Map();
modelNames = /* @__PURE__ */ new Map();
for (const e of AGENT_NAMES) {
const byModel = e.scope === "models";
const target2 = { label: e.name, families: byModel ? [] : e.families, models: byModel ? e.models : [], legacy: false, exclusive: true };
for (const key of [normalizeModelName(e.name), ...e.keys]) agentIndex.set(key, target2);
if (byModel) for (const id of e.models) modelNames.set(id, e.name);
else for (const tag of e.families) familyNames.set(tag, e.name);
}
}
function manualAlias(n) {
if (!manualIndex) buildIndexes();
return manualIndex.get(n) ?? null;
}
function agentNameTarget(n) {
if (!agentIndex) buildIndexes();
return agentIndex.get(n) ?? null;
}
function generatedAlias(n) {
const families = generated.aliases[n];
return families?.length ? { label: n, families, models: [], legacy: false } : null;
}
var belongsTo = (t, m) => t.models.includes(m.id) || t.families.includes(m.family);
function familyAgentName(tag) {
if (!familyNames) buildIndexes();
return familyNames.get(tag) ?? null;
}
function agentNameOfModel(m) {
if (!modelNames) buildIndexes();
return modelNames.get(m.id) ?? familyNames.get(m.family);
}
function agentNameOfFamily(tag) {
if (!familyNames) buildIndexes();
return familyNames.get(tag) ?? runtimeCatalog.families[tag]?.label ?? tag;
}
// src/services/customConfigsLoader.ts
import fs4 from "fs";
import path4 from "path";
import os from "os";
var MODE_ALIASES = {
text2image: "txt2img",
t2i: "txt2img",
txt2img: "txt2img",
image2image: "img2img",
i2i: "img2img",
img2img: "img2img",
edit: "edit",
zoom: "zoom",
restore: "restore",
text2video: "txt2vid",
t2v: "txt2vid",
txt2vid: "txt2vid",
image2video: "img2vid",
i2v: "img2vid",
img2vid: "img2vid"
};
var USER_MODE_NAME = {
txt2img: "text2image",
img2img: "image2image",
edit: "edit",
zoom: "zoom",
restore: "restore",
txt2vid: "text2video",
img2vid: "image2video"
};
var cachedPresets = null;
var configFilePath = null;
var didWarnCacheUninitialized = false;
var didLogUsingPreset = /* @__PURE__ */ new Set();
function isVerboseCustomConfigsLoggingEnabled() {
try {
return process?.env?.DTC_CUSTOM_CONFIGS_VERBOSE === "1";
} catch {
return false;
}
}
function getPresetsCacheOrNull() {
if (cachedPresets === null && !configFilePath) {
cachedPresets = /* @__PURE__ */ new Map();
}
return cachedPresets;
}
function getConfiguredCustomConfigsPath() {
return configFilePath;
}
async function checkCustomConfigs(customPath) {
try {
cachedPresets = null;
const rawPath = typeof customPath === "string" ? customPath.trim() : "";
if (!rawPath) {
configFilePath = null;
cachedPresets = /* @__PURE__ */ new Map();
didWarnCacheUninitialized = false;
return {
available: false,
filePath: null
};
}
const expandedPath = rawPath.startsWith("~") ? path4.join(os.homedir(), rawPath.slice(1)) : rawPath;
configFilePath = expandedPath;
didWarnCacheUninitialized = false;
await fs4.promises.access(expandedPath, fs4.constants.R_OK);
return {
available: true,
filePath: expandedPath
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error";
return {
available: false,
filePath: null,
error: errorMessage
};
}
}
async function loadCustomConfigs() {
if (cachedPresets !== null) {
return cachedPresets;
}
const presets = /* @__PURE__ */ new Map();
try {
if (!configFilePath) {
cachedPresets = presets;
return presets;
}
const fileContent = await fs4.promises.readFile(configFilePath, "utf-8");
const rawPresets = JSON.parse(fileContent);
if (!Array.isArray(rawPresets)) {
console.warn(
"[CustomConfigs] Expected array of presets, got:",
typeof rawPresets
);
cachedPresets = presets;
return presets;
}
for (const rawPreset of rawPresets) {
try {
const preset = parsePreset(rawPreset);
if (preset) {
presets.set(preset.name, preset);
}
} catch (error) {
}
}
if (presets.size > 0) {
const presetNames = Array.from(presets.keys()).join(", ");
console.log(
`[CustomConfigs] Loaded ${presets.size} presets: ${presetNames}`
);
} else {
console.log(
`[CustomConfigs] No valid presets found in ${configFilePath}`
);
}
} catch (error) {
console.warn(
"[CustomConfigs] Failed to load custom_configs.json:",
error instanceof Error ? error.message : error
);
}
cachedPresets = presets;
didWarnCacheUninitialized = false;
return presets;
}
function convertParamNames(config) {
const converted = {};
for (const [key, value] of Object.entries(config)) {
const snakeKey = key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase();
if (Array.isArray(value)) {
converted[snakeKey] = value.map(
(item) => typeof item === "object" && item !== null ? convertParamNames(item) : item
);
} else if (typeof value === "object" && value !== null) {
converted[snakeKey] = convertParamNames(value);
} else {
converted[snakeKey] = value;
}
}
return converted;
}
function parsePreset(rawPreset) {
const { name, configuration } = rawPreset;
if (!name || typeof name !== "string") {
console.warn("[CustomConfigs] Preset missing name field");
return null;
}
const dotIdx = name.indexOf(".");
if (dotIdx <= 0 || dotIdx === name.length - 1) {
return null;
}
const modeRaw = name.slice(0, dotIdx);
const modelId = name.slice(dotIdx + 1);
const mode = MODE_ALIASES[modeRaw.trim().toLowerCase()];
if (!mode) {
return null;
}
const convertedConfig = convertParamNames(configuration);
const params = convertedConfig;
return {
// Stored under the spelled-out mode so that lookups work for every accepted spelling.
name: `${USER_MODE_NAME[mode]}.${modelId}`,
mode,
modelId,
params
};
}
function getCustomPreset(notation) {
const cache = getPresetsCacheOrNull();
if (!cache) {
if (!didWarnCacheUninitialized) {
console.warn(
"[CustomConfigs] Cache not initialized, call loadCustomConfigs() first"
);
didWarnCacheUninitialized = true;
}
return null;
}
return cache.get(notation) ?? null;
}
function findCustomPresetsByModelFile(mode, files) {
const cache = getPresetsCacheOrNull();
if (!cache) return [];
const internal = MODE_ALIASES[mode.trim().toLowerCase()] ?? (mode === "inpaint" || mode === "outpaint" ? "edit" : void 0);
if (!internal) return [];
const wanted = new Set([...files].map((f) => path4.basename(f).trim().toLowerCase()));
return [...cache.values()].filter((p) => {
const model = p.params.model;
return p.mode === internal && typeof model === "string" && wanted.has(path4.basename(model).trim().toLowerCase());
}).sort((a, b) => a.modelId.localeCompare(b.modelId));
}
function clearCustomConfigsCache() {
cachedPresets = null;
configFilePath = null;
didWarnCacheUninitialized = false;
didLogUsingPreset = /* @__PURE__ */ new Set();
}
function getEffectiveOverlay(modelId, mode) {
const normalizedModelId = modelId?.trim() ? modelId.trim() : void 0;
const cache = getPresetsCacheOrNull();
if (cache) {
const effectiveModelId = normalizedModelId ? normalizeModelId(normalizedModelId) : "auto";
const notation = buildPresetNotation(mode, effectiveModelId);
const verbose = isVerboseCustomConfigsLoggingEnabled();
if (verbose) {
console.debug(
`[CustomConfigs] getEffectiveOverlay: modelId=${effectiveModelId}, mode=${mode}, notation=${notation}, cacheSize=${cache.size}`
);
}
const familyTag = officialNameFor(effectiveModelId);
const presetNames = [.../* @__PURE__ */ new Set([normalizedModelId ?? effectiveModelId, effectiveModelId, ...legacyNamesOf(effectiveModelId), familyTag])];
let customPreset = null;
for (const name of presetNames) {
customPreset = getCustomPreset(buildPresetNotation(mode, name));
if (customPreset) break;
}
const byFile = !customPreset && normalizedModelId?.toLowerCase().endsWith(".ckpt") ? findCustomPresetsByModelFile(mode, [normalizedModelId])[0] : void 0;
if (byFile) return { source: "custom", presetName: byFile.name, params: byFile.params };
if (customPreset) {
if (verbose && !didLogUsingPreset.has(notation)) {
console.info(`[CustomConfigs] Using custom preset '${notation}'`);
didLogUsingPreset.add(notation);
}
return {
source: "custom",
presetName: customPreset.name,
params: customPreset.params
};
} else {
if (verbose) {
console.debug(
`[CustomConfigs] Custom preset '${notation}' not found, falling back to model overlay`
);
}
}
} else {
if (configFilePath && !didWarnCacheUninitialized) {
console.warn(
`[CustomConfigs] cachedPresets is null (loadCustomConfigs() was not called or failed)`
);
didWarnCacheUninitialized = true;
}
}
const isPreset = !!normalizedModelId && MODEL_IDS.includes(normalizeModelId(normalizedModelId));
let overlayId = normalizedModelId;
if (normalizedModelId && !isPreset && normalizedModelId !== "auto" && mode !== "zoom" && mode !== "restore") {
const tunedId = normalizedModelId.toLowerCase().endsWith(".ckpt") ? MODEL_IDS.find((id) => id !== "auto" && id !== "custom" && getModelOverlay(id, mode)?.model === normalizedModelId) : void 0;
if (tunedId) overlayId = tunedId;
else {
const fromCatalog = catalogOverlayFor(normalizedModelId, peekInventory());
if (fromCatalog) return { source: "catalog", note: fromCatalog.note, params: fromCatalog.params };
}
}
const modelOverlay = getModelOverlay(overlayId, mode);
if (modelOverlay) {
const tuned = withInstalledPrecision(modelOverlay, peekInventory());
const fallback = loraFallbackOverlay(tuned, peekInventory());
if (fallback) return { source: "recommended", note: fallback.note, params: fallback.params };
return {
source: "modelOverlay",
params: tuned
};
}
return {
source: "default",
params: null
};
}
function buildPresetNotation(mode, modelId) {
return `${USER_MODE_NAME[mode]}.${modelId}`;
}
function getAvailableCustomCombinations() {
const cache = getPresetsCacheOrNull();
if (!cache) return [];
const combinations = [];
for (const preset of cache.values()) {
if (preset.mode === "zoom" || preset.mode === "restore") continue;
combinations.push([USER_MODE_NAME[preset.mode], preset.modelId]);
}
return combinations;
}
function getCustomPresetLabelsUsingModelFilename(modelFilenameOrPath) {
const cache = getPresetsCacheOrNull();
if (!cache) return [];
if (typeof modelFilenameOrPath !== "string") return [];
const wanted = path4.basename(modelFilenameOrPath).trim().toLowerCase();
if (!wanted) return [];
const labels = /* @__PURE__ */ new Set();
for (const preset of cache.values()) {
const presetModel = preset.params?.model;
if (typeof presetModel !== "string") continue;
const presetBase = path4.basename(presetModel).trim().toLowerCase();
if (presetBase === wanted) {
labels.add(preset.name);
}
}
return Array.from(labels).sort();
}
// src/services/image2imagePolicy.ts
var isImage2ImageMode = (mode) => mode === "image2image" || mode === "img2img";
function image2imagePresetOf(model, inv, onlyFile) {
const user = findCustomPresetsByModelFile("image2image", onlyFile ? [onlyFile] : model.installedFiles)[0];
if (user) return { kind: "user", preset: user };
const ours = tunedPresetFor(model.id, "image2image", inv, onlyFile);
return ours ? { kind: "ours", preset: ours } : null;
}
function listImage2ImageModels(inv) {
return inv.installed.filter((m) => m.ready && !m.deprecated && m.rubric !== "uncurated" && image2imagePresetOf(m, inv));
}
function image2imageAlternatives(inv) {
const names = [...new Set(listImage2ImageModels(inv).map((m) => m.name))].slice(0, 5);
return names.length ? `image2image is available for: ${names.join(", ")}.` : "No installed model has an image2image preset.";
}
function image2imageUnavailable(subject, inv) {
return `${subject} has no image2image preset (a preset with a tuned strength). ${image2imageAlternatives(inv)}`;
}
// src/services/agentNames.ts
var AGENT_MODE_ORDER = ["text2image", "image2image", "edit", "text2video", "image2video"];
function installedAgentNames(inv, mode) {
const byName = /* @__PURE__ */ new Map();
for (const m of [...inv.installed].sort((a, b) => a.rank - b.rank)) {
if (!m.ready || m.deprecated || m.rubric === "uncurated") continue;
const kind = runtimeCatalog.families[m.family]?.kind;
if (kind === "upscaler") continue;
const name = agentNameOfModel(m);
if (!name) continue;
const entryOf = (n) => byName.get(n) ?? byName.set(n, { kind: kind === "video" ? "video" : "image", modes: /* @__PURE__ */ new Set() }).get(n);
const own = entryOf(name);
m.modes.forEach((x) => x !== "image2image" && own.modes.add(x));
if (image2imagePresetOf(m, inv)) own.modes.add("image2image");
const familyName = familyAgentName(m.family);
if (familyName && familyName !== name) {
const fam = entryOf(familyName);
for (const x of AGENT_MODE_ORDER) if (x === "image2image" ? image2imagePresetOf(m, inv) : tunedPresetFor(m.id, x, inv)) fam.modes.add(x);
}
}
const wanted = mode === "inpaint" || mode === "outpaint" ? "edit" : mode;
return [...byName].map(([name, e]) => ({ name, kind: e.kind, modes: AGENT_MODE_ORDER.filter((x) => e.modes.has(x)) })).filter((e) => e.modes.length > 0 && (!wanted || e.modes.includes(wanted))).sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === "image" ? -1 : 1);
}
// src/services/modelInventoryRuntime.ts
var fetcher = null;
var provider = null;
function snapshotPath() {
try {
return path5.join(getProjectRoot(), "logs", "model-inventory.json");
} catch {
return void 0;
}
}
function getProvider() {
provider ??= createInventoryProvider({
fetchEcho: () => fetcher ? fetcher() : Promise.reject(new Error("no echo fetcher registered")),
snapshotPath: snapshotPath()
});
return provider;
}
function registerInventoryFetcher(fn) {
fetcher = fn;
}
function primeInventoryFromEcho(echoResponse, durationMs = 0) {
try {
return getProvider().prime(parseEchoResponse(echoResponse), durationMs);
} catch {
return null;
}
}
function echoFetcherForClient(client, clientName2, sharedSecret) {
return () => new Promise((resolve, reject) => {
const echo = client?.echo?.bind(client);
if (typeof echo !== "function") return reject(new Error("client has no echo"));
const req = { name: clientName2 };
if (sharedSecret) req.sharedSecret = sharedSecret;
echo(req, (err, resp) => err ? reject(err) : resolve(parseEchoResponse(resp)));
});
}
function peekInventory() {
return provider ? provider.peek() : null;
}
async function currentInventory() {
try {
return (await getProvider().get()).inventory;
} catch {
return null;
}
}
var OVERLAY_MODE2 = {
text2image: "txt2img",
image2image: "img2img",
edit: "edit",
inpaint: "edit",
outpaint: "edit",
text2video: "txt2vid",
image2video: "img2vid"
};
function presetAvailability(inv, mode) {
const overlayMode = OVERLAY_MODE2[mode];
const out = { usable: [], degraded: [], unusable: [] };
if (!overlayMode) return out;
for (const id of MODEL_IDS) {
if (id === "auto" || id === "custom") continue;
const wanted = getModelFilename(id, overlayMode);
if (!wanted) continue;
const file = installedFileOf(wanted, inv).file;
const state = stateOfFile(inv, file);
const ready = state.state === "ready" || state.state === "custom" && state.model.ready;
const missingLoras = getModelRequiredFiles(id, overlayMode).filter((f) => f !== wanted && !inv.files.has(f));
if (ready && !missingLoras.length) out.usable.push(id);
else if (ready && loraFallbackOverlay(withInstalledPrecision(getModelOverlay(id, overlayMode), inv), inv)) {
out.degraded.push({ preset: id, reason: `LoRA '${missingLoras[0]}' is not installed, so the slower recommended settings apply` });
} else out.unusable.push({ preset: id, reason: ready ? `LoRA '${missingLoras[0]}' is not installed` : explainFile(inv, file) });
}
return out;
}
var unique = (list) => [...new Set(list)];
function agentNameOfPreset(preset) {
for (const mode of ["txt2img", "edit", "txt2vid", "img2vid", "img2img"]) {
const file = getModelFilename(preset, mode);
const model = file ? catalogModelOfFile(file) : void 0;
const name = model && agentNameOfModel(model);
if (name) return name;
}
return agentNameOfFamily(officialNameFor(preset));
}
var firstPerName = (list) => {
const byName = /* @__PURE__ */ new Map();
for (const u of list) if (!byName.has(agentNameOfPreset(u.preset))) byName.set(agentNameOfPreset(u.preset), u.reason.replace(/\.$/, ""));
return [...byName].map(([name, reason]) => `${name} (${reason})`);
};
function formatModelHint(inv, mode) {
const { usable, degraded, unusable } = presetAvailability(inv, mode);
const usableNames = installedAgentNames(inv, mode).map((e) => e.name);
const lines = [
usableNames.length ? `Models usable on this machine for mode '${mode}': ${usableNames.join(", ")}.` : `No model is usable on this machine for mode '${mode}'.`
];
const usableTuned = new Set(usable.map(agentNameOfPreset));
const slower = degraded.filter((d) => !usableTuned.has(agentNameOfPreset(d.preset)));
if (slower.length) lines.push(`Slower than tuned: ${firstPerName(slower).join("; ")}.`);
const known = /* @__PURE__ */ new Set([...usableNames, ...usableTuned, ...degraded.map((d) => agentNameOfPreset(d.preset))]);
const blocked = unusable.filter((u) => !known.has(agentNameOfPreset(u.preset)));
if (blocked.length) lines.push(`Not usable here: ${firstPerName(blocked).join("; ")}.`);
return lines.join("\n");
}
async function appendModelHint(message, mode) {
try {
const inv = await currentInventory();
return inv ? `${message}
${formatModelHint(inv, mode)}` : message;
} catch {
return message;
}
}
async function listUsablePresets(mode) {
try {
const inv = await currentInventory();
if (!inv) return null;
const a = presetAvailability(inv, mode);
return unique([...a.usable, ...a.degraded.map((d) => d.preset)].map(officialNameFor));
} catch {
return null;
}
}
async function explainRequiredFile(file) {
try {
const inv = await currentInventory();
return inv ? explainFile(inv, file) : null;
} catch {
return null;
}
}
function hasInventoryFetcher() {
return fetcher !== null;
}
// src/services/modelResolver.ts
var PRECISION_RE = /_(bf16_q8p|bf16|f16|f32|q8p|q6p|q5p|q4p|i8x|i6x|i5x|i4x|i3x)(_svd)?\.ckpt$/;
var fileOf = (i) => runtimeCatalog.files[i];
var precisionOf = (file) => PRECISION_RE.exec(file)?.[1] ?? null;
function precisionFromHint(hint) {
const h = hint.toLowerCase();
const bits = /(\d)\s*-?\s*bit(\s*s\b)?/.exec(h);
if (bits) return bits[2] ? `i${bits[1]}x` : `q${bits[1]}p`;
if (/exact|f16/.test(h)) return "f16";
if (/f32/.test(h)) return "f32";
if (/bf16/.test(h)) return "bf16";
return null;
}
var index = null;
function getIndex() {
if (index) return index;
const idx = { tags: /* @__PURE__ */ new Map(), labels: /* @__PURE__ */ new Map(), files: /* @__PURE__ */ new Map(), names: /* @__PURE__ */ new Map(), ids: /* @__PURE__ */ new Map() };
for (const [tag, fam] of Object.entries(runtimeCatalog.families)) {
idx.tags.set(normalizeModelName(tag), tag);
if (fam.label) idx.labels.set(normalizeModelName(fam.label), tag);
}
for (const m of runtimeCatalog.models) {
idx.ids.set(normalizeModelName(m.id), m);
const key = normalizeModelName(m.name);
idx.names.set(key, [...idx.names.get(key) ?? [], m]);
for (const [i] of m.files) idx.files.set(normalizeModelName(fileOf(i)), { model: m, file: fileOf(i) });
}
index = idx;
return idx;
}
function isPresetName(name) {
return name === "auto" || name === "custom" || isLegacyPresetName(name);
}
function kindMismatch(model, mode) {
const kind = runtimeCatalog.families[model.family]?.kind;
const videoMode = mode === "text2video" || mode === "image2video";
return kind === "upscaler" || videoMode !== (kind === "video");
}
function modeProblem(model, mode) {
if (kindMismatch(model, mode) || !model.modesUncertain && !supportsMode(model.modes, mode)) {
return `Model '${model.name}' does not support mode '${mode}'. Supported modes for this model: ${model.modes.join(", ")}.`;
}
return null;
}
function userPresetFor(mode, files, prefer) {
const hits = findCustomPresetsByModelFile(mode, files);
if (!hits.length) return null;
const preferred = new Set(prefer.map(normalizeModelName));
const official = (p) => preferred.has(normalizeModelName(p.modelId)) || isPresetName(p.modelId) || !!runtimeCatalog.families[p.modelId];
return hits.find(official) ?? hits[0];
}
var userPresetNote = (p) => `Using your preset '${p.name}' (${p.params.model}).`;
function tunedPresetWithoutHijack(preset, mode) {
return preset && [preset, ...legacyNamesOf(preset)].some((name) => getCustomPreset(`${mode}.${name}`)) ? null : preset;
}
function alternativesOf(name, mode, inv) {
if (!name) return "";
const files = inv.installed.filter((m) => m.ready && agentNameOfModel(m) === name && supportsMode(m.modes, mode)).flatMap((m) => m.installedFiles);
return files.length ? ` Installed for '${name}' (mode '${mode}'): ${files.join(", ")}.` : ` Nothing is installed for '${name}' in mode '${mode}'.`;
}
function concrete(model, requestedFile, precision, mode, inv) {
const problem = modeProblem(model, mode);
if (problem) return { ok: false, reason: problem };
const modelFiles = model.files.map(([i]) => fileOf(i));
if (!inv) return { ok: true, passAs: requestedFile ?? modelFiles.find((f) => !precision || precisionOf(f)?.startsWith(precision)) ?? modelFiles[0] };
const installed = inv.installed.find((m) => m.id === model.id);
if (!installed) return { ok: false, reason: `Model '${model.name}' is not installed.${alternativesOf(agentNameOfModel(model), mode, inv)}` };
if (!installed.ready) return { ok: false, reason: explainFile(inv, installed.file) };
const wanted = requestedFile ?? (precision ? installed.installedFiles.find((f) => precisionOf(f)?.startsWith(precision)) : void 0);
if (requestedFile && !installed.installedFiles.includes(requestedFile)) {
return { ok: false, reason: explainFile(inv, requestedFile) };
}
if (precision && !wanted) {
return { ok: false, reason: `'${model.name}' is not installed in precision '${precision}'. Installed: ${installed.installedFiles.join(", ")}.` };
}
const file = wanted ?? installed.file;
const mine = userPresetFor(mode, wanted ? [wanted] : installed.installedFiles, [model.id, model.family]);
if (mine) return { ok: true, passAs: mine.modelId, note: userPresetNote(mine) };
const preset = tunedPresetWithoutHijack(tunedPresetFor(model.id, mode, inv, wanted), mode);
if (isImage2ImageMode(mode) && !preset) return { ok: false, reason: image2imageUnavailable(`'${requestedFile ?? model.name}'`, inv) };
return { ok: true, passAs: preset ?? file };
}
function supportedModesOf(belongs, display, inv) {
const modes = new Set(inv.installed.filter((m) => m.ready && belongs(m)).flatMap((m) => m.modes));
return modes.size ? ` Installed models of '${display}' support: ${[...modes].join(", ")}.` : ` Nothing is installed for '${display}'.`;
}
function group(display, belongs, mode, inv) {
if (!inv) return { ok: false, reason: `'${display}' can only be resolved against the server's installed models, which are not available.` };
const pick = pickFallbackModel(inv, mode, { accept: (m) => belongs(m) && (!isImage2ImageMode(mode) || !!image2imagePresetOf(m, inv)) });
if (!pick) {
return { ok: false, reason: isImage2ImageMode(mode) ? `'${display}' has no installed model with an image2image preset (a preset with a tuned strength). ${image2imageAlternatives(inv)}` : `No installed model of '${display}' supports mode '${mode}'.${supportedModesOf(belongs, display, inv)}` };
}
const tag = pick.model.family;
const mine = userPresetFor(mode, pick.model.installedFiles, [pick.model.id, tag]);
if (mine) return { ok: true, passAs: mine.modelId, familyTag: tag, note: `'${display}': ${userPresetNote(mine)}` };
const preset = tunedPresetWithoutHijack(tunedPresetFor(pick.model.id, mode, inv), mode);
if (isImage2ImageMode(mode) && !preset) return { ok: false, reason: image2imageUnavailable(`'${pick.model.name}'`, inv) };
return {
ok: true,
passAs: preset ?? pick.model.file,
familyTag: tag,
note: `'${display}' resolved to '${pick.model.name}' (${preset ? `preset ${preset}` : pick.model.file}).`
};
}
var family = (tag, mode, inv) => group(tag, (m) => m.family === tag, mode, inv);
var target = (t, display, mode, inv) => group(display, (m) => belongsTo(t, m) && (!t.exclusive || agentNameOfModel(m) === t.label || !!inv && !!tunedPresetFor(m.id, mode, inv)), mode, inv);
function resolveModelArgument(input, mode, inv) {
const raw = input.trim();
if (!raw || raw === "auto" || raw === "custom") return null;
const idx = getIndex();
const n = normalizeModelName(raw);
const byFile = idx.files.get(n);
if (byFile) return concrete(byFile.model, byFile.file, null, mode, inv);
const named = manualAlias(n) ?? agentNameTarget(n);
if (named) return target(named, agentNameTarget(n)?.label ?? raw, mode, inv);
let nameHits = idx.names.get(n);
let precision = null;
if (!nameHits) {
const m = /^(.*?)\s*\(([^()]*)\)\s*$/.exec(raw);
if (m) {
precision = precisionFromHint(m[2]);
nameHits = precision ? idx.names.get(normalizeModelName(m[1])) : void 0;
}
}
if (nameHits) {
if (nameHits.length > 1) return { ok: false, reason: `'${raw}' is ambiguous: ${nameHits.map((m) => m.name).join(", ")}.` };
return concrete(nameHits[0], void 0, precision, mode, inv);
}
const byId = idx.ids.get(n);
if (byId) return concrete(byId, void 0, null, mode, inv);
const custom = inv && [...inv.customByFile.values()].filter((c) => normalizeModelName(c.name) === n || normalizeModelName(c.file) === n);
if (custom && custom.length > 1) return { ok: false, reason: `'${raw}' is ambiguous among custom models: ${custom.map((c) => c.file).join(", ")}.` };
if (custom?.length) {
const c = custom[0];
return c.ready ? { ok: true, passAs: c.file, note: `Custom model '${c.name}' (${c.family}): no curated settings, engine defaults apply.` } : { ok: false, reason: explainFile(inv, c.file) };
}
const tag = idx.tags.get(n);
if (tag) return family(tag, mode, inv);
const label = idx.labels.get(n);
if (label) return family(label, mode, inv);
const prefix = generatedAlias(n);
return prefix ? target(prefix, raw, mode, inv) : lookalike(raw, mode, inv);
}
var LOOSE_PRECISION_RE = new RegExp(PRECISION_RE.source.replace("\\.ckpt$", "(?:\\.ckpt)?$"));
function lookalike(raw, mode, inv) {
const stem = normalizeModelName(raw.replace(/\s*\([^()]*\)\s*$/, "").replace(LOOSE_PRECISION_RE, ""));
if (stem.length < 5) return null;
const names = /* @__PURE__ */ new Set();
for (const m of runtimeCatalog.models) {
const keys = [m.name, m.id, ...m.files.map(([i]) => fileOf(i).replace(PRECISION_RE, ""))].map(normalizeModelName);
const name = keys.some((k) => k === stem || k.startsWith(`${stem}-`)) ? agentNameOfModel(m) : void 0;
if (name) names.add(name);
}
if (!names.size) return null;
const parts = [...names].map((name) => {
const files = inv?.installed.filter((m) => m.ready && agentNameOfModel(m) === name && supportsMode(m.modes, mode)).flatMap((m) => m.installedFiles) ?? [];
return files.length ? `${name} (installed for mode '${mode}': ${files.join(", ")})` : `${name} (nothing installed for mode '${mode}')`;
});
return { ok: false, reason: `'${raw}' is not a known model. It looks like: ${parts.join("; ")}. Use the name to get the best installed variant, or one of the listed files.` };
}
async function resolveRequestedModel(name, mode) {
try {
const r = resolveModelArgument(name, mode, await currentInventory());
if (!r) return null;
return r.ok ? { modelId: r.passAs, familyTag: r.familyTag, note: r.note } : { error: r.reason };
} catch {
return null;
}
}
// src/capabilities.ts
var cachedSelfPluginIdentifier;
function getSelfPluginIdentifier() {
if (cachedSelfPluginIdentifier !== void 0)
return cachedSelfPluginIdentifier;
try {
const pluginIdentifier = getPluginMeta().pluginIdentifier;
if (pluginIdentifier && pluginIdentifier !== "unknown") {
cachedSelfPluginIdentifier = pluginIdentifier;
return cachedSelfPluginIdentifier;
}
} catch (err) {
console.warn(
"[Capabilities] Failed to resolve pluginIdentifier from manifest.json.",
err
);
cachedSelfPluginIdentifier = null;
return cachedSelfPluginIdentifier;
}
console.warn(
"[Capabilities] manifest.json did not contain valid owner/name."
);
cachedSelfPluginIdentifier = null;
return cachedSelfPluginIdentifier;
}
var MEDIA_HARVESTING_CONFIG = {
/**
* Attachments: User-uploaded files.
* allow: "all" because LM Studio controls the source.
* SSOT Location: User-Turns → message.files[]
*/
attachment: {
allow: "all"
},
/**
* Variants: Our own generate_image outputs.
* allow: "all" because we control the source (ourselves).
*/
variant: {
allow: "all"
// Implicitly: only our own plugin via getSelfPluginIdentifier()
},
/**
* Images: 3rd-party image generators.
* allow: "all" because LM Studio is the gatekeeper:
* If base64 arrives and gets decoded to ChatWd, we trust it.
*/
image: {
allow: "all"
// Universal: any tool that delivers base64/filename
},
/**
* Pictures: External URLs from web searches.
* allow: "only" because extraction logic is tool-specific
* (Brave JSON structure ≠Google JSON structure ≠...).
*/
picture: {
allow: "only",
tools: {
"mcp/brave-search-mcp": ["brave_image_search"],
// NUR brave_image_search
"ceveyne/draw-things-index": ["index_image"],
"ceveyne/find-image": ["find_image"]
// Add new picture tools here...
}
}
};
function isToolAllowlistedForMediaType(mediaType, pluginIdentifier, toolName2) {
const config = MEDIA_HARVESTING_CONFIG[mediaType];
if (config.allow === "all") {
return true;
}
const tools = config.tools[pluginIdentifier];
if (!tools) return false;
return tools.includes(toolName2);
}
function getMediaTypeForTool(pluginIdentifier, toolName2) {
if (isToolAllowlistedForMediaType("picture", pluginIdentifier, toolName2)) {
return "picture";
}
const selfPlugin2 = getSelfPluginIdentifier();
if (selfPlugin2 && pluginIdentifier === selfPlugin2) {
return "variant";
}
return "image";
}
function isAllowlistedSsotToolCall(input) {
const name = input?.name;
const pluginIdentifier = input?.pluginIdentifier;
if (typeof pluginIdentifier !== "string" || !pluginIdentifier.trim()) {
return false;
}
if (typeof name !== "string" || !name.trim()) {
return false;
}
return getMediaTypeForTool(pluginIdentifier, name) !== void 0;
}
var CAPABILITY_MAP = {
// Local LM Studio Models (Orchestrator/Agent)
"google/gemma-4-26b-a4b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<|channel>thought",
endString: "<channel|>"
},
requiresEnableThinkingFlag: false
},
supportsStreaming: true
},
"google/gemma-4-31b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<|channel>thought",
endString: "<channel|>"
},
requiresEnableThinkingFlag: false
},
supportsStreaming: true
},
"google/gemma-4-26b-a4b-it": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<|channel>thought",
endString: "<channel|>"
},
requiresEnableThinkingFlag: false
},
supportsStreaming: true
},
"google/gemma-4-31b-it": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<|channel>thought",
endString: "<channel|>"
},
requiresEnableThinkingFlag: false
},
supportsStreaming: true
},
"google/gemma-4-12b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: false,
supportsStreaming: true
},
"qwen/qwen3.6-35b-a3b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<think>",
endString: "</think>"
},
// Qwen3.6 does NOT support the /think soft-switch of Qwen3.
// The Jinja template opens <think> by default, but only if
// `enable_thinking` is NOT explicitly set to false.
// To be safe and explicit, we always send the flag as true.
requiresEnableThinkingFlag: true
},
supportsStreaming: true
},
"qwen/qwen3.5-35b-a3b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<think>",
endString: "</think>"
},
// Qwen3.5 does NOT support the /think soft-switch of Qwen3.
// The Jinja template opens <think> by default, but only if
// `enable_thinking` is NOT explicitly set to false.
// To be safe and explicit, we always send the flag as true.
requiresEnableThinkingFlag: true
},
supportsStreaming: true
},
"qwen/qwen3.8-27b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<think>",
endString: "</think>"
},
requiresEnableThinkingFlag: true
},
supportsStreaming: true
},
"qwen/qwen3.6-27b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<think>",
endString: "</think>"
},
requiresEnableThinkingFlag: true
},
supportsStreaming: true
},
"qwen/qwen3.5-27b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<think>",
endString: "</think>"
},
requiresEnableThinkingFlag: true
},
supportsStreaming: true
},
"qwen/qwen3.5-9b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<think>",
endString: "</think>"
},
requiresEnableThinkingFlag: true
},
supportsStreaming: true
},
"qwen/qwen3-vl-30b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: false,
supportsStreaming: true
},
"google/gemma-3-27b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: false,
supportsStreaming: true
},
"mistralai/magistral-small-2509": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "[THINK]",
endString: "[/THINK]"
}
},
supportsStreaming: true
},
"mistralai/devstral-small-2-2512": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<think>",
endString: "</think>"
}
},
supportsStreaming: true
},
"zai-org/glm-4.6v-flash": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
// Spontaneous <think>...</think> reasoning
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<think>",
endString: "</think>"
}
},
supportsStreaming: true
},
// OpenAI API (https://api.openai.com/v1)
"openai/gpt-5.5": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: false,
// Reasoning is internal, not exposed as stream tokens
supportsStreaming: true
},
// Anthropic API via OpenAI-compatible endpoint (no Anthropic SDK)
// Extended thinking tokens are not surfaced through the OpenAI-compatible layer.
"anthropic/claude-sonnet-4-6": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: false,
supportsStreaming: true
},
"anthropic/claude-opus-4-7": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: false,
supportsStreaming: true
}
};
var CAPABILITY_SUBSTRING_ALIASES = {
"qwen36-27b": "qwen/qwen3.6-27b",
"qwen36-35b": "qwen/qwen3.6-35b-a3b"
};
var DEFAULT_CAPABILITIES = {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: false,
supportsStreaming: true
};
function stripPublisher(modelId) {
const idx = modelId.indexOf("/");
return idx >= 0 ? modelId.slice(idx + 1) : modelId;
}
function detectCapabilities(modelId) {
const input = (modelId || "").trim();
const inputLower = input.toLowerCase();
const inputStripped = stripPublisher(input).toLowerCase();
if (CAPABILITY_MAP[input]) {
return CAPABILITY_MAP[input];
}
for (const key of Object.keys(CAPABILITY_MAP)) {
if (key.toLowerCase() === inputLower) {
return CAPABILITY_MAP[key];
}
}
for (const key of Object.keys(CAPABILITY_MAP)) {
const keyStripped = stripPublisher(key).toLowerCase();
if (keyStripped === inputStripped) {
return CAPABILITY_MAP[key];
}
}
for (const key of Object.keys(CAPABILITY_MAP)) {
const keyStripped = stripPublisher(key).toLowerCase();
if (inputStripped.startsWith(keyStripped + "-")) {
return CAPABILITY_MAP[key];
}
}
for (const [alias, targetKey] of Object.entries(CAPABILITY_SUBSTRING_ALIASES)) {
if (inputStripped.includes(alias) && CAPABILITY_MAP[targetKey]) {
return CAPABILITY_MAP[targetKey];
}
}
console.warn(`[Capabilities] Unknown model ID "${modelId}", using defaults.`);
return DEFAULT_CAPABILITIES;
}
function isKnownModel(modelId) {
const input = (modelId || "").trim();
const inputLower = input.toLowerCase();
const inputStripped = stripPublisher(input).toLowerCase();
if (CAPABILITY_MAP[input]) return true;
for (const key of Object.keys(CAPABILITY_MAP)) {
if (key.toLowerCase() === inputLower) return true;
}
for (const key of Object.keys(CAPABILITY_MAP)) {
if (stripPublisher(key).toLowerCase() === inputStripped) return true;
}
for (const key of Object.keys(CAPABILITY_MAP)) {
if (inputStripped.startsWith(stripPublisher(key).toLowerCase() + "-")) return true;
}
for (const [alias, targetKey] of Object.entries(CAPABILITY_SUBSTRING_ALIASES)) {
if (inputStripped.includes(alias) && CAPABILITY_MAP[targetKey]) return true;
}
return false;
}
function shouldUseFilesApiForModel(modelId, userToggle) {
if (!userToggle) return false;
return true;
}
var PROMPT_UPSAMPLING_MODEL_FAMILIES = {
"flux-3-image-klein-pup": {
contextLength: 16384,
ggufVariant: "UD-Q4_K_XL",
knownModels: [
"flux-3-image-klein-pup",
"unsloth/flux-3-image-klein-pup",
"lmstudio-community/flux-3-image-klein-pup",
"mlx-community/flux-3-image-klein-pup-8bit",
"unsloth/flux-3-image-klein-pup-GGUF"
]
}
};
var CAPABILITY_ENTRIES = {
// IMPORTANT: keys are Draw Things model filenames without extension,
// using hyphens instead of underscores, and without quantization suffix.
"z-image-turbo-1.0": {
modelFilenames: [
"z_image_turbo_1.0_q8p.ckpt",
"z_image_turbo_1.0_q6p.ckpt",
"z_image_turbo_1.0_i8x.ckpt"
]
},
"z-image-1.0": {
modelFilenames: [
"z_image_1.0_q8p.ckpt",
"z_image_1.0_q6p.ckpt",
"z_image_1.0_i8x.ckpt"
]
},
"krea-2-turbo": {
modelFilenames: [
"krea_2_turbo_i8x.ckpt",
"krea_2_turbo_i6x.ckpt",
"krea_2_turbo_q8p.ckpt",
"krea_2_turbo_q6p.ckpt"
]
},
"krea-2-raw": {
modelFilenames: [
"krea_2_raw_i8x.ckpt",
"krea_2_raw_q8p.ckpt",
"krea_2_raw_q6p.ckpt"
]
},
"qwen-image-1.0": {
modelFilenames: [
// Legacy / stable names
"qwen_image_1.0_q8p.ckpt",
"qwen_image_1.0_q6p.ckpt",
// Current Draw Things builds
"qwen_image_2512_bf16_q8p.ckpt",
"qwen_image_2512_bf16_q6p.ckpt",
"qwen_image_2512_i8x.ckpt",
"qwen_image_2512_bf16_i8x.ckpt",
// Edit models (used by defaults/overlays depending on mode and version)
"qwen_image_edit_2509_q8p.ckpt",
"qwen_image_edit_2509_q6p.ckpt",
"qwen_image_edit_2511_q8p.ckpt",
"qwen_image_edit_2511_q6p.ckpt"
]
},
// Unified qwen-edit preset (covers both 2509 and 2511 edit models)
"qwen-edit": {
modelFilenames: [
"qwen_image_edit_2509_q6p.ckpt",
"qwen_image_edit_2511_q6p.ckpt",
"qwen_image_edit_2511_i8x.ckpt",
"qwen_image_edit_2511_bf16_i8x.ckpt"
]
},
"qwen-image-edit-2509": {
modelFilenames: ["qwen_image_edit_2509_q6p.ckpt"]
},
"qwen-image-edit-2511": {
modelFilenames: [
"qwen_image_edit_2511_q6p.ckpt",
"qwen_image_edit_2511_i8x.ckpt",
"qwen_image_edit_2511_bf16_i8x.ckpt"
]
},
"flux-1-schnell": {
modelFilenames: ["flux_1_schnell_q8p.ckpt"]
},
"flux-2-klein": {
modelFilenames: [
// Common variants
"flux_2_klein_9b_q6p.ckpt",
"flux_2_klein_9b_q8p.ckpt",
"flux_2_klein_9b_kv_q6p.ckpt",
"flux_2_klein_9b_kv_q8p.ckpt",
"flux_2_klein_base_9b_q8p.ckpt",
// Seen in logs for custom presets (still in the Flux family)
"flux_2_dev_q6p.ckpt",
// 4B variants
"flux_2_klein_4b_i8x.ckpt",
"flux_2_klein_base_4b_i8x.ckpt"
]
},
// FLUX.3 [klein] 5.6B
"flux-3-klein": {
promptUpsampling: { promptUpsamplingModelFamily: "flux-3-image-klein-pup", maxImages: 10 },
modelFilenames: [
// Distilled (default: q8p; currently used: f16 "Exact")
"flux_3_klein_q8p.ckpt",
"flux_3_klein_f16.ckpt",
"flux_3_klein_i8x.ckpt",
"flux_3_klein_i4x.ckpt",
// Base (undistilled)
"flux_3_klein_base_q8p.ckpt",
"flux_3_klein_base_f16.ckpt",
"flux_3_klein_base_i8x.ckpt",
"flux_3_klein_base_i4x.ckpt"
]
},
"ltx-2-distilled": {
video: {
defaultFps: 25,
audioSampleRate: 24e3
},
// ModelZoo: framesPerSecondForModel(.ltx2) = 25, audioSampleRateForModel(.ltx2) = 24 000
modelFilenames: [
"ltx_2_19b_distilled_q6p.ckpt",
"ltx_2_19b_distilled_q8p.ckpt"
]
},
"ltx-2-dev": {
video: {
defaultFps: 25,
audioSampleRate: 24e3
},
// ModelZoo: framesPerSecondForModel(.ltx2) = 25, audioSampleRateForModel(.ltx2) = 24 000
modelFilenames: [
"ltx_2_19b_dev_q6p.ckpt",
"ltx_2_19b_dev_q8p.ckpt"
]
},
"ltx-2.3-distilled": {
video: {
defaultFps: 25,
audioSampleRate: 48e3
},
// ModelZoo: framesPerSecondForModel(.ltx2_3) = 25, audioSampleRateForModel(.ltx2_3) = 48 000
modelFilenames: [
"ltx_2.3_22b_distilled_q6p.ckpt",
"ltx_2.3_22b_distilled_q8p.ckpt",
"ltx_2.3_22b_distilled_1.1_q6p.ckpt",
"ltx_2.3_22b_distilled_1.1_q8p.ckpt",
"ltx_2.3_22b_distilled_i8x.ckpt",
"ltx_2.3_22b_distilled_1.1_i8x.ckpt"
]
},
"ltx-2.3-dev": {
video: {
defaultFps: 25,
audioSampleRate: 48e3
},
// ModelZoo: framesPerSecondForModel(.ltx2_3) = 25, audioSampleRateForModel(.ltx2_3) = 48 000
modelFilenames: [
"ltx_2.3_22b_dev_q6p.ckpt",
"ltx_2.3_22b_dev_q8p.ckpt",
"ltx_2.3_22b_dev_i8x.ckpt"
]
},
"seedvr2-7b": {
modelFilenames: [
"seedvr2_7b_q8p.ckpt",
"seedvr2_7b_q6p.ckpt"
]
},
"qwen-image-2.1": {
modelFilenames: [
"qwen_image_2.1_q8p.ckpt",
"qwen_image_2.1_q6p.ckpt",
"qwen_image_2.1_i8x.ckpt",
"qwen_image_2.1_i4x.ckpt"
]
},
"qwen-image-2.1-turbo": {
modelFilenames: [
"qwen_image_2.1_turbo_q8p.ckpt",
"qwen_image_2.1_turbo_q6p.ckpt",
"qwen_image_2.1_turbo_i8x.ckpt",
"qwen_image_2.1_turbo_i4x.ckpt"
]
},
// MiniMax H3 (first/last-frame-conditioned): canvas = first frame, first enabled
// moodboard image = last frame (or omit images for text-to-video).
"minimax-h3-fl2va": {
video: {
defaultFps: 24,
audioSampleRate: 32e3
// ModelZoo note: "24 FPS video with synchronized 32 kHz stereo audio"
},
modelFilenames: [
"minimax_h3_fl2va_q8p.ckpt",
"minimax_h3_fl2va_q6p.ckpt",
"minimax_h3_fl2va_i8x.ckpt",
"minimax_h3_fl2va_i4x.ckpt"
]
},
// MiniMax H3 [ref2va]: subject/object/scene-guided generation via canvas + moodboard.
"minimax-h3-ref2va": {
video: {
defaultFps: 24,
audioSampleRate: 32e3
// ModelZoo note: "24 FPS video with synchronized 32 kHz stereo audio"
},
modelFilenames: [
"minimax_h3_ref2va_q8p.ckpt",
"minimax_h3_ref2va_q6p.ckpt",
"minimax_h3_ref2va_i8x.ckpt",
"minimax_h3_ref2va_i4x.ckpt"
]
}
};
var OVERLAY_MODES = ["txt2img", "img2img", "edit", "txt2vid", "img2vid"];
function deriveCapabilities(entries) {
const overlayIds = (mode) => MODEL_IDS.filter((id) => id !== "auto" && id !== "custom" && getModelFilename(id, mode));
const filesOfModel = (m) => m.files.map(([i]) => runtimeCatalog.files[i]);
const all = { ...entries };
const listed = new Set(Object.values(entries).flatMap((e) => (e.modelFilenames ?? []).map((f) => catalogModelOfFile(f)?.id).filter(Boolean)));
for (const id of MODEL_IDS) {
if (id === "auto" || id === "custom" || all[id]) continue;
const files = OVERLAY_MODES.map((mode) => getModelFilename(id, mode)).filter((f) => !!f);
if (files.length && !files.some((f) => listed.has(catalogModelOfFile(f)?.id ?? ""))) all[id] = { modelFilenames: files };
}
const out = {};
for (const [key, entry] of Object.entries(all)) {
const models = (entry.modelFilenames ?? []).map((file) => catalogModelOfFile(file)).filter((m) => !!m);
const modelIds = new Set(models.map((m) => m.id));
const catalogModes = new Set(models.flatMap((m) => m.modes));
const modelFilenames = [.../* @__PURE__ */ new Set([...entry.modelFilenames ?? [], ...models.flatMap(filesOfModel)])];
const overlaysOf = (mode) => overlayIds(mode).filter((id) => modelIds.has(catalogModelOfFile(getModelFilename(id, mode) ?? "")?.id ?? ""));
const image2image = overlaysOf("img2img").length > 0;
const edit = catalogModes.has("edit");
const modes = {
text2image: catalogModes.has("text2image"),
image2image,
edit,
text2video: catalogModes.has("text2video"),
image2video: catalogModes.has("image2video"),
refine: image2image
};
out[key] = {
...entry,
modelFilenames,
modes,
...edit ? { edit: { maxReferenceImages: getMaxReferenceImages(overlaysOf("edit")[0], "edit") } } : {},
...image2image ? { image2image: { maxReferenceImages: 1 } } : {}
};
}
return out;
}
var IMAGE_MODEL_CAPABILITY_MAP = deriveCapabilities(CAPABILITY_ENTRIES);
var DEFAULT_IMAGE_MODEL_CAPABILITIES = {
modes: {
text2image: false,
image2image: false,
edit: false,
text2video: false,
image2video: false
}
};
var MODEL_PRESET_TO_CAPABILITY_KEY = {
"z-image": "z-image-turbo-1.0",
krea: "krea-2-turbo",
krea2: "krea-2-turbo",
"qwen-image": "qwen-image-1.0",
"qwen-image-2.1": "qwen-image-2.1",
"qwen-image-2.1-turbo": "qwen-image-2.1-turbo",
"qwen-edit": "qwen-edit",
// qwen_image_edit_2509_q6p.ckpt or qwen_image_edit_2511_q6p.ckpt
flux: "flux-2-klein",
"flux-2": "flux-2-klein",
"flux-3": "flux-3-klein",
"flux-3-klein": "flux-3-klein",
ltx: "ltx-2.3-distilled",
// ltx-2-distilled is obsolete; current LTX family is 2.3 (distilled variant)
minimax: "minimax-h3-fl2va",
"minimax-ref": "minimax-h3-ref2va",
seedvr2: "seedvr2-7b"
// Note: 'custom' is not in this map - it uses custom_configs.json only
};
function detectImageModelCapabilities(modelId) {
const m = (modelId || "").toLowerCase();
if (IMAGE_MODEL_CAPABILITY_MAP[modelId]) {
return IMAGE_MODEL_CAPABILITY_MAP[modelId];
}
const key = Object.keys(IMAGE_MODEL_CAPABILITY_MAP).find(
(k) => k.toLowerCase() === m
);
if (key) {
return IMAGE_MODEL_CAPABILITY_MAP[key];
}
return DEFAULT_IMAGE_MODEL_CAPABILITIES;
}
function getDefaultFpsForModel(modelId) {
const direct = detectImageModelCapabilities(modelId);
if (direct !== DEFAULT_IMAGE_MODEL_CAPABILITIES) {
return direct.video?.defaultFps;
}
const lower = (modelId || "").toLowerCase();
for (const caps of Object.values(IMAGE_MODEL_CAPABILITY_MAP)) {
if (caps.modelFilenames?.some((f) => f.toLowerCase() === lower)) {
return caps.video?.defaultFps;
}
}
return void 0;
}
function getAudioSampleRateForModel(modelId) {
const direct = detectImageModelCapabilities(modelId);
if (direct !== DEFAULT_IMAGE_MODEL_CAPABILITIES) {
return direct.video?.audioSampleRate;
}
const lower = (modelId || "").toLowerCase();
for (const caps of Object.values(IMAGE_MODEL_CAPABILITY_MAP)) {
if (caps.modelFilenames?.some((f) => f.toLowerCase() === lower)) {
return caps.video?.audioSampleRate;
}
}
return void 0;
}
function findImageModelCapabilitiesByFilename(filename) {
const lower = (filename || "").toLowerCase();
if (!lower) return void 0;
for (const caps of Object.values(IMAGE_MODEL_CAPABILITY_MAP)) {
if (caps.modelFilenames?.some((f) => f.toLowerCase() === lower)) return caps;
}
return void 0;
}
function checkCatalogModel(name, mode) {
const r = resolveModelArgument(name, mode, peekInventory());
if (!r) return null;
return r.ok ? { supported: true } : { supported: false, reason: r.reason };
}
function capabilityKeyOfPreset(preset) {
const listed = MODEL_PRESET_TO_CAPABILITY_KEY[preset] ?? legacyNamesOf(preset).map((name) => MODEL_PRESET_TO_CAPABILITY_KEY[name]).find(Boolean);
if (listed) return listed;
for (const mode of OVERLAY_MODES) {
const file = getModelFilename(preset, mode)?.toLowerCase();
const key = file && Object.keys(IMAGE_MODEL_CAPABILITY_MAP).find((k) => IMAGE_MODEL_CAPABILITY_MAP[k].modelFilenames?.some((f) => f.toLowerCase() === file));
if (key) return key;
}
return void 0;
}
function getCapabilityKeyForPreset(preset) {
if (preset === "auto") return void 0;
return capabilityKeyOfPreset(preset);
}
function checkModeSupport(modelPreset, mode) {
if (modelPreset === "auto") {
return { supported: true };
}
const capKey = capabilityKeyOfPreset(modelPreset);
if (!capKey) {
const catalogCheck = checkCatalogModel(modelPreset, mode);
if (catalogCheck) return catalogCheck;
return {
supported: false,
reason: `Unknown model '${modelPreset}'. Use auto or one of the names listed here; a model name or a file name also works.`
};
}
const caps = detectImageModelCapabilities(capKey);
if (!caps.modes[mode]) {
const supportedModes = Object.entries(caps.modes).filter(([, v]) => v).map(([k]) => k);
return {
supported: false,
reason: `Model '${modelPreset}' does not support mode '${mode}'. Supported modes for this model: ${supportedModes.join(", ") || "none"}.`
};
}
return { supported: true };
}
function checkModeSupportWithCustom(modelPreset, mode, getAvailableCombos) {
if (getAvailableCombos) {
try {
const customCombos = getAvailableCombos();
const hasCustomConfig = customCombos.some(
([customMode, customModelId]) => customMode === mode && customModelId === modelPreset
);
if (hasCustomConfig) {
return { supported: true };
}
} catch {
}
}
const baseCheck = checkModeSupport(modelPreset, mode);
if (baseCheck.supported || !getAvailableCombos) {
return baseCheck;
}
let reason = baseCheck.reason;
try {
const customCombos = getAvailableCombos();
const customForModel = customCombos.filter(
([, modelId]) => modelId === modelPreset
);
if (customForModel.length > 0) {
const customModes = customForModel.map(([m]) => m).join(", ");
reason += ` Custom configs available for '${modelPreset}': ${customModes}.`;
} else {
const customForMode = customCombos.filter(([m]) => m === mode);
if (customForMode.length > 0) {
const customModels = customForMode.map(([, modelId]) => modelId);
reason += ` Mode '${mode}' is available via custom configs for: ${customModels.join(
", "
)}.`;
}
}
} catch {
}
return {
supported: false,
reason
};
}
function resolvePresetFromModelFilename(filename) {
const needle = (filename || "").trim().toLowerCase();
if (!needle) return void 0;
const capKey = Object.keys(IMAGE_MODEL_CAPABILITY_MAP).find(
(k) => IMAGE_MODEL_CAPABILITY_MAP[k].modelFilenames?.some((f) => f.toLowerCase() === needle)
);
if (!capKey) return void 0;
return Object.keys(MODEL_PRESET_TO_CAPABILITY_KEY).find(
(preset) => MODEL_PRESET_TO_CAPABILITY_KEY[preset] === capKey
);
}
function selectAutoModel(mode) {
const defaultModelFilename = mode === "edit" ? defaultParamsImg2Img2.model : mode === "image2image" ? defaultParamsImg2Img.model : mode === "text2video" ? defaultParamsText2Video.model : mode === "image2video" ? defaultParamsImage2Video.model : defaultParams.model;
const resolved = resolvePresetFromModelFilename(defaultModelFilename);
if (resolved) return resolved;
console.warn(
`[Capabilities] selectAutoModel(${mode}): default model '${defaultModelFilename}' is not registered in IMAGE_MODEL_CAPABILITY_MAP/MODEL_PRESET_TO_CAPABILITY_KEY.`
);
return defaultModelFilename ?? "unknown";
}
var VISION_WINDOW_SIZES = {
/** Window 1: User attachments */
attachments: 5,
/** Window 2: Variants + Images (shared cap) */
everythingElse: 4
};
var MEDIA_SOURCE_REGISTRY = {
attachment: {
kind: "attachment",
indexPrefix: "a",
stateArrayKey: "attachments",
counterKey: "nextAttachmentA",
dedupeKey: "originAbs",
visionPromoted: true,
window: 1
},
variant: {
kind: "variant",
indexPrefix: "v",
stateArrayKey: "variants",
counterKey: "nextVariantV",
dedupeKey: "filename",
visionPromoted: true,
window: 2
},
picture: {
kind: "picture",
indexPrefix: "p",
stateArrayKey: "pictures",
counterKey: "nextPictureP",
dedupeKey: "sourceUrl",
visionPromoted: false
// No window assignment: not vision-promoted
},
image: {
kind: "image",
indexPrefix: "i",
stateArrayKey: "images",
counterKey: "nextImageI",
dedupeKey: "filename",
visionPromoted: true,
window: 2
}
};
function getAttachmentWindowSize() {
return VISION_WINDOW_SIZES.attachments;
}
function getEverythingElseWindowSize() {
return VISION_WINDOW_SIZES.everythingElse;
}
function getWindowSizeForKind(kind) {
const config = MEDIA_SOURCE_REGISTRY[kind];
if (!config.visionPromoted || config.window === void 0) return void 0;
return config.window === 1 ? VISION_WINDOW_SIZES.attachments : VISION_WINDOW_SIZES.everythingElse;
}
var FASTVLM_DEFAULT_ENDPOINT = "http://localhost:8765/analyze";
var MLX_VISION_ANALYZE_IMAGE_PROMPT = "";
var MLX_VISION_INDEX_IMAGE_PROMPT = "";
// src/config.ts
import { createConfigSchematics } from "@lmstudio/sdk";
var configSchematics = createConfigSchematics().field(
"model",
"string",
{
displayName: "Agent Model",
subtitle: "Enter the vision model to use as orchestrator. Default: Qwen3.6 35B \u0410\u0417\u0412.",
placeholder: "qwen/qwen3.6-35b-a3b"
},
"qwen/qwen3.6-35b-a3b"
).field(
"usePromptUpsampling",
"boolean",
{
displayName: "Use Prompt Upsampling",
subtitle: "Rewrites the prompt with a prompt upsampling model before rendering, for models that support it. OFF: the prompt goes to Draw Things unchanged.",
engineDoesNotSupport: false
},
true
).field(
"visionPromotionPersistent",
"boolean",
{
displayName: "Vision Promotion: Persistent",
subtitle: "ON: promote up to 5 attachments + 4 variants every turn. OFF: promote only when new.",
engineDoesNotSupport: true
},
false
).field(
"logRequests",
"boolean",
{
displayName: "Debug: Log requests/response",
subtitle: "Logs full request/response JSON; may include sensitive data.",
engineDoesNotSupport: true
},
false
).field(
"debugPromotion",
"boolean",
{
displayName: "Debug: Media promotion",
subtitle: "Verbose logs for media state, previews and cleanup.",
engineDoesNotSupport: true
},
false
).field(
"debugChunks",
"boolean",
{
displayName: "Debug: Stream chunk logs",
subtitle: "Log raw streaming chunks to console (verbose).",
engineDoesNotSupport: true
},
false
).build();
var globalConfigSchematics = createConfigSchematics().field(
"baseUrl",
"string",
{
displayName: "LM Studio API base-URL",
subtitle: "Local LM Studio server base-URL. Default: http://127.0.0.1:1234/v1",
placeholder: "http://127.0.0.1:1234/v1"
},
"http://127.0.0.1:1234/v1"
).field(
"apiKey",
"string",
{
displayName: "(Optional) API Key",
subtitle: "Only needed if your LM Studio server requires authentication.",
isProtected: true,
placeholder: "sk-..."
},
""
).field(
"PREVIEW_IN_CHAT",
"boolean",
{
displayName: "Simple Previews in Chat",
subtitle: "When enabled, tool responses include client-based image previews. Not recommended for advanced functionality.",
engineDoesNotSupport: false
},
false
).field(
"unloadAgentModelDuringRender",
"boolean",
{
displayName: "Unload Agent Model During Render",
subtitle: "When enabled, unloads the agent model from VRAM before long renders (image2image, edit, text2video, image2video). Only applies to local LM Studio instances.",
engineDoesNotSupport: false
},
true
).field(
"DRAW_THINGS_HOST",
"string",
{
displayName: "Draw Things Host",
subtitle: "Hostname or IP of the Draw Things backend server.",
placeholder: "127.0.0.1"
},
"127.0.0.1"
).field(
"DRAW_THINGS_HTTP_PORT",
"numeric",
{
displayName: "Draw Things HTTP Port",
subtitle: "HTTP API port (default: 7860)."
},
7860
).field(
"DRAW_THINGS_GRPC_PORT",
"numeric",
{
displayName: "Draw Things gRPC Port",
subtitle: "gRPC port (default: 7859)."
},
7859
).field(
"embedPngMetadata",
"boolean",
{
displayName: "Embed Metadata in PNGs",
subtitle: "Write generation parameters (prompt, model, seed, LoRAs, sources) into saved PNGs as XMP metadata. Compatible with draw-things-index and find-image.",
engineDoesNotSupport: false
},
true
).field(
"customConfigsPath",
"string",
{
displayName: "Custom Configs Path",
subtitle: "Path to custom_configs.json from Draw Things. Change to: `none` to disable.",
placeholder: "~/Library/Containers/com.liuliu.draw-things/Data/Documents/Models/custom_configs.json",
engineDoesNotSupport: false
},
"~/Library/Containers/com.liuliu.draw-things/Data/Documents/Models/custom_configs.json"
).field(
"HTTP_SERVER_PORT",
"numeric",
{
displayName: "Local HTTP Server Port",
subtitle: "Port for serving generated images over localhost (default: 54760).",
engineDoesNotSupport: true
},
54760
).build();
// src/preprocessor.ts
async function preprocess(ctl, userMessage) {
try {
const originalText = userMessage.getText();
const files = userMessage.consumeFiles(ctl.client, (file) => file.type !== "image");
let injected = "";
for (const file of files) {
const { content } = await ctl.client.files.parseDocument(file, { signal: ctl.abortSignal });
const snippet = content.length > 2e5 ? content.slice(0, 2e5) + "\n...[truncated]" : content;
injected += `
[Attachment: ${file.name}]
${snippet}
`;
}
const wrappers = [];
const inlineImageUrls = /* @__PURE__ */ new Set();
const mdImg = /!\[[^\]]*\]\((https?:[^\s)]+)\)/g;
let m;
while ((m = mdImg.exec(originalText)) !== null) inlineImageUrls.add(m[1]);
const tagImg = /\[image:\s*(https?:[^\]\s]+)\s*\]/gi;
while ((m = tagImg.exec(originalText)) !== null) inlineImageUrls.add(m[1]);
for (const url of inlineImageUrls) {
wrappers.push(`[[LMSTUDIO_ATTACHMENT: ${JSON.stringify({ kind: "image", url })}]]`);
}
if (injected.length === 0 && wrappers.length === 0) return userMessage;
const combined = `${originalText}${injected}${wrappers.length ? "\n\n" + wrappers.join("\n") : ""}`.trim();
userMessage.replaceText(combined);
return userMessage;
} catch (err) {
return userMessage;
}
}
// src/vision-promotion.ts
import fs5 from "fs";
// src/helpers/projectUriResolver.ts
var flatbuffers6 = __toESM(require_flatbuffers(), 1);
import { copyFileSync, existsSync, readFileSync, unlinkSync } from "fs";
import { execFileSync } from "child_process";
import { tmpdir } from "os";
import { join } from "path";
// src/interfaces/thumbnail-history-node.ts
var flatbuffers = __toESM(require_flatbuffers(), 1);
var ThumbnailHistoryNode = class _ThumbnailHistoryNode {
bb = null;
bb_pos = 0;
__init(i, bb) {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsThumbnailHistoryNode(bb, obj) {
return (obj || new _ThumbnailHistoryNode()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
static getSizePrefixedRootAsThumbnailHistoryNode(bb, obj) {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new _ThumbnailHistoryNode()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
id() {
const offset = this.bb.__offset(this.bb_pos, 4);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
data(index2) {
const offset = this.bb.__offset(this.bb_pos, 6);
return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index2) : 0;
}
dataLength() {
const offset = this.bb.__offset(this.bb_pos, 6);
return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
}
dataArray() {
const offset = this.bb.__offset(this.bb_pos, 6);
if (!offset) return null;
const start = this.bb.__vector(this.bb_pos + offset);
const len = this.bb.__vector_len(this.bb_pos + offset);
return this.bb.bytes().subarray(start, start + len);
}
};
// src/interfaces/tensor-history-node.ts
var flatbuffers4 = __toESM(require_flatbuffers(), 1);
// src/interfaces/control.ts
var flatbuffers2 = __toESM(require_flatbuffers(), 1);
// src/interfaces/control-input-type.ts
var ControlInputType = /* @__PURE__ */ ((ControlInputType2) => {
ControlInputType2[ControlInputType2["Unspecified"] = 0] = "Unspecified";
ControlInputType2[ControlInputType2["Custom"] = 1] = "Custom";
ControlInputType2[ControlInputType2["Depth"] = 2] = "Depth";
ControlInputType2[ControlInputType2["Canny"] = 3] = "Canny";
ControlInputType2[ControlInputType2["Scribble"] = 4] = "Scribble";
ControlInputType2[ControlInputType2["Pose"] = 5] = "Pose";
ControlInputType2[ControlInputType2["Normalbae"] = 6] = "Normalbae";
ControlInputType2[ControlInputType2["Color"] = 7] = "Color";
ControlInputType2[ControlInputType2["Lineart"] = 8] = "Lineart";
ControlInputType2[ControlInputType2["Softedge"] = 9] = "Softedge";
ControlInputType2[ControlInputType2["Seg"] = 10] = "Seg";
ControlInputType2[ControlInputType2["Inpaint"] = 11] = "Inpaint";
ControlInputType2[ControlInputType2["Ip2p"] = 12] = "Ip2p";
ControlInputType2[ControlInputType2["Shuffle"] = 13] = "Shuffle";
ControlInputType2[ControlInputType2["Mlsd"] = 14] = "Mlsd";
ControlInputType2[ControlInputType2["Tile"] = 15] = "Tile";
ControlInputType2[ControlInputType2["Blur"] = 16] = "Blur";
ControlInputType2[ControlInputType2["Lowquality"] = 17] = "Lowquality";
ControlInputType2[ControlInputType2["Gray"] = 18] = "Gray";
return ControlInputType2;
})(ControlInputType || {});
// src/interfaces/control-mode.ts
var ControlMode = /* @__PURE__ */ ((ControlMode2) => {
ControlMode2[ControlMode2["Balanced"] = 0] = "Balanced";
ControlMode2[ControlMode2["Prompt"] = 1] = "Prompt";
ControlMode2[ControlMode2["Control"] = 2] = "Control";
return ControlMode2;
})(ControlMode || {});
// src/interfaces/control.ts
var Control = class _Control {
bb = null;
bb_pos = 0;
__init(i, bb) {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsControl(bb, obj) {
return (obj || new _Control()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
static getSizePrefixedRootAsControl(bb, obj) {
bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
return (obj || new _Control()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
file(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 4);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
weight() {
const offset = this.bb.__offset(this.bb_pos, 6);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1;
}
guidanceStart() {
const offset = this.bb.__offset(this.bb_pos, 8);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0;
}
guidanceEnd() {
const offset = this.bb.__offset(this.bb_pos, 10);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1;
}
noPrompt() {
const offset = this.bb.__offset(this.bb_pos, 12);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
globalAveragePooling() {
const offset = this.bb.__offset(this.bb_pos, 14);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true;
}
downSamplingRate() {
const offset = this.bb.__offset(this.bb_pos, 16);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1;
}
controlMode() {
const offset = this.bb.__offset(this.bb_pos, 18);
return offset ? this.bb.readInt8(this.bb_pos + offset) : 0 /* Balanced */;
}
targetBlocks(index2, optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 20);
return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index2 * 4, optionalEncoding) : null;
}
targetBlocksLength() {
const offset = this.bb.__offset(this.bb_pos, 20);
return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
}
inputOverride() {
const offset = this.bb.__offset(this.bb_pos, 22);
return offset ? this.bb.readInt8(this.bb_pos + offset) : 0 /* Unspecified */;
}
static startControl(builder) {
builder.startObject(10);
}
static addFile(builder, fileOffset) {
builder.addFieldOffset(0, fileOffset, 0);
}
static addWeight(builder, weight) {
builder.addFieldFloat32(1, weight, 1);
}
static addGuidanceStart(builder, guidanceStart) {
builder.addFieldFloat32(2, guidanceStart, 0);
}
static addGuidanceEnd(builder, guidanceEnd) {
builder.addFieldFloat32(3, guidanceEnd, 1);
}
static addNoPrompt(builder, noPrompt) {
builder.addFieldInt8(4, +noPrompt, 0);
}
static addGlobalAveragePooling(builder, globalAveragePooling) {
builder.addFieldInt8(5, +globalAveragePooling, 1);
}
static addDownSamplingRate(builder, downSamplingRate) {
builder.addFieldFloat32(6, downSamplingRate, 1);
}
static addControlMode(builder, controlMode) {
builder.addFieldInt8(7, controlMode, 0 /* Balanced */);
}
static addTargetBlocks(builder, targetBlocksOffset) {
builder.addFieldOffset(8, targetBlocksOffset, 0);
}
static createTargetBlocksVector(builder, data) {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
static startTargetBlocksVector(builder, numElems) {
builder.startVector(4, numElems, 4);
}
static addInputOverride(builder, inputOverride) {
builder.addFieldInt8(9, inputOverride, 0 /* Unspecified */);
}
static endControl(builder) {
const offset = builder.endObject();
return offset;
}
static createControl(builder, fileOffset, weight, guidanceStart, guidanceEnd, noPrompt, globalAveragePooling, downSamplingRate, controlMode, targetBlocksOffset, inputOverride) {
_Control.startControl(builder);
_Control.addFile(builder, fileOffset);
_Control.addWeight(builder, weight);
_Control.addGuidanceStart(builder, guidanceStart);
_Control.addGuidanceEnd(builder, guidanceEnd);
_Control.addNoPrompt(builder, noPrompt);
_Control.addGlobalAveragePooling(builder, globalAveragePooling);
_Control.addDownSamplingRate(builder, downSamplingRate);
_Control.addControlMode(builder, controlMode);
_Control.addTargetBlocks(builder, targetBlocksOffset);
_Control.addInputOverride(builder, inputOverride);
return _Control.endControl(builder);
}
};
// src/interfaces/lo-ra.ts
var flatbuffers3 = __toESM(require_flatbuffers(), 1);
// src/interfaces/lo-ramode.ts
var LoRAMode = /* @__PURE__ */ ((LoRAMode2) => {
LoRAMode2[LoRAMode2["All"] = 0] = "All";
LoRAMode2[LoRAMode2["Base"] = 1] = "Base";
LoRAMode2[LoRAMode2["Refiner"] = 2] = "Refiner";
return LoRAMode2;
})(LoRAMode || {});
// src/interfaces/lo-ra.ts
var LoRA = class _LoRA {
bb = null;
bb_pos = 0;
__init(i, bb) {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsLoRA(bb, obj) {
return (obj || new _LoRA()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
static getSizePrefixedRootAsLoRA(bb, obj) {
bb.setPosition(bb.position() + flatbuffers3.SIZE_PREFIX_LENGTH);
return (obj || new _LoRA()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
file(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 4);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
weight() {
const offset = this.bb.__offset(this.bb_pos, 6);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.6;
}
mode() {
const offset = this.bb.__offset(this.bb_pos, 8);
return offset ? this.bb.readInt8(this.bb_pos + offset) : 0 /* All */;
}
static startLoRA(builder) {
builder.startObject(3);
}
static addFile(builder, fileOffset) {
builder.addFieldOffset(0, fileOffset, 0);
}
static addWeight(builder, weight) {
builder.addFieldFloat32(1, weight, 0.6);
}
static addMode(builder, mode) {
builder.addFieldInt8(2, mode, 0 /* All */);
}
static endLoRA(builder) {
const offset = builder.endObject();
return offset;
}
static createLoRA(builder, fileOffset, weight, mode) {
_LoRA.startLoRA(builder);
_LoRA.addFile(builder, fileOffset);
_LoRA.addWeight(builder, weight);
_LoRA.addMode(builder, mode);
return _LoRA.endLoRA(builder);
}
};
// src/interfaces/sampler-type.ts
var SamplerType = /* @__PURE__ */ ((SamplerType2) => {
SamplerType2[SamplerType2["DPMPP2MKarras"] = 0] = "DPMPP2MKarras";
SamplerType2[SamplerType2["EulerA"] = 1] = "EulerA";
SamplerType2[SamplerType2["DDIM"] = 2] = "DDIM";
SamplerType2[SamplerType2["PLMS"] = 3] = "PLMS";
SamplerType2[SamplerType2["DPMPPSDEKarras"] = 4] = "DPMPPSDEKarras";
SamplerType2[SamplerType2["UniPC"] = 5] = "UniPC";
SamplerType2[SamplerType2["LCM"] = 6] = "LCM";
SamplerType2[SamplerType2["EulerASubstep"] = 7] = "EulerASubstep";
SamplerType2[SamplerType2["DPMPPSDESubstep"] = 8] = "DPMPPSDESubstep";
SamplerType2[SamplerType2["TCD"] = 9] = "TCD";
SamplerType2[SamplerType2["EulerATrailing"] = 10] = "EulerATrailing";
SamplerType2[SamplerType2["DPMPPSDETrailing"] = 11] = "DPMPPSDETrailing";
SamplerType2[SamplerType2["DPMPP2MAYS"] = 12] = "DPMPP2MAYS";
SamplerType2[SamplerType2["EulerAAYS"] = 13] = "EulerAAYS";
SamplerType2[SamplerType2["DPMPPSDEAYS"] = 14] = "DPMPPSDEAYS";
SamplerType2[SamplerType2["DPMPP2MTrailing"] = 15] = "DPMPP2MTrailing";
SamplerType2[SamplerType2["DDIMTrailing"] = 16] = "DDIMTrailing";
SamplerType2[SamplerType2["UniPCTrailing"] = 17] = "UniPCTrailing";
SamplerType2[SamplerType2["UniPCAYS"] = 18] = "UniPCAYS";
SamplerType2[SamplerType2["TCDTrailing"] = 19] = "TCDTrailing";
return SamplerType2;
})(SamplerType || {});
// src/interfaces/seed-mode.ts
var SeedMode = /* @__PURE__ */ ((SeedMode2) => {
SeedMode2[SeedMode2["Legacy"] = 0] = "Legacy";
SeedMode2[SeedMode2["TorchCpuCompatible"] = 1] = "TorchCpuCompatible";
SeedMode2[SeedMode2["ScaleAlike"] = 2] = "ScaleAlike";
SeedMode2[SeedMode2["NvidiaGpuCompatible"] = 3] = "NvidiaGpuCompatible";
return SeedMode2;
})(SeedMode || {});
// src/interfaces/reason.ts
var Reason = /* @__PURE__ */ ((Reason2) => {
Reason2[Reason2["Other"] = 0] = "Other";
Reason2[Reason2["Generate"] = 1] = "Generate";
Reason2[Reason2["Imported"] = 2] = "Imported";
Reason2[Reason2["Draw"] = 3] = "Draw";
Reason2[Reason2["Mask"] = 4] = "Mask";
Reason2[Reason2["Scribble"] = 5] = "Scribble";
Reason2[Reason2["Moodboard"] = 6] = "Moodboard";
Reason2[Reason2["DepthMap"] = 7] = "DepthMap";
Reason2[Reason2["Clear"] = 8] = "Clear";
return Reason2;
})(Reason || {});
// src/interfaces/tensor-history-node.ts
var TensorHistoryNode = class _TensorHistoryNode {
bb = null;
bb_pos = 0;
__init(i, bb) {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsTensorHistoryNode(bb, obj) {
return (obj || new _TensorHistoryNode()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
static getSizePrefixedRootAsTensorHistoryNode(bb, obj) {
bb.setPosition(bb.position() + flatbuffers4.SIZE_PREFIX_LENGTH);
return (obj || new _TensorHistoryNode()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
lineage() {
const offset = this.bb.__offset(this.bb_pos, 4);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
logicalTime() {
const offset = this.bb.__offset(this.bb_pos, 6);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
startWidth() {
const offset = this.bb.__offset(this.bb_pos, 8);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
}
startHeight() {
const offset = this.bb.__offset(this.bb_pos, 10);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
}
seed() {
const offset = this.bb.__offset(this.bb_pos, 12);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
steps() {
const offset = this.bb.__offset(this.bb_pos, 14);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
guidanceScale() {
const offset = this.bb.__offset(this.bb_pos, 16);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0;
}
strength() {
const offset = this.bb.__offset(this.bb_pos, 18);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0;
}
model(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 20);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
tensorId() {
const offset = this.bb.__offset(this.bb_pos, 22);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
maskId() {
const offset = this.bb.__offset(this.bb_pos, 24);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
depthMapId() {
const offset = this.bb.__offset(this.bb_pos, 48);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
generated() {
const offset = this.bb.__offset(this.bb_pos, 50);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true;
}
wallClock() {
const offset = this.bb.__offset(this.bb_pos, 26);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
textEdits() {
const offset = this.bb.__offset(this.bb_pos, 28);
return offset ? this.bb.readInt64(this.bb_pos + offset) : -1n;
}
textLineage() {
const offset = this.bb.__offset(this.bb_pos, 30);
return offset ? this.bb.readInt64(this.bb_pos + offset) : -1n;
}
batchSize() {
const offset = this.bb.__offset(this.bb_pos, 32);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 1;
}
sampler() {
const offset = this.bb.__offset(this.bb_pos, 34);
return offset ? this.bb.readUint8(this.bb_pos + offset) : 0 /* DPMPP2MKarras */;
}
seedMode() {
const offset = this.bb.__offset(this.bb_pos, 54);
return offset ? this.bb.readUint8(this.bb_pos + offset) : 0 /* Legacy */;
}
controls(index2, obj) {
const offset = this.bb.__offset(this.bb_pos, 58);
return offset ? (obj || new Control()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index2 * 4), this.bb) : null;
}
controlsLength() {
const offset = this.bb.__offset(this.bb_pos, 58);
return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
}
scribbleId() {
const offset = this.bb.__offset(this.bb_pos, 60);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
poseId() {
const offset = this.bb.__offset(this.bb_pos, 62);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
loras(index2, obj) {
const offset = this.bb.__offset(this.bb_pos, 64);
return offset ? (obj || new LoRA()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index2 * 4), this.bb) : null;
}
lorasLength() {
const offset = this.bb.__offset(this.bb_pos, 64);
return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
}
colorPaletteId() {
const offset = this.bb.__offset(this.bb_pos, 66);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
customId() {
const offset = this.bb.__offset(this.bb_pos, 70);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
dataStored() {
const offset = this.bb.__offset(this.bb_pos, 84);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
}
previewId() {
const offset = this.bb.__offset(this.bb_pos, 86);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
targetImageHeight() {
const offset = this.bb.__offset(this.bb_pos, 104);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
targetImageWidth() {
const offset = this.bb.__offset(this.bb_pos, 106);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
shuffleDataStored() {
const offset = this.bb.__offset(this.bb_pos, 120);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
}
generationTime() {
const offset = this.bb.__offset(this.bb_pos, 218);
return offset ? this.bb.readFloat64(this.bb_pos + offset) : 0;
}
textPrompt(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 200);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
negativeTextPrompt(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 202);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
numFrames() {
const offset = this.bb.__offset(this.bb_pos, 130);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 14;
}
clipId() {
const offset = this.bb.__offset(this.bb_pos, 204);
return offset ? this.bb.readInt64(this.bb_pos + offset) : -1n;
}
indexInAClip() {
const offset = this.bb.__offset(this.bb_pos, 206);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
}
reason() {
const offset = this.bb.__offset(this.bb_pos, 220);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0 /* Other */;
}
};
// src/interfaces/text-history-node.ts
var flatbuffers5 = __toESM(require_flatbuffers(), 1);
// src/interfaces/text-range.ts
var TextRange = class _TextRange {
bb = null;
bb_pos = 0;
__init(i, bb) {
this.bb_pos = i;
this.bb = bb;
return this;
}
static createTextRange(bb, offset, obj) {
return (obj || new _TextRange()).__init(offset, bb);
}
location() {
return this.bb.readInt32(this.bb_pos);
}
length() {
return this.bb.readInt32(this.bb_pos + 4);
}
};
// src/interfaces/text-type.ts
var TextType = /* @__PURE__ */ ((TextType2) => {
TextType2[TextType2["PositiveText"] = 0] = "PositiveText";
TextType2[TextType2["NegativeText"] = 1] = "NegativeText";
return TextType2;
})(TextType || {});
// src/interfaces/text-modification.ts
var TextModification = class _TextModification {
bb = null;
bb_pos = 0;
__init(i, bb) {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsTextModification(bb, obj) {
return (obj || new _TextModification()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
type() {
const offset = this.bb.__offset(this.bb_pos, 4);
return offset ? this.bb.readUint8(this.bb_pos + offset) : 0 /* PositiveText */;
}
range(obj) {
const offset = this.bb.__offset(this.bb_pos, 6);
return offset ? (obj || new TextRange()).__init(this.bb_pos + offset, this.bb) : null;
}
text(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 8);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
};
// src/interfaces/text-history-node.ts
var TextHistoryNode = class _TextHistoryNode {
bb = null;
bb_pos = 0;
__init(i, bb) {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsTextHistoryNode(bb, obj) {
return (obj || new _TextHistoryNode()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
static getSizePrefixedRootAsTextHistoryNode(bb, obj) {
bb.setPosition(bb.position() + flatbuffers5.SIZE_PREFIX_LENGTH);
return (obj || new _TextHistoryNode()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
lineage() {
const offset = this.bb.__offset(this.bb_pos, 4);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
logicalTime() {
const offset = this.bb.__offset(this.bb_pos, 6);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
startEdits() {
const offset = this.bb.__offset(this.bb_pos, 8);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
startPositiveText(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 10);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
startNegativeText(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 12);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
modifications(index2, obj) {
const offset = this.bb.__offset(this.bb_pos, 14);
return offset ? (obj || new TextModification()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index2 * 4), this.bb) : null;
}
modificationsLength() {
const offset = this.bb.__offset(this.bb_pos, 14);
return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
}
};
// src/helpers/projectUriResolver.ts
var SQL = null;
async function getSqlJs() {
if (!SQL) {
const { default: initSqlJs } = await import("sql.js");
SQL = await initSqlJs();
}
return SQL;
}
function isProjectUri(uri) {
return typeof uri === "string" && uri.startsWith("project://");
}
function parseProjectUri(uri) {
if (!isProjectUri(uri)) {
return null;
}
const withoutScheme = uri.slice("project://".length);
const hashIndex = withoutScheme.lastIndexOf("#");
if (hashIndex === -1) {
return null;
}
const projectPath = withoutScheme.slice(0, hashIndex);
const thumbnailId = parseInt(withoutScheme.slice(hashIndex + 1), 10);
if (isNaN(thumbnailId) || thumbnailId < 0) {
return null;
}
return { projectPath, thumbnailId };
}
function decodeThumbnailFromBlob(blob) {
const bytes = new Uint8Array(blob.buffer, blob.byteOffset, blob.byteLength);
for (const kind of ["root", "size"]) {
try {
const byteBuffer = new flatbuffers6.ByteBuffer(bytes);
const node = kind === "size" ? ThumbnailHistoryNode.getSizePrefixedRootAsThumbnailHistoryNode(byteBuffer) : ThumbnailHistoryNode.getRootAsThumbnailHistoryNode(byteBuffer);
const data = node.dataArray();
if (data?.length) return Buffer.from(data);
} catch {
}
}
return null;
}
function extractImageFromThumbnailBlob(blob) {
const jpegMarker = Buffer.from([255, 216, 255]);
const jpegStart = blob.indexOf(jpegMarker);
if (jpegStart !== -1) {
const jpegEnd = blob.lastIndexOf(Buffer.from([255, 217]));
if (jpegEnd !== -1 && jpegEnd > jpegStart) {
return blob.slice(jpegStart, jpegEnd + 2);
}
return blob.slice(jpegStart);
}
const pngMarker = Buffer.from([137, 80, 78, 71]);
const pngStart = blob.indexOf(pngMarker);
if (pngStart !== -1) {
const iendMarker = Buffer.from([
73,
69,
78,
68,
174,
66,
96,
130
]);
const pngEnd = blob.lastIndexOf(iendMarker);
if (pngEnd !== -1 && pngEnd > pngStart) {
return blob.slice(pngStart, pngEnd + 8);
}
return blob.slice(pngStart);
}
return null;
}
function normalizedThumbnailIds(thumbnailIds) {
return [...new Set([...thumbnailIds].filter((thumbnailId) => Number.isSafeInteger(thumbnailId) && thumbnailId >= 0))];
}
function thumbnailQuery(thumbnailIds) {
return `SELECT __pk0, p FROM thumbnailhistorynode WHERE __pk0 IN (${thumbnailIds.join(",")})`;
}
function decodeThumbnailRows(rows) {
const thumbnails = /* @__PURE__ */ new Map();
for (const [thumbnailId, rawBlob] of rows) {
const blob = Buffer.from(rawBlob);
const image = decodeThumbnailFromBlob(blob) ?? extractImageFromThumbnailBlob(blob);
if (image) thumbnails.set(thumbnailId, image);
}
return thumbnails;
}
function cleanupFile(filePath) {
if (filePath) try {
unlinkSync(filePath);
} catch {
}
}
async function openProjectDatabase(projectPath) {
const sqlJs = await getSqlJs();
const walPath = projectPath + "-wal";
const shmPath = projectPath + "-shm";
if (existsSync(walPath)) {
const tempFile = join(tmpdir(), `dt-project-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.sqlite3`);
try {
execFileSync("sqlite3", ["-readonly", projectPath, `VACUUM INTO '${tempFile.replace(/'/g, "''")}'`], { timeout: 1e4 });
return { db: new sqlJs.Database(readFileSync(tempFile)), tempFile };
} catch {
cleanupFile(tempFile);
const tempSourceFile = join(tmpdir(), `dt-project-source-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.sqlite3`);
copyFileSync(projectPath, tempSourceFile);
copyFileSync(walPath, `${tempSourceFile}-wal`);
if (existsSync(shmPath)) copyFileSync(shmPath, `${tempSourceFile}-shm`);
execFileSync("sqlite3", [tempSourceFile, `VACUUM INTO '${tempFile.replace(/'/g, "''")}'`], { timeout: 1e4 });
return { db: new sqlJs.Database(readFileSync(tempFile)), tempFile, tempSourceFile };
}
}
return { db: new sqlJs.Database(readFileSync(projectPath)) };
}
function closeProjectDatabase(db, tempFile, tempSourceFile) {
db?.close();
cleanupFile(tempFile);
if (tempSourceFile) {
for (const filePath of [tempSourceFile, `${tempSourceFile}-wal`, `${tempSourceFile}-shm`]) {
cleanupFile(filePath);
}
}
}
async function readThumbnailsFromSnapshot(projectPath, thumbnailIds) {
let db = null;
let tempFile;
let tempSourceFile;
try {
({ db, tempFile, tempSourceFile } = await openProjectDatabase(projectPath));
const result = db.exec(thumbnailQuery(thumbnailIds));
const rows = result.length ? result[0].values.flatMap((row) => typeof row[0] === "number" && row[1] instanceof Uint8Array ? [[row[0], row[1]]] : []) : [];
return decodeThumbnailRows(rows);
} finally {
closeProjectDatabase(db, tempFile, tempSourceFile);
}
}
async function getThumbnailsFromProject(projectPath, thumbnailIds) {
const ids = normalizedThumbnailIds(thumbnailIds);
if (ids.length === 0) return /* @__PURE__ */ new Map();
try {
return await readThumbnailsFromSnapshot(projectPath, ids);
} catch (error) {
console.error(`[ProjectUriResolver] Failed to read thumbnails from ${projectPath}:`, error);
return /* @__PURE__ */ new Map();
}
}
async function getThumbnailFromProject(projectPath, thumbnailId) {
return (await getThumbnailsFromProject(projectPath, [thumbnailId])).get(thumbnailId) ?? null;
}
async function resolveProjectUri(uri) {
const parts = parseProjectUri(uri);
if (!parts) {
console.error(`[ProjectUriResolver] Invalid project URI: ${uri}`);
return null;
}
return getThumbnailFromProject(parts.projectPath, parts.thumbnailId);
}
function bigintToSafeNumber(v) {
const n = Number(v);
if (!Number.isFinite(n)) return void 0;
if (BigInt(Math.trunc(n)) !== v) return void 0;
return n;
}
function coerceFlatbuffersString(v) {
if (typeof v === "string") return v;
if (v instanceof Uint8Array) {
try {
return Buffer.from(v).toString("utf8");
} catch {
return void 0;
}
}
return void 0;
}
function samplerToString(sampler) {
const names = {
[0 /* DPMPP2MKarras */]: "DPM++ 2M Karras",
[1 /* EulerA */]: "Euler A",
[2 /* DDIM */]: "DDIM",
[3 /* PLMS */]: "PLMS",
[4 /* DPMPPSDEKarras */]: "DPM++ SDE Karras",
[5 /* UniPC */]: "UniPC",
[6 /* LCM */]: "LCM",
[7 /* EulerASubstep */]: "Euler A Substep",
[8 /* DPMPPSDESubstep */]: "DPM++ SDE Substep",
[9 /* TCD */]: "TCD",
[10 /* EulerATrailing */]: "Euler A Trailing",
[11 /* DPMPPSDETrailing */]: "DPM++ SDE Trailing",
[12 /* DPMPP2MAYS */]: "DPM++ 2M AYS",
[13 /* EulerAAYS */]: "Euler A AYS",
[14 /* DPMPPSDEAYS */]: "DPM++ SDE AYS",
[15 /* DPMPP2MTrailing */]: "DPM++ 2M Trailing",
[16 /* DDIMTrailing */]: "DDIM Trailing",
[17 /* UniPCTrailing */]: "UniPC Trailing",
[18 /* UniPCAYS */]: "UniPC AYS"
};
return names[sampler] ?? `Unknown(${sampler})`;
}
function decodeTensorHistoryNodeFromBlob(blob) {
const u8 = new Uint8Array(blob.buffer, blob.byteOffset, blob.byteLength);
for (const kind of ["root", "size"]) {
try {
const bb = new flatbuffers6.ByteBuffer(u8);
const node = kind === "size" ? TensorHistoryNode.getSizePrefixedRootAsTensorHistoryNode(bb) : TensorHistoryNode.getRootAsTensorHistoryNode(bb);
const previewId = bigintToSafeNumber(node.previewId());
const logicalTime = bigintToSafeNumber(node.logicalTime());
const textLineage = bigintToSafeNumber(node.textLineage());
const textEdits = bigintToSafeNumber(node.textEdits());
const loras = [];
for (let i = 0; i < node.lorasLength(); i++) {
const lora = node.loras(i);
const file = coerceFlatbuffersString(lora?.file());
if (file?.trim()) loras.push({ file, weight: lora?.weight() });
}
const model = coerceFlatbuffersString(node.model()) ?? void 0;
const prompt = coerceFlatbuffersString(node.textPrompt()) ?? void 0;
const negativePrompt = coerceFlatbuffersString(node.negativeTextPrompt()) ?? void 0;
let width = node.startWidth() || node.targetImageWidth() || void 0;
let height = node.startHeight() || node.targetImageHeight() || void 0;
if (width != null && height != null && Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0 && width <= 64 && height <= 64) {
width = width * 64;
height = height * 64;
}
const generationTimeSec = node.generationTime();
const inferenceTimeMs = Number.isFinite(generationTimeSec) && generationTimeSec > 0 ? Math.round(generationTimeSec * 1e3) : void 0;
return {
seed: node.seed(),
steps: node.steps(),
cfgScale: node.guidanceScale(),
width,
height,
sampler: samplerToString(node.sampler()),
model: model?.trim() ? model : void 0,
prompt: prompt?.trim() ? prompt : void 0,
negativePrompt: negativePrompt?.trim() ? negativePrompt : void 0,
loras: loras.length ? loras : void 0,
previewId,
logicalTime,
textLineage,
textEdits,
inferenceTimeMs
};
} catch {
}
}
return null;
}
function decodeTextHistoryNodeFromBlob(blob) {
const u8 = new Uint8Array(blob.buffer, blob.byteOffset, blob.byteLength);
for (const kind of ["root", "size"]) {
try {
const bb = new flatbuffers6.ByteBuffer(u8);
const node = kind === "size" ? TextHistoryNode.getSizePrefixedRootAsTextHistoryNode(bb) : TextHistoryNode.getRootAsTextHistoryNode(bb);
const lineage = bigintToSafeNumber(node.lineage());
const logicalTime = bigintToSafeNumber(node.logicalTime());
const startEdits = bigintToSafeNumber(node.startEdits()) ?? 0;
if (lineage == null || logicalTime == null) return null;
const startPositiveText = coerceFlatbuffersString(node.startPositiveText()) ?? "";
const startNegativeText = coerceFlatbuffersString(node.startNegativeText()) ?? "";
const modifications = [];
for (let i = 0; i < node.modificationsLength(); i++) {
const mod = node.modifications(i);
if (!mod) continue;
const range = mod.range();
const text = coerceFlatbuffersString(mod.text()) ?? "";
modifications.push({ type: mod.type(), location: range?.location() ?? 0, length: range?.length() ?? 0, text });
}
return { lineage, logicalTime, startEdits, startPositiveText, startNegativeText, modifications };
} catch {
}
}
return null;
}
function applyTextEdit(base, edit) {
const loc = Math.max(0, Math.min(base.length, edit.location));
const end = Math.max(loc, Math.min(base.length, loc + Math.max(0, edit.length)));
return base.slice(0, loc) + edit.text + base.slice(end);
}
function replayTextHistory(history, upToEdits) {
let prompt = history.startPositiveText ?? "";
let negativePrompt = history.startNegativeText ?? "";
let toApply = history.modifications.length;
if (upToEdits != null && Number.isFinite(upToEdits)) {
const remaining = upToEdits - history.startEdits;
toApply = remaining <= 0 ? 0 : Math.min(history.modifications.length, remaining);
}
for (let i = 0; i < toApply; i++) {
const edit = history.modifications[i];
if (edit.type === 0 /* PositiveText */) prompt = applyTextEdit(prompt, edit);
else negativePrompt = applyTextEdit(negativePrompt, edit);
}
return { prompt, negativePrompt };
}
function promptLooksTaggy(s) {
const t = s.toLowerCase();
return t.includes("best quality") || t.includes("high quality") || t.includes("trending on artstation") || t.includes("award-winning") || t.includes("cgsociety");
}
function scorePromptCandidate(s) {
const t = s.trim();
if (t.length < 10) return -1;
if (t.startsWith("{") || t.startsWith("[")) return -1;
if (/\.(ckpt|safetensors|gguf|pt|pth)$/i.test(t)) return -1;
if (/^\w+:\/\//.test(t)) return -1;
if (/^\/[A-Za-z0-9_\-./]+$/.test(t)) return -1;
let score = t.length;
const words = t.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
score += new Set(words).size * 3;
if (t.includes(".")) score += 10;
if (t.includes("'")) score += 5;
const commaCount = t.split(",").length - 1;
if (commaCount >= 6) score -= 25;
if (promptLooksTaggy(t)) score -= 80;
if (/timings|duration|profile/i.test(t)) score -= 30;
if (/[{}]/.test(t)) score -= 20;
return score;
}
function pickTextHistoryForGeneration(historyByLineage, lineage, generationLogicalTime) {
const rows = historyByLineage.get(lineage) ?? [];
if (!rows.length) return null;
const chosen = [...rows].filter((r) => r.logicalTime <= generationLogicalTime).sort((a, b) => b.logicalTime - a.logicalTime)[0];
return chosen ?? rows[rows.length - 1];
}
function pickTextPromptForGeneration(textByLineage, generationLogicalTime) {
if (textByLineage.size === 0) return null;
const lineage = textByLineage.has(0) ? 0 : [...textByLineage.entries()].sort((a, b) => b[1].length - a[1].length)[0][0];
const rows = textByLineage.get(lineage) ?? [];
if (!rows.length) return null;
const candidate = [...rows].filter((r) => r.logicalTime <= generationLogicalTime).sort((a, b) => b.logicalTime - a.logicalTime)[0];
const chosen = candidate ?? rows[rows.length - 1];
return { prompt: chosen.prompt, negativePrompt: chosen.negativePrompt };
}
function findTensorHistoryRowForThumbnail(db, thumbnailId) {
try {
const linkResult = db.exec(`SELECT rowid FROM tensorhistorynode__f86 WHERE f86 = ${thumbnailId}`);
const rowid = linkResult.length && linkResult[0].values.length ? linkResult[0].values[0][0] : void 0;
if (rowid != null) {
const rowResult = db.exec(`SELECT rowid, p FROM tensorhistorynode WHERE rowid = ${rowid}`);
if (rowResult.length && rowResult[0].values.length) {
const row = rowResult[0].values[0];
return { rowid: row[0], p: Buffer.from(row[1]) };
}
}
} catch {
}
const scanResult = db.exec("SELECT rowid, p FROM tensorhistorynode WHERE __pk1 >= 1 ORDER BY rowid");
if (!scanResult.length) return null;
for (const row of scanResult[0].values) {
const blob = Buffer.from(row[1]);
const decoded = decodeTensorHistoryNodeFromBlob(blob);
if (decoded?.previewId === thumbnailId) return { rowid: row[0], p: blob };
}
return null;
}
async function getDrawThingsGenerationMetadata(projectPath, thumbnailId) {
let db = null;
let tempFile;
let tempSourceFile;
try {
({ db, tempFile, tempSourceFile } = await openProjectDatabase(projectPath));
const target2 = findTensorHistoryRowForThumbnail(db, thumbnailId);
if (!target2) return null;
const decoded = decodeTensorHistoryNodeFromBlob(target2.p);
if (!decoded || decoded.inferenceTimeMs === void 0) return null;
const textByLineage = /* @__PURE__ */ new Map();
const textHistoryByLineage = /* @__PURE__ */ new Map();
const textResult = db.exec("SELECT __pk0, __pk1, p FROM texthistorynode ORDER BY __pk0, __pk1");
if (textResult.length && textResult[0].values.length) {
for (const row of textResult[0].values) {
const decodedText = decodeTextHistoryNodeFromBlob(Buffer.from(row[2]));
if (!decodedText) continue;
textHistoryByLineage.set(decodedText.lineage, [...textHistoryByLineage.get(decodedText.lineage) ?? [], decodedText]);
const final = replayTextHistory(decodedText);
const prompt2 = final.prompt.trim();
if (!prompt2) continue;
const score = scorePromptCandidate(prompt2);
if (score < 0) continue;
textByLineage.set(decodedText.lineage, [
...textByLineage.get(decodedText.lineage) ?? [],
{ lineage: decodedText.lineage, logicalTime: decodedText.logicalTime, prompt: prompt2, negativePrompt: final.negativePrompt.trim() || void 0, score }
]);
}
}
let prompt = decoded.prompt;
let negativePrompt = decoded.negativePrompt;
const generationLogicalTime = decoded.logicalTime ?? 0;
if (decoded.textLineage != null && decoded.textEdits != null) {
const history = pickTextHistoryForGeneration(textHistoryByLineage, decoded.textLineage, generationLogicalTime);
if (history) {
const rebuilt = replayTextHistory(history, decoded.textEdits);
prompt = rebuilt.prompt;
negativePrompt = rebuilt.negativePrompt || negativePrompt;
} else {
const textCand = pickTextPromptForGeneration(textByLineage, generationLogicalTime);
if (textCand) {
prompt = textCand.prompt;
negativePrompt = textCand.negativePrompt || negativePrompt;
}
}
}
return {
prompt,
negativePrompt,
model: decoded.model,
sampler: decoded.sampler,
steps: decoded.steps,
guidanceScale: decoded.cfgScale,
seed: decoded.seed,
width: decoded.width,
height: decoded.height,
loras: decoded.loras,
inferenceTimeMs: decoded.inferenceTimeMs
};
} catch (error) {
console.error(`[ProjectUriResolver] Failed to read generation metadata from ${projectPath}:`, error);
return null;
} finally {
closeProjectDatabase(db, tempFile, tempSourceFile);
}
}
async function resolveProjectGenerationMetadata(uri) {
const parts = parseProjectUri(uri);
if (!parts) {
console.error(`[ProjectUriResolver] Invalid project URI: ${uri}`);
return null;
}
return getDrawThingsGenerationMetadata(parts.projectPath, parts.thumbnailId);
}
function detectImageMimeType(buf) {
if (!buf || buf.length < 3) return null;
if (buf[0] === 255 && buf[1] === 216 && buf[2] === 255) return "image/jpeg";
if (buf.length >= 8 && buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71 && buf[4] === 13 && buf[5] === 10 && buf[6] === 26 && buf[7] === 10) return "image/png";
if (buf.length >= 12 && buf[0] === 82 && buf[1] === 73 && buf[2] === 70 && buf[3] === 70 && buf[8] === 87 && buf[9] === 69 && buf[10] === 66 && buf[11] === 80) return "image/webp";
if (buf.length >= 6 && buf[0] === 71 && buf[1] === 73 && buf[2] === 70 && buf[3] === 56 && (buf[4] === 55 || buf[4] === 57) && buf[5] === 97) return "image/gif";
return null;
}
function detectProjectImageType(buf) {
const mimeType = detectImageMimeType(buf);
if (mimeType === "image/jpeg") return "jpeg";
if (mimeType === "image/png") return "png";
return null;
}
// src/vision-promotion.ts
async function toOpenAIPromptParts(items) {
const parts = [];
for (const it of items) {
const label = it.label || "Image";
parts.push({ type: "text", text: label });
const buf = await fs5.promises.readFile(it.previewAbs);
const b64 = buf.toString("base64");
const mime = detectImageMimeType(buf);
if (!mime) throw new Error(`Unsupported image bytes: ${it.previewAbs}`);
parts.push({ type: "image_url", image_url: { url: `data:${mime};base64,${b64}` } });
}
return parts;
}
// src/helpers/agentModelUnload.ts
import fs8 from "fs";
import path7 from "path";
// src/media-promotion-core/state.ts
import fs7 from "fs";
import path6 from "path";
// src/helpers/fileLock.ts
import fs6 from "fs";
var POLL_MS = 15;
var ACQUIRE_TIMEOUT_MS = 15e3;
var MAX_LOCK_AGE_MS = 3e4;
var EMPTY_LOCK_GRACE_MS = 1e3;
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function pidAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch (e) {
return e?.code === "EPERM";
}
}
async function readLockHolder(lockPath) {
try {
const [raw, st] = await Promise.all([fs6.promises.readFile(lockPath, "utf-8"), fs6.promises.stat(lockPath)]);
const pid = parseInt(raw.trim(), 10);
return { pid: Number.isFinite(pid) && pid > 0 ? pid : null, ageMs: Date.now() - st.mtimeMs };
} catch (e) {
if (e?.code === "ENOENT") return null;
throw e;
}
}
async function reclaimIfStale(lockPath) {
const holder = await readLockHolder(lockPath);
if (!holder) return true;
const stale = holder.ageMs > MAX_LOCK_AGE_MS || holder.pid === null && holder.ageMs > EMPTY_LOCK_GRACE_MS || holder.pid !== null && !pidAlive(holder.pid);
if (!stale) return false;
const again = await readLockHolder(lockPath);
if (!again || again.pid !== holder.pid) return true;
await fs6.promises.rm(lockPath, { force: true });
return true;
}
async function withFileLock(lockPath, fn) {
const deadline = Date.now() + ACQUIRE_TIMEOUT_MS;
for (; ; ) {
try {
const handle = await fs6.promises.open(lockPath, "wx");
try {
await handle.writeFile(String(process.pid));
} finally {
await handle.close();
}
break;
} catch (e) {
if (e?.code !== "EEXIST") throw e;
if (await reclaimIfStale(lockPath)) continue;
if (Date.now() > deadline) throw new Error(`Timed out waiting for lock ${lockPath}`);
await sleep(POLL_MS);
}
}
try {
return await fn();
} finally {
await fs6.promises.rm(lockPath, { force: true });
}
}
function uniqueTmpPath(dst) {
return `${dst}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`;
}
// src/media-promotion-core/state.ts
function localTimestamp(d = /* @__PURE__ */ new Date()) {
const pad = (n, len = 2) => String(n).padStart(len, "0");
const year = d.getFullYear();
const month = pad(d.getMonth() + 1);
const day = pad(d.getDate());
const hours = pad(d.getHours());
const minutes = pad(d.getMinutes());
const seconds = pad(d.getSeconds());
const millis = pad(d.getMilliseconds(), 3);
const tzOffset = -d.getTimezoneOffset();
const tzSign = tzOffset >= 0 ? "+" : "-";
const tzHours = pad(Math.floor(Math.abs(tzOffset) / 60));
const tzMins = pad(Math.abs(tzOffset) % 60);
return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${millis}${tzSign}${tzHours}:${tzMins}`;
}
function tsForFilename(d = /* @__PURE__ */ new Date()) {
const year = d.getUTCFullYear();
const month = String(d.getUTCMonth() + 1).padStart(2, "0");
const day = String(d.getUTCDate()).padStart(2, "0");
const hours = String(d.getUTCHours()).padStart(2, "0");
const minutes = String(d.getUTCMinutes()).padStart(2, "0");
const seconds = String(d.getUTCSeconds()).padStart(2, "0");
const millis = String(d.getUTCMilliseconds()).padStart(3, "0");
return `${year}${month}${day}T${hours}${minutes}${seconds}${millis}Z`;
}
var STATE_BASE = /* @__PURE__ */ Symbol.for("dtc.chatMediaState.baseRaw");
function setStateBase(state, raw) {
Object.defineProperty(state, STATE_BASE, {
value: raw,
enumerable: false,
configurable: true,
writable: true
});
}
function emptyState() {
return {
attachments: [],
variants: [],
pictures: [],
images: [],
counters: {}
};
}
async function readState(chatWd) {
const p = path6.join(chatWd, "chat_media_state.json");
let raw = "";
try {
raw = await fs7.promises.readFile(p, "utf-8");
} catch {
raw = "";
}
let state;
try {
state = raw ? normalizeState(JSON.parse(raw)) : emptyState();
} catch {
state = emptyState();
}
setStateBase(state, raw);
return state;
}
var isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
function stableStringify(v) {
if (Array.isArray(v)) return `[${v.map(stableStringify).join(",")}]`;
if (isPlainObject(v)) {
return `{${Object.keys(v).filter((k) => v[k] !== void 0).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(v[k])}`).join(",")}}`;
}
return JSON.stringify(v) ?? "undefined";
}
var jsonEqual = (a, b) => stableStringify(a) === stableStringify(b);
var KEYED_COLLECTIONS = {
attachments: "a",
variants: "v",
pictures: "p",
images: "i"
};
function mergeKeyedRecords(base, mine, theirs, keyField) {
const index2 = (arr) => new Map(arr.map((r) => [r?.[keyField], r]));
const B = index2(base);
const M = index2(mine);
const T = index2(theirs);
const out = [];
for (const k of /* @__PURE__ */ new Set([...M.keys(), ...T.keys()])) {
const inB = B.has(k);
const inM = M.has(k);
const inT = T.has(k);
if (inM && inT) {
out.push(mergeStateValue(B.get(k), M.get(k), T.get(k), ""));
} else if (inM) {
if (!inB || !jsonEqual(M.get(k), B.get(k))) out.push(M.get(k));
} else if (!inB || !jsonEqual(T.get(k), B.get(k))) {
out.push(T.get(k));
}
}
return out;
}
function mergePrimitiveSet(base, mine, theirs) {
const baseSet = new Set(base);
const mineSet = new Set(mine);
const removedByMe = new Set(base.filter((x) => !mineSet.has(x)));
const out = theirs.filter((x) => !removedByMe.has(x));
for (const x of mine) if (!baseSet.has(x) && !out.includes(x)) out.push(x);
return out;
}
function mergeStateValue(base, mine, theirs, p) {
if (jsonEqual(mine, base)) return theirs;
if (jsonEqual(theirs, base) || jsonEqual(mine, theirs)) return mine;
if (isPlainObject(mine) && isPlainObject(theirs)) {
const b = isPlainObject(base) ? base : {};
const out = {};
for (const k of /* @__PURE__ */ new Set([...Object.keys(mine), ...Object.keys(theirs), ...Object.keys(b)])) {
const v = mergeStateValue(b[k], mine[k], theirs[k], p ? `${p}.${k}` : k);
if (v !== void 0) out[k] = v;
}
return out;
}
if (Array.isArray(mine) && Array.isArray(theirs)) {
const b = Array.isArray(base) ? base : [];
const keyField = KEYED_COLLECTIONS[p];
if (keyField) return mergeKeyedRecords(b, mine, theirs, keyField);
const prim = (x) => x === null || typeof x !== "object";
if (b.every(prim) && mine.every(prim) && theirs.every(prim)) return mergePrimitiveSet(b, mine, theirs);
return mine;
}
if (p.startsWith("counters.") && typeof mine === "number" && typeof theirs === "number") {
return Math.max(mine, theirs);
}
return mine;
}
async function readRawOrEmpty(file) {
try {
return await fs7.promises.readFile(file, "utf-8");
} catch {
return "";
}
}
function parseStateOrEmpty(raw) {
try {
return raw ? normalizeState(JSON.parse(raw)) : emptyState();
} catch {
return emptyState();
}
}
async function writeStateAtomic(chatWd, state) {
const dst = path6.join(chatWd, "chat_media_state.json");
await withFileLock(`${dst}.lock`, async () => {
const baseRaw = state[STATE_BASE];
if (typeof baseRaw === "string") {
const currentRaw = await readRawOrEmpty(dst);
if (currentRaw !== baseRaw) {
const merged = mergeStateValue(
JSON.parse(JSON.stringify(parseStateOrEmpty(baseRaw))),
JSON.parse(JSON.stringify(state)),
JSON.parse(JSON.stringify(parseStateOrEmpty(currentRaw))),
""
);
for (const k of Object.keys(state)) delete state[k];
Object.assign(state, merged);
console.info(`[chat_media_state] merged concurrent changes in ${dst}`);
}
}
await writeStateFile(chatWd, state);
});
}
async function writeStateFile(chatWd, state) {
const dst = path6.join(chatWd, "chat_media_state.json");
const tmp = uniqueTmpPath(dst);
if (Array.isArray(state.attachments) && state.attachments.length > 1) {
state.attachments.sort((a, b) => (a.a ?? 0) - (b.a ?? 0));
}
if (Array.isArray(state.variants) && state.variants.length > 1) {
state.variants.sort((a, b) => (a.v ?? 0) - (b.v ?? 0));
}
if (Array.isArray(state.pictures) && state.pictures.length > 1) {
state.pictures.sort((a, b) => (a.p ?? 0) - (b.p ?? 0));
}
if (Array.isArray(state.images) && state.images.length > 1) {
state.images.sort((a, b) => (a.i ?? 0) - (b.i ?? 0));
}
let pretty = JSON.stringify(state, null, 2);
pretty = pretty.replace(
/"(lastPromotedAttachmentAs|lastPromotedVariantVs|lastPromotedImageIs|lastPixelPromotedAttachmentAs|lastPixelPromotedVariantVs|lastPixelPromotedImageIs|injectedMarkdown)":\s*\[\s*\n([\s\S]*?)\n\s*\]/g,
(match, key, content) => {
const items = content.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
return `"${key}": [${items.join(", ")}]`;
}
);
await fs7.promises.writeFile(tmp, pretty, "utf-8");
await fs7.promises.rename(tmp, dst);
setStateBase(state, pretty);
}
function normalizeState(s) {
let lastPromotedAttachmentAs;
if (Array.isArray(s?.lastPromotedAttachmentAs)) {
lastPromotedAttachmentAs = s.lastPromotedAttachmentAs.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
} else if (Array.isArray(s?.lastPromotedAttachmentNs)) {
lastPromotedAttachmentAs = s.lastPromotedAttachmentNs.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
} else if (typeof s?.lastPromotedAttachmentN === "number") {
lastPromotedAttachmentAs = [s.lastPromotedAttachmentN];
} else if (typeof s?.lastPromotedAttachmentA === "number") {
lastPromotedAttachmentAs = [s.lastPromotedAttachmentA];
}
let lastPromotedVariantVs;
if (Array.isArray(s?.lastPromotedVariantVs)) {
lastPromotedVariantVs = s.lastPromotedVariantVs.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
}
let lastPromotedImageIs;
if (Array.isArray(s?.lastPromotedImageIs)) {
lastPromotedImageIs = s.lastPromotedImageIs.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
}
let lastPixelPromotedAttachmentAs;
if (Array.isArray(s?.lastPixelPromotedAttachmentAs)) {
lastPixelPromotedAttachmentAs = s.lastPixelPromotedAttachmentAs.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
} else if (Array.isArray(s?.lastPixelPromotedAttachmentNs)) {
lastPixelPromotedAttachmentAs = s.lastPixelPromotedAttachmentNs.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
}
let lastPixelPromotedVariantVs;
if (Array.isArray(s?.lastPixelPromotedVariantVs)) {
lastPixelPromotedVariantVs = s.lastPixelPromotedVariantVs.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
}
let lastPixelPromotedImageIs;
if (Array.isArray(s?.lastPixelPromotedImageIs)) {
lastPixelPromotedImageIs = s.lastPixelPromotedImageIs.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
}
const normalizeNumberArray = (v) => {
if (!Array.isArray(v)) return void 0;
const a = v.filter((x) => typeof x === "number" && Number.isFinite(x)).map((x) => Math.floor(x)).filter((x) => x > 0);
if (!a.length) return void 0;
return Array.from(new Set(a)).sort((x, y) => x - y);
};
const pendingReviewPromotion = (() => {
const pr = s?.pendingReviewPromotion;
if (!pr || typeof pr !== "object") return void 0;
const requestedAt = typeof pr.requestedAt === "string" && pr.requestedAt.trim() ? String(pr.requestedAt) : "";
const targets = pr.targets && typeof pr.targets === "object" ? pr.targets : null;
if (!requestedAt || !targets) return void 0;
const a = normalizeNumberArray(targets.a);
const v = normalizeNumberArray(targets.v);
const i = normalizeNumberArray(targets.i);
const p = normalizeNumberArray(targets.p);
if (!a && !v && !i && !p) return void 0;
const ttlMs = typeof pr.ttlMs === "number" && Number.isFinite(pr.ttlMs) && pr.ttlMs > 0 ? pr.ttlMs : void 0;
return {
requestedAt,
requestedByToolCallId: typeof pr.requestedByToolCallId === "string" && pr.requestedByToolCallId.trim() ? String(pr.requestedByToolCallId) : void 0,
reason: typeof pr.reason === "string" && pr.reason.trim() ? String(pr.reason) : void 0,
ttlMs,
targets: {
a,
v,
i,
p
}
};
})();
const pendingSequenceReview = (() => {
const ps = s?.pendingSequenceReview;
if (!ps || typeof ps !== "object") return void 0;
const requestedAt = typeof ps.requestedAt === "string" && ps.requestedAt.trim() ? String(ps.requestedAt) : "";
const movAbs = typeof ps.movAbs === "string" && ps.movAbs.trim() ? String(ps.movAbs) : "";
const variant = typeof ps.variant === "number" && Number.isFinite(ps.variant) ? Math.floor(ps.variant) : 0;
if (!requestedAt || !movAbs || variant <= 0) return void 0;
const fps = typeof ps.fps === "number" && Number.isFinite(ps.fps) && ps.fps > 0 ? ps.fps : 2;
const ttlMs = typeof ps.ttlMs === "number" && Number.isFinite(ps.ttlMs) && ps.ttlMs > 0 ? ps.ttlMs : void 0;
return {
requestedAt,
movAbs,
variant,
variantLabel: typeof ps.variantLabel === "string" && ps.variantLabel.trim() ? String(ps.variantLabel) : void 0,
fps,
ttlMs
};
})();
const n = {
attachments: Array.isArray(s?.attachments) ? s.attachments : [],
variants: Array.isArray(s?.variants) ? s.variants : [],
pictures: Array.isArray(s?.pictures) ? s.pictures : [],
images: Array.isArray(s?.images) ? s.images : [],
pendingReviewPromotion,
pendingSequenceReview,
lastEvent: s?.lastEvent,
lastCanvasNotation: typeof s?.lastCanvasNotation === "string" ? s.lastCanvasNotation : void 0,
lastCanvasAt: typeof s?.lastCanvasAt === "string" ? s.lastCanvasAt : void 0,
counters: typeof s?.counters === "object" && s?.counters ? s.counters : {},
injectedMarkdown: Array.isArray(s?.injectedMarkdown) ? s.injectedMarkdown : void 0,
injectedContent: Array.isArray(s?.injectedContent) ? s.injectedContent.filter((x) => typeof x === "string" && x.trim()) : void 0,
lastVariantsTs: typeof s?.lastVariantsTs === "string" ? s.lastVariantsTs : void 0,
lastPromotedTs: typeof s?.lastPromotedTs === "string" ? s.lastPromotedTs : void 0,
lastPromotedAttachmentAs,
// Keep deprecated field for backward compat during transition
lastPromotedAttachmentA: typeof s?.lastPromotedAttachmentA === "number" ? s.lastPromotedAttachmentA : typeof s?.lastPromotedAttachmentN === "number" ? s.lastPromotedAttachmentN : void 0,
lastPromotedVariantVs,
lastPromotedImageIs,
lastPixelPromotedAt: typeof s?.lastPixelPromotedAt === "string" ? s.lastPixelPromotedAt : void 0,
lastPixelPromotedAttachmentAs,
lastPixelPromotedVariantVs,
lastPixelPromotedImageIs,
forcePixelPromotionNextTurn: typeof s?.forcePixelPromotionNextTurn === "boolean" ? s.forcePixelPromotionNextTurn : void 0,
forcePixelPromotionSetAt: typeof s?.forcePixelPromotionSetAt === "string" ? s.forcePixelPromotionSetAt : void 0,
forcePixelPromotionReason: typeof s?.forcePixelPromotionReason === "string" ? s.forcePixelPromotionReason : void 0,
lastSsotMessageCount: typeof s?.lastSsotMessageCount === "number" && Number.isFinite(s.lastSsotMessageCount) ? s.lastSsotMessageCount : void 0
};
if (n.attachments.length > 1) {
n.attachments.sort((a, b) => (a.a ?? 0) - (b.a ?? 0));
}
if (n.variants.length > 1) {
n.variants.sort((a, b) => (a.v ?? 0) - (b.v ?? 0));
}
if (n.pictures.length > 1) {
n.pictures.sort((a, b) => (a.p ?? 0) - (b.p ?? 0));
}
if (n.images.length > 1) {
n.images.sort((a, b) => (a.i ?? 0) - (b.i ?? 0));
}
return n;
}
function upsertAttachment(state, rec) {
const existing = Array.isArray(state.attachments) ? state.attachments : [];
const createdAt = rec.createdAt ?? localTimestamp();
const matches = (a) => {
if (rec.originAbs && a.originAbs && a.originAbs === rec.originAbs)
return true;
return a.filename === rec.filename && a.preview === rec.preview;
};
const idx = existing.findIndex(matches);
if (idx >= 0) {
const keep = existing[idx];
const updated = {
...keep,
filename: rec.filename,
origin: rec.origin,
originAbs: rec.originAbs,
originalName: rec.originalName ?? keep.originalName,
turnId: rec.turnId ?? keep.turnId,
preview: rec.preview,
createdAt: keep.createdAt,
a: keep.a
};
const next2 = [updated, ...existing.filter((_, i) => i !== idx)];
const changed = JSON.stringify(next2) !== JSON.stringify(existing);
if (changed) {
state.attachments = next2;
state.lastEvent = { type: "attachment", at: localTimestamp() };
}
return { changed, state, record: updated };
}
const nextA = rec.a ?? Math.max(1, state.counters.nextAttachmentA ?? 1);
const finalRec = {
filename: rec.filename,
origin: rec.origin,
originAbs: rec.originAbs,
originalName: rec.originalName,
turnId: rec.turnId,
preview: rec.preview,
createdAt,
a: nextA
};
const next = [finalRec, ...existing];
state.attachments = next;
state.counters.nextAttachmentA = nextA + 1;
state.lastEvent = { type: "attachment", at: localTimestamp() };
return { changed: true, state, record: finalRec };
}
function normalizeString(val) {
return typeof val === "string" ? String(val) : void 0;
}
function normalizeNumber(val) {
return typeof val === "number" && Number.isFinite(val) ? val : void 0;
}
var COMMON_MEDIA_KEYS = /* @__PURE__ */ new Set([
"filename",
"preview",
"sourceTool",
"pluginId",
"sourceUrl",
"title",
"confidence",
"width",
"height",
"pageUrl",
"turnId",
"createdAt",
"kind",
"v",
"p",
"i"
]);
function buildMediaRecord(input, index2, indexField, createdAt, existingIndex) {
const base = {
filename: input.filename,
preview: input.preview,
sourceTool: normalizeString(input.sourceTool),
pluginId: normalizeString(input.pluginId),
sourceUrl: normalizeString(input.sourceUrl),
title: normalizeString(input.title),
confidence: normalizeString(input.confidence),
width: normalizeNumber(input.width),
height: normalizeNumber(input.height),
pageUrl: normalizeString(input.pageUrl),
turnId: normalizeNumber(input.turnId),
createdAt: input.createdAt ?? createdAt
};
if (input.kind === "tool_result" || input.kind === "generated") {
base.kind = input.kind;
}
for (const key of Object.keys(input)) {
if (!COMMON_MEDIA_KEYS.has(key) && input[key] != null) {
base[key] = input[key];
}
}
base[indexField] = existingIndex ?? index2;
return base;
}
function upgradeExistingRecord(existing, incoming, indexField) {
const incomingIndex = incoming[indexField];
if (existing[indexField] == null && typeof incomingIndex === "number") {
existing[indexField] = incomingIndex;
}
const fieldsToUpgrade = [
"sourceTool",
"pluginId",
"sourceUrl",
"title",
"confidence",
"pageUrl",
"kind"
];
for (const field of fieldsToUpgrade) {
if (existing[field] == null && incoming[field] != null) {
existing[field] = incoming[field];
}
}
if (existing.width == null && typeof incoming.width === "number") {
existing.width = incoming.width;
}
if (existing.height == null && typeof incoming.height === "number") {
existing.height = incoming.height;
}
if (existing.turnId == null && typeof incoming.turnId === "number") {
existing.turnId = incoming.turnId;
}
for (const key of Object.keys(incoming)) {
if (!COMMON_MEDIA_KEYS.has(key) && existing[key] == null && incoming[key] != null) {
existing[key] = incoming[key];
}
}
}
function appendMediaItems(state, items, config) {
if (!items.length) return { changed: false, state, records: [] };
const {
stateArrayKey,
counterKey,
indexField,
eventType,
getDedupeKey,
filter
} = config;
const existing = Array.isArray(
state[stateArrayKey]
) ? [...state[stateArrayKey]] : [];
const maxExistingIndex = existing.reduce((max, r) => {
const idx = r[indexField];
return Math.max(max, typeof idx === "number" && Number.isFinite(idx) ? idx : 0);
}, 0);
const counterIndex = state.counters[counterKey] ?? 1;
const baseIndex = Math.max(1, counterIndex, maxExistingIndex + 1);
const createdAt = localTimestamp();
let newOnes = items.map(
(it, idx) => buildMediaRecord(
it,
baseIndex + idx,
indexField,
createdAt,
it[indexField]
)
);
if (filter) {
newOnes = newOnes.filter(filter);
}
const existingByKey = /* @__PURE__ */ new Map();
for (const item of existing) {
const key = getDedupeKey(item);
if (key) existingByKey.set(key, item);
}
const all = [...existing];
for (const r of newOnes) {
const key = getDedupeKey(r);
const existingItem = key ? existingByKey.get(key) : void 0;
if (!existingItem) {
all.push(r);
if (key) existingByKey.set(key, r);
} else {
upgradeExistingRecord(
existingItem,
r,
indexField
);
}
}
all.sort((a, b) => {
const aIdx = a[indexField] ?? 0;
const bIdx = b[indexField] ?? 0;
return aIdx - bIdx || String(a.createdAt || "").localeCompare(String(b.createdAt || ""));
});
const changed = JSON.stringify(all) !== JSON.stringify(state[stateArrayKey] || []);
if (changed) {
state[stateArrayKey] = all;
const lastIndex = all.at(-1)?.[indexField];
state.counters[counterKey] = (typeof lastIndex === "number" ? lastIndex : baseIndex - 1) + 1;
state.lastEvent = { type: eventType, at: localTimestamp() };
}
return { changed, state, records: newOnes };
}
var VARIANT_APPEND_CONFIG = {
stateArrayKey: "variants",
counterKey: "nextVariantV",
indexField: "v",
eventType: "variants",
getDedupeKey: (item) => `${item.filename}|${item.preview}`
};
var PICTURE_APPEND_CONFIG = {
stateArrayKey: "pictures",
counterKey: "nextPictureP",
indexField: "p",
eventType: "pictures",
getDedupeKey: (item) => item.sourceUrl ? item.sourceUrl : `${item.filename}|${item.preview}`,
filter: (item) => !!String(item.sourceUrl || "").trim()
};
var IMAGE_APPEND_CONFIG = {
stateArrayKey: "images",
counterKey: "nextImageI",
indexField: "i",
eventType: "images",
getDedupeKey: (item) => `${item.filename}|${item.preview}`
};
function appendVariants(state, items) {
return appendMediaItems(
state,
items,
VARIANT_APPEND_CONFIG
);
}
function appendPictures(state, items) {
return appendMediaItems(
state,
items,
PICTURE_APPEND_CONFIG
);
}
function appendImages(state, items) {
return appendMediaItems(
state,
items,
IMAGE_APPEND_CONFIG
);
}
function referencedFiles(state) {
const s = /* @__PURE__ */ new Set();
for (const a of state.attachments) {
if (a.filename) s.add(a.filename);
if (a.preview) s.add(a.preview);
}
for (const v of state.variants) {
if (v.filename) s.add(v.filename);
if (v.preview) s.add(v.preview);
}
for (const p of state.pictures || []) {
if (p.filename) s.add(p.filename);
if (p.preview) s.add(p.preview);
}
for (const i of state.images || []) {
if (i.filename) s.add(i.filename);
if (i.preview) s.add(i.preview);
}
s.add("chat_media_state.json");
return s;
}
function fileInWd(absOrRel, chatWd) {
return path6.isAbsolute(absOrRel) ? absOrRel : path6.join(chatWd, absOrRel);
}
// src/helpers/agentModelUnload.ts
async function getAxios() {
return (await import("axios")).default;
}
function normalizeLmApiRoot(baseUrl) {
return String(baseUrl || "").trim().replace(/\/(api\/v1|v1)\/?$/i, "").replace(/\/+$/, "");
}
function buildLmApiAuthHeaders(apiKey) {
if (typeof apiKey === "string" && apiKey.trim()) {
return { Authorization: `Bearer ${apiKey.trim()}` };
}
return {};
}
function appendToPluginLog(line) {
try {
const logsDir2 = getLogsDir();
fs8.mkdirSync(logsDir2, { recursive: true });
fs8.appendFileSync(
path7.join(logsDir2, "generate-image-plugin.log"),
`${localTimestamp()} - ${line}
`
);
} catch {
}
}
async function unloadAgentModel(opts) {
const apiRoot = normalizeLmApiRoot(opts.baseUrl);
const unloadUrl = `${apiRoot}/api/v1/models/unload`;
try {
const axios2 = await getAxios();
await axios2.post(
unloadUrl,
{ instance_id: opts.modelKey },
{
timeout: 15e3,
headers: {
"Content-Type": "application/json",
...buildLmApiAuthHeaders(opts.apiKey)
}
}
);
appendToPluginLog(`[INFO] [AgentModel] \u2713 Unloaded: ${opts.modelKey}`);
console.info(`[INFO] [AgentModel] Unloaded model to free VRAM: ${opts.modelKey}`);
return true;
} catch (e) {
console.warn(`[AgentModel] Unload failed (non-fatal):`, e?.message || e);
return false;
}
}
// src/helpers/activeChatContext.ts
import { AsyncLocalStorage } from "async_hooks";
var activeChatContext = null;
var STORE_KEY = /* @__PURE__ */ Symbol.for("draw-things.activeChatContext");
function store() {
const holder = globalThis;
let existing = holder[STORE_KEY];
if (!existing) {
existing = new AsyncLocalStorage();
holder[STORE_KEY] = existing;
}
return existing;
}
function setActiveChatContext(ctx) {
const next = {
chatId: String(ctx.chatId),
workingDir: String(ctx.workingDir),
setAtMs: Date.now(),
requestId: ctx.requestId
};
activeChatContext = next;
store().enterWith(next);
}
function getActiveChatContext(opts) {
const scoped = store().getStore();
if (scoped) return scoped;
const maxAgeMs = typeof opts?.maxAgeMs === "number" && Number.isFinite(opts.maxAgeMs) ? Math.max(0, Math.floor(opts.maxAgeMs)) : 60 * 1e3;
if (!activeChatContext) return null;
if (maxAgeMs === 0) return activeChatContext;
const ageMs = Date.now() - activeChatContext.setAtMs;
if (!Number.isFinite(ageMs) || ageMs < 0) return null;
if (ageMs > maxAgeMs) return null;
return activeChatContext;
}
// src/helpers/attachments.ts
import { promises as fsp2 } from "fs";
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
import path8, { join as join3, extname } from "path";
import os2 from "os";
// src/helpers/findLMStudioHome.ts
import {
existsSync as existsSync2,
readFileSync as readFileSync2,
realpathSync,
writeFileSync
} from "fs";
import { homedir } from "os";
import { join as join2 } from "path";
var lmstudioHome = null;
function findLMStudioHome() {
if (lmstudioHome !== null) {
return lmstudioHome;
}
const resolvedHomeDir = realpathSync(homedir());
const pointerFilePath = join2(resolvedHomeDir, ".lmstudio-home-pointer");
if (existsSync2(pointerFilePath)) {
const candidate = readFileSync2(pointerFilePath, "utf-8").trim();
try {
if (candidate && existsSync2(candidate)) {
const hasConversations = existsSync2(join2(candidate, "conversations"));
const hasUserFiles = existsSync2(join2(candidate, "user-files"));
if (hasConversations || hasUserFiles) {
lmstudioHome = candidate;
return lmstudioHome;
}
}
} catch {
}
}
const dotHome = join2(resolvedHomeDir, ".lmstudio");
const cacheHome = join2(resolvedHomeDir, ".cache", "lm-studio");
const looksValid = (p) => {
try {
if (!existsSync2(p)) return false;
const conv = join2(p, "conversations");
const files = join2(p, "user-files");
return existsSync2(conv) || existsSync2(files);
} catch {
return false;
}
};
if (looksValid(dotHome)) {
lmstudioHome = dotHome;
try {
writeFileSync(pointerFilePath, lmstudioHome, "utf-8");
} catch {
}
return lmstudioHome;
}
if (looksValid(cacheHome)) {
lmstudioHome = cacheHome;
try {
writeFileSync(pointerFilePath, lmstudioHome, "utf-8");
} catch {
}
return lmstudioHome;
}
const home = dotHome;
lmstudioHome = home;
try {
writeFileSync(pointerFilePath, lmstudioHome, "utf-8");
} catch {
}
return lmstudioHome;
}
function getLMStudioWorkingDir(chatId) {
const home = findLMStudioHome();
return join2(home, "working-directories", chatId);
}
// src/helpers/attachments.ts
var loadedSharp = void 0;
var loadedJimp = void 0;
async function tryLoadSharp() {
if (loadedSharp !== void 0) return loadedSharp;
try {
const mod = await import("sharp");
loadedSharp = mod?.default || mod;
return loadedSharp;
} catch {
loadedSharp = null;
return null;
}
}
async function tryLoadJimp() {
if (loadedJimp !== void 0) return loadedJimp;
try {
const mod = await import("jimp");
loadedJimp = mod.default || mod.Jimp || mod;
return loadedJimp;
} catch {
loadedJimp = null;
return null;
}
}
async function validateImageBuffer(buf) {
const sharp = await tryLoadSharp();
if (sharp) {
try {
const meta = await sharp(buf).metadata();
if (meta && (meta.width || meta.height)) {
return { ok: true, width: meta.width, height: meta.height };
}
} catch {
}
return { ok: false };
}
const Jimp = await tryLoadJimp();
if (Jimp && typeof Jimp.read === "function") {
try {
const img = await Jimp.read(buf);
const w = typeof img.getWidth === "function" ? img.getWidth() : typeof img.width === "number" ? img.width : img.bitmap?.width || 0;
const h = typeof img.getHeight === "function" ? img.getHeight() : typeof img.height === "number" ? img.height : img.bitmap?.height || 0;
if (w || h) return { ok: true, width: w, height: h };
} catch {
}
return { ok: false };
}
return { ok: true };
}
function projectRootFromHere() {
const currentDir = typeof __dirname !== "undefined" ? __dirname : process.cwd();
if (currentDir.endsWith("helpers") || currentDir.endsWith("src")) {
return path8.resolve(currentDir, "..", "..");
}
return currentDir;
}
async function readLastAttachmentRef() {
try {
const root = projectRootFromHere();
const p = join3(root, "logs", "last-attachment.json");
if (!existsSync3(p)) return null;
const raw = await fsp2.readFile(p, "utf-8");
const json = JSON.parse(raw);
if (!json || typeof json !== "object" || !json.client) return null;
return json;
} catch {
return null;
}
}
function inferMimeFromExt(name, fallback = "image/png") {
if (!name) return fallback;
const ext = extname(name).toLowerCase().replace(/^\./, "");
switch (ext) {
case "jpg":
case "jpeg":
return "image/jpeg";
case "png":
return "image/png";
case "webp":
return "image/webp";
case "gif":
return "image/gif";
case "bmp":
return "image/bmp";
case "tif":
case "tiff":
return "image/tiff";
case "heic":
return "image/heic";
default:
return fallback;
}
}
async function rehydrateLastAttachment() {
try {
const ref = await readLastAttachmentRef();
if (!ref) return { ok: false, reason: "No persisted attachment reference" };
if (ref.client === "lmstudio") {
if (!ref.fileIdentifier)
return {
ok: false,
reason: "Persisted LM attachment has no fileIdentifier"
};
const LM_HOME2 = findLMStudioHome() || join3(os2.homedir(), ".lmstudio");
const userFilesDir = join3(LM_HOME2, "user-files");
const metaPath = join3(
userFilesDir,
`${ref.fileIdentifier}.metadata.json`
);
let buffer = null;
let mime;
if (existsSync3(metaPath)) {
try {
const metaRaw = readFileSync3(metaPath, "utf-8");
const meta = JSON.parse(metaRaw);
const dataStr = typeof meta?.preview?.data === "string" ? meta.preview.data : typeof meta?.content === "string" ? meta.content : typeof meta?.base64 === "string" ? meta.base64 : typeof meta?.data === "string" ? meta.data : void 0;
if (dataStr) {
const s = dataStr.trim();
let b64 = null;
let mimeFromHeader;
if (s.startsWith("data:")) {
const comma = s.indexOf(",");
if (comma > 0) {
b64 = s.slice(comma + 1);
const header = s.slice(5, comma);
const semi = header.indexOf(";");
mimeFromHeader = (semi >= 0 ? header.slice(0, semi) : header) || void 0;
}
} else {
const stripped = s.replace(/\s+/g, "");
if (/^[A-Za-z0-9+/]+={0,2}$/.test(stripped) && stripped.length >= 8) {
b64 = stripped;
}
}
if (b64) {
try {
const buf = Buffer.from(b64, "base64");
const im = await validateImageBuffer(buf);
if (im.ok) {
buffer = buf;
mime = mimeFromHeader || meta?.preview?.mimeType || meta?.mimeType || meta?.mimetype || meta?.contentType;
}
} catch {
}
}
}
} catch {
}
}
if (!buffer) {
const orig = join3(userFilesDir, ref.fileIdentifier);
if (existsSync3(orig)) buffer = readFileSync3(orig);
}
if (!buffer)
return {
ok: false,
reason: "Persisted LM attachment not found on disk"
};
const imgCheck = await validateImageBuffer(buffer);
if (!imgCheck.ok) {
return {
ok: false,
reason: "Persisted LM attachment is not a valid image"
};
}
const mimeType = mime || inferMimeFromExt(ref.fileIdentifier, "image/png");
return {
ok: true,
buffer,
mimeType,
tag: `lmstudio_attachment:${ref.fileIdentifier} (persisted)`
};
}
return {
ok: false,
reason: `Unknown client in last-attachment: ${ref.client}`
};
} catch (e) {
return { ok: false, reason: e?.message || String(e) };
}
}
async function getLMStudioFileMetadata(fileIdentifier) {
try {
const home = findLMStudioHome() || join3(os2.homedir(), ".lmstudio");
const metadataPath = join3(
home,
"user-files",
`${fileIdentifier}.metadata.json`
);
if (!existsSync3(metadataPath)) return null;
const raw = await fsp2.readFile(metadataPath, "utf-8");
const meta = JSON.parse(raw);
if (typeof meta.originalName !== "string" || typeof meta.fileIdentifier !== "string") {
return null;
}
return meta;
} catch {
return null;
}
}
async function getOriginalFileName(fileIdentifier) {
const meta = await getLMStudioFileMetadata(fileIdentifier);
return meta?.originalName ?? null;
}
function getLMStudioUserFilePath(fileIdentifier) {
const home = findLMStudioHome() || join3(os2.homedir(), ".lmstudio");
const filePath = join3(home, "user-files", fileIdentifier);
return existsSync3(filePath) ? filePath : null;
}
// src/services/toolParams/attachments.ts
function extractAttachmentFromSsot(raw) {
const candidates = [];
if (Array.isArray(raw)) {
for (let i = 0; i < raw.length; i++) {
const item = raw[i];
if (typeof item === "string" && item.trim()) {
candidates.push({ filename: item.trim(), index: i + 1 });
} else if (item && typeof item === "object") {
const obj = item;
if (typeof obj.identifier === "string" && obj.identifier.trim()) {
candidates.push({ filename: obj.identifier.trim(), index: i + 1 });
} else if (typeof obj.filename === "string" && obj.filename.trim()) {
candidates.push({ filename: obj.filename.trim(), index: i + 1 });
}
}
}
}
return candidates;
}
var ATTACHMENT_FULL_CONFIG = {
mediaType: "attachment",
allow: "all",
ssotJoin: {
source: "conversation.json",
messageRole: "user",
jsonPath: "message.files[]",
extractFromSource: extractAttachmentFromSsot
},
scan: {
trigger: "on-turn-start",
scope: "all-turns"
// Full scan for reconcile (user can delete attachments)
},
harvesting: {
defaultExtractor: extractAttachmentFromSsot,
tools: {}
// Attachments kommen nicht aus Tools
},
actions: {
generatePreview: true,
visionPromotion: {
metadata: true,
// Labels (a1, a2) ALWAYS included
pixel: true
// Base64 pixels in rolling window
}
},
injectMdInAgentResponse: {
format: "none",
labelGenerator: (item, i) => `a${item.index ?? i + 1}`
},
preview: {
generate: true,
namingPattern: "preview-{basename}.jpg",
format: drawthingsLimits.previewFormat,
mimeType: "image/jpeg",
maxSum: drawthingsLimits.previewMaxSum,
quality: drawthingsLimits.previewQuality,
outputDir: "."
},
toggles: {
toggles: []
// No toggle dependencies for attachments
}
};
var ATTACHMENT_CONFIG = {
mediaType: "attachment",
allow: "all",
defaultExtractor: extractAttachmentFromSsot,
defaultActions: ATTACHMENT_FULL_CONFIG.actions,
tools: {}
};
// src/services/toolParams/variants.ts
function extractVariantUrisFromContent(raw) {
const candidates = [];
const text = typeof raw === "string" ? raw : JSON.stringify(raw);
const uriRegex = /file:\/\/[^\s"')]+generated-image-[^\s"')]*-v(\d+)\.png/gi;
let match;
while ((match = uriRegex.exec(text)) !== null) {
const uri = match[0];
const variantNum = parseInt(match[1], 10);
const filename = uri.split("/").pop() ?? "";
candidates.push({
filename,
index: variantNum
});
}
return candidates;
}
function extractGenerateImageResult(raw) {
const candidates = [];
if (raw && typeof raw === "object") {
const obj = raw;
if (Array.isArray(obj.filenames)) {
for (let i = 0; i < obj.filenames.length; i++) {
const fn = obj.filenames[i];
if (typeof fn === "string") {
candidates.push({ filename: fn, index: i + 1 });
}
}
}
if (Array.isArray(obj.content)) {
for (const item of obj.content) {
if (item && typeof item === "object" && "text" in item) {
const nested = extractVariantUrisFromContent(item.text);
candidates.push(...nested);
}
}
}
}
if (candidates.length === 0) {
return extractVariantUrisFromContent(raw);
}
return candidates;
}
var selfPlugin = getSelfPluginIdentifier() ?? "unknown";
var VARIANT_FULL_CONFIG = {
mediaType: "variant",
allow: "all",
ssotJoin: {
source: "conversation.json",
messageRole: "assistant",
jsonPath: "content",
// Regex scan for file:// URIs
extractFromSource: extractVariantUrisFromContent
},
scan: {
trigger: "both",
scope: "all-turns"
},
harvesting: {
defaultExtractor: extractGenerateImageResult,
tools: {
[`${selfPlugin}/generate_image`]: {
extractCandidates: extractGenerateImageResult,
actions: {
generatePreview: true,
visionPromotion: {
metadata: true,
pixel: true
}
}
}
}
},
actions: {
generatePreview: true,
visionPromotion: {
metadata: true,
// Labels (v1, v2) ALWAYS included
pixel: true
// Base64 pixels in rolling window
}
},
injectMdInAgentResponse: {
format: "none",
// Toggle-dependent: !PREVIEW_IN_CHAT
itemTemplate: "",
labelGenerator: (item, i) => `v${item.index ?? i + 1}`
},
preview: {
generate: true,
namingPattern: "preview-{basename}.jpg",
format: drawthingsLimits.previewFormat,
mimeType: "image/jpeg",
maxSum: drawthingsLimits.previewMaxSum,
quality: drawthingsLimits.previewQuality,
outputDir: "."
},
toggles: {
toggles: []
}
};
var VARIANT_CONFIG = {
mediaType: "variant",
allow: "all",
defaultExtractor: extractGenerateImageResult,
defaultActions: VARIANT_FULL_CONFIG.actions,
tools: VARIANT_FULL_CONFIG.harvesting.tools
};
// src/helpers/toolResultImageHarvest.ts
import fs10 from "fs";
import path10 from "path";
import crypto from "crypto";
// src/media-promotion-core/image.ts
import fs9 from "fs";
import path9 from "path";
// src/helpers/imageUtils.ts
var loadedSharp2 = void 0;
var loadedJimp2 = void 0;
var libLogged = false;
var loggedFns = /* @__PURE__ */ new Set();
function logOnce(msg) {
if (loggedFns.has(msg)) return;
loggedFns.add(msg);
try {
console.debug(msg);
} catch {
}
}
async function tryLoadSharp2() {
if (loadedSharp2 !== void 0) return loadedSharp2;
try {
const mod = await import("sharp");
loadedSharp2 = mod?.default || mod;
if (!libLogged) {
try {
console.debug(`[imageUtils] using lib=sharp`);
libLogged = true;
} catch {
}
}
return loadedSharp2;
} catch {
loadedSharp2 = null;
return null;
}
}
async function tryLoadJimp2() {
if (loadedJimp2 !== void 0) return loadedJimp2;
try {
const mod = await import("jimp");
const candidate = mod && (mod.default || mod.Jimp || mod);
loadedJimp2 = candidate;
if (!libLogged) {
try {
console.debug(`[imageUtils] using lib=jimp`);
libLogged = true;
} catch {
}
}
return loadedJimp2;
} catch {
loadedJimp2 = null;
return null;
}
}
function isPng(buf) {
try {
return buf && buf.length >= 8 && buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71 && buf[4] === 13 && buf[5] === 10 && buf[6] === 26 && buf[7] === 10;
} catch {
return false;
}
}
function jimpHasFn(obj, name) {
try {
return obj && typeof obj[name] === "function";
} catch {
return false;
}
}
async function jimpResizeCompat(img, w, h) {
if (!jimpHasFn(img, "resize")) {
throw new Error("Jimp resize not available");
}
let lastError;
try {
await img.resize({ w, h });
return;
} catch (e) {
lastError = e;
}
try {
await img.resize(w, h);
return;
} catch (e) {
lastError = e;
}
throw new Error(
`Jimp resize failed for both API variants: ${lastError?.message || String(lastError)}`
);
}
async function jimpCropCompat(img, x, y, w, h) {
if (!jimpHasFn(img, "crop")) {
throw new Error("Jimp crop not available");
}
let lastError;
try {
await img.crop({ x, y, w, h });
return;
} catch (e) {
lastError = e;
}
try {
await img.crop(x, y, w, h);
return;
} catch (e) {
lastError = e;
}
throw new Error(
`Jimp crop failed for both API variants: ${lastError?.message || String(lastError)}`
);
}
async function jimpAutoRotate(img) {
try {
if (jimpHasFn(img, "exifRotate")) {
await img.exifRotate();
} else if (jimpHasFn(img, "rotate")) {
}
} catch (e) {
try {
console.error(`[imageUtils] Jimp EXIF rotation failed: ${String(e)}`);
} catch {
}
}
}
async function jimpGetBufferCompat(img, mime, options) {
let lastError;
try {
if (jimpHasFn(img, "getBufferAsync")) {
return await img.getBufferAsync(mime, options);
}
} catch (e) {
lastError = e;
}
try {
if (jimpHasFn(img, "getBuffer")) {
return await img.getBuffer(mime, options);
}
} catch (e) {
lastError = e;
}
throw new Error(
`Jimp getBuffer failed for both API variants (mime=${mime}): ${lastError?.message || String(lastError)}`
);
}
async function getSize(buffer) {
const sharp = await tryLoadSharp2();
if (sharp) {
try {
logOnce(`[imageUtils.getSize] using Sharp`);
const oriented = await sharp(buffer).rotate().png().toBuffer();
const meta = await sharp(oriented).metadata();
return { width: meta.width || 0, height: meta.height || 0 };
} catch (e) {
console.warn(`[imageUtils.getSize] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.getSize] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
const w = typeof img.getWidth === "function" ? img.getWidth() : typeof img.width === "number" ? img.width : img.bitmap?.width || 0;
const h = typeof img.getHeight === "function" ? img.getHeight() : typeof img.height === "number" ? img.height : img.bitmap?.height || 0;
return { width: w || 0, height: h || 0 };
}
return { width: 0, height: 0 };
}
async function toPng(buffer) {
if (isPng(buffer)) return buffer;
const sharp = await tryLoadSharp2();
if (sharp) {
try {
logOnce(`[imageUtils.toPng] using Sharp`);
return await sharp(buffer).rotate().png().toBuffer();
} catch (e) {
console.warn(`[imageUtils.toPng] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.toPng] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
return await jimpGetBufferCompat(img, "image/png");
}
return buffer;
}
async function resizeAndEncode(buffer, format, quality, width, _maxBytes) {
const sharp = await tryLoadSharp2();
if (sharp) {
try {
logOnce(`[imageUtils.resizeAndEncode] using Sharp`);
const pipeline = sharp(buffer).rotate().resize({ width, fit: "inside", withoutEnlargement: false });
const { data, info } = await (format === "jpeg" ? pipeline.jpeg({
quality: clampQuality(quality),
mozjpeg: true,
chromaSubsampling: "4:2:0",
progressive: true
}) : pipeline.webp({ quality: clampQuality(quality), effort: 4 })).toBuffer({ resolveWithObject: true });
const outW = typeof info.width === "number" ? info.width : width;
const outH = typeof info.height === "number" ? info.height : Math.round(width * 0.75);
return { data, width: outW, height: outH };
} catch (e) {
console.warn(`[imageUtils.resizeAndEncode] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.resizeAndEncode] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
const origW = typeof img.getWidth === "function" ? img.getWidth() : typeof img.width === "number" ? img.width : img.bitmap?.width || 0;
const origH = typeof img.getHeight === "function" ? img.getHeight() : typeof img.height === "number" ? img.height : img.bitmap?.height || 0;
const scale = width / Math.max(1, origW);
const outW = Math.max(1, Math.round(origW * scale));
const outH = Math.max(1, Math.round(origH * scale));
await jimpResizeCompat(img, outW, outH);
const q = clampQuality(quality);
if (format === "jpeg") {
const data = await jimpGetBufferCompat(img, "image/jpeg", { quality: q });
return { data, width: outW, height: outH };
} else {
try {
const data = await jimpGetBufferCompat(img, "image/webp", {
quality: q
});
return { data, width: outW, height: outH };
} catch {
const data = await jimpGetBufferCompat(img, "image/jpeg", {
quality: q
});
return { data, width: outW, height: outH };
}
}
}
return { data: buffer, width, height: Math.round(width * 0.75) };
}
async function resizeAndEncodeByHeight(buffer, format, quality, maxHeight) {
const sharp = await tryLoadSharp2();
if (sharp) {
try {
logOnce(`[imageUtils.resizeAndEncodeByHeight] using Sharp`);
const pipeline = sharp(buffer).rotate().resize({ height: maxHeight, fit: "inside", withoutEnlargement: false });
const { data, info } = await (format === "jpeg" ? pipeline.jpeg({
quality: clampQuality(quality),
mozjpeg: true,
chromaSubsampling: "4:2:0",
progressive: true
}) : pipeline.webp({ quality: clampQuality(quality), effort: 4 })).toBuffer({ resolveWithObject: true });
const outW = typeof info.width === "number" ? info.width : Math.round(maxHeight * 1.33);
const outH = typeof info.height === "number" ? info.height : maxHeight;
return { data, width: outW, height: outH };
} catch (e) {
console.warn(`[imageUtils.resizeAndEncodeByHeight] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.resizeAndEncodeByHeight] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
const origW = typeof img.getWidth === "function" ? img.getWidth() : typeof img.width === "number" ? img.width : img.bitmap?.width || 0;
const origH = typeof img.getHeight === "function" ? img.getHeight() : typeof img.height === "number" ? img.height : img.bitmap?.height || 0;
const scale = maxHeight / Math.max(1, origH);
const outH = Math.max(1, Math.round(maxHeight));
const outW = Math.max(1, Math.round(origW * scale));
await jimpResizeCompat(img, outW, outH);
const q = clampQuality(quality);
if (format === "jpeg") {
const data = await jimpGetBufferCompat(img, "image/jpeg", { quality: q });
return { data, width: outW, height: outH };
} else {
try {
const data = await jimpGetBufferCompat(img, "image/webp", {
quality: q
});
return { data, width: outW, height: outH };
} catch {
const data = await jimpGetBufferCompat(img, "image/jpeg", {
quality: q
});
return { data, width: outW, height: outH };
}
}
}
return {
data: buffer,
width: Math.round(maxHeight * 1.33),
height: maxHeight
};
}
async function resizeAndEncodeBySum(buffer, format, quality, maxSum) {
const sharp = await tryLoadSharp2();
const calcDims = (origW, origH) => {
let w = Math.max(1, Math.round(origW));
let h = Math.max(1, Math.round(origH));
const currentSum = w + h;
if (currentSum > maxSum) {
const scale = maxSum / currentSum;
w = Math.max(1, Math.round(w * scale));
h = Math.max(1, Math.round(h * scale));
}
return { w, h };
};
if (sharp) {
try {
logOnce(`[imageUtils.resizeAndEncodeBySum] using Sharp`);
const metadata = await sharp(buffer).metadata();
const rotatesDimensions = metadata.orientation !== void 0 && metadata.orientation >= 5 && metadata.orientation <= 8;
const origW = rotatesDimensions ? metadata.height ?? 640 : metadata.width ?? 640;
const origH = rotatesDimensions ? metadata.width ?? 640 : metadata.height ?? 640;
const { w, h } = calcDims(origW, origH);
const pipeline = sharp(buffer).rotate().resize({ width: w, height: h, fit: "inside", withoutEnlargement: true });
const { data, info } = await (format === "jpeg" ? pipeline.jpeg({
quality: clampQuality(quality),
mozjpeg: true,
chromaSubsampling: "4:2:0",
progressive: true
}) : pipeline.webp({ quality: clampQuality(quality), effort: 4 })).toBuffer({ resolveWithObject: true });
const outW = typeof info.width === "number" ? info.width : w;
const outH = typeof info.height === "number" ? info.height : h;
return { data, width: outW, height: outH };
} catch (e) {
console.warn(`[imageUtils.resizeAndEncodeBySum] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.resizeAndEncodeBySum] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
const origW = typeof img.getWidth === "function" ? img.getWidth() : typeof img.width === "number" ? img.width : img.bitmap?.width || 640;
const origH = typeof img.getHeight === "function" ? img.getHeight() : typeof img.height === "number" ? img.height : img.bitmap?.height || 640;
const { w, h } = calcDims(origW, origH);
await jimpResizeCompat(img, w, h);
const q = clampQuality(quality);
if (format === "jpeg") {
const data = await jimpGetBufferCompat(img, "image/jpeg", { quality: q });
return { data, width: w, height: h };
} else {
try {
const data = await jimpGetBufferCompat(img, "image/webp", {
quality: q
});
return { data, width: w, height: h };
} catch {
const data = await jimpGetBufferCompat(img, "image/jpeg", {
quality: q
});
return { data, width: w, height: h };
}
}
}
return {
data: buffer,
width: Math.round(maxSum / 2),
height: Math.round(maxSum / 2)
};
}
async function resizeInsideToPng(buffer, targetW, targetH) {
const sharp = await tryLoadSharp2();
const w = Math.max(1, Math.round(targetW));
const h = Math.max(1, Math.round(targetH));
if (sharp) {
try {
logOnce(`[imageUtils.resizeInsideToPng] using Sharp`);
return await sharp(buffer).rotate().resize({ width: w, height: h, fit: "inside", withoutEnlargement: false }).png().toBuffer();
} catch (e) {
console.warn(`[imageUtils.resizeInsideToPng] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.resizeInsideToPng] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
const origW = typeof img.getWidth === "function" ? img.getWidth() : typeof img.width === "number" ? img.width : img.bitmap?.width || 0;
const origH = typeof img.getHeight === "function" ? img.getHeight() : typeof img.height === "number" ? img.height : img.bitmap?.height || 0;
const scale = Math.min(w / Math.max(1, origW), h / Math.max(1, origH));
const newW = Math.max(1, Math.round(origW * scale));
const newH = Math.max(1, Math.round(origH * scale));
await jimpResizeCompat(img, newW, newH);
return await jimpGetBufferCompat(img, "image/png");
}
return buffer;
}
async function resizeFillToPng(buffer, targetW, targetH) {
const sharp = await tryLoadSharp2();
const w = Math.max(1, Math.round(targetW));
const h = Math.max(1, Math.round(targetH));
if (sharp) {
try {
logOnce(`[imageUtils.resizeFillToPng] using Sharp`);
return await sharp(buffer).rotate().resize({ width: w, height: h, fit: "fill" }).png().toBuffer();
} catch (e) {
console.warn(`[imageUtils.resizeFillToPng] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.resizeFillToPng] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
await jimpResizeCompat(img, w, h);
return await jimpGetBufferCompat(img, "image/png");
}
return buffer;
}
async function resizeCoverToPng(buffer, targetW, targetH) {
const sharp = await tryLoadSharp2();
const w = Math.max(1, Math.round(targetW));
const h = Math.max(1, Math.round(targetH));
if (sharp) {
try {
logOnce(`[imageUtils.resizeCoverToPng] using Sharp`);
return await sharp(buffer).rotate().resize({ width: w, height: h, fit: "cover", position: "centre" }).png().toBuffer();
} catch (e) {
console.warn(`[imageUtils.resizeCoverToPng] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.resizeCoverToPng] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
const origW = typeof img.getWidth === "function" ? img.getWidth() : typeof img.width === "number" ? img.width : img.bitmap?.width || 0;
const origH = typeof img.getHeight === "function" ? img.getHeight() : typeof img.height === "number" ? img.height : img.bitmap?.height || 0;
if (!origW || !origH) {
await jimpResizeCompat(img, w, h);
return await jimpGetBufferCompat(img, "image/png");
}
const scale = Math.max(w / origW, h / origH);
const newW = Math.max(1, Math.round(origW * scale));
const newH = Math.max(1, Math.round(origH * scale));
await jimpResizeCompat(img, newW, newH);
const x = Math.max(0, Math.floor((newW - w) / 2));
const y = Math.max(0, Math.floor((newH - h) / 2));
await jimpCropCompat(img, x, y, w, h);
return await jimpGetBufferCompat(img, "image/png");
}
return buffer;
}
async function cropToPng(buffer, opts) {
const sharp = await tryLoadSharp2();
if (sharp) {
try {
logOnce(`[imageUtils.cropToPng] using Sharp`);
const oriented = await sharp(buffer).rotate().png().toBuffer();
const meta = await sharp(oriented).metadata();
const imgW = meta.width ?? 0;
const imgH = meta.height ?? 0;
const x = Math.floor(imgW * opts.left / 100);
const xEnd = Math.ceil(imgW * (1 - opts.right / 100));
const y = Math.floor(imgH * opts.top / 100);
const yEnd = Math.ceil(imgH * (1 - opts.bottom / 100));
const cropW = Math.max(1, xEnd - x);
const cropH = Math.max(1, yEnd - y);
return await sharp(oriented).extract({ left: x, top: y, width: cropW, height: cropH }).png().toBuffer();
} catch (e) {
console.warn(`[imageUtils.cropToPng] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.cropToPng] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
const imgW = typeof img.getWidth === "function" ? img.getWidth() : typeof img.width === "number" ? img.width : img.bitmap?.width || 0;
const imgH = typeof img.getHeight === "function" ? img.getHeight() : typeof img.height === "number" ? img.height : img.bitmap?.height || 0;
const x = Math.floor(imgW * opts.left / 100);
const xEnd = Math.ceil(imgW * (1 - opts.right / 100));
const y = Math.floor(imgH * opts.top / 100);
const yEnd = Math.ceil(imgH * (1 - opts.bottom / 100));
const cropW = Math.max(1, xEnd - x);
const cropH = Math.max(1, yEnd - y);
await jimpCropCompat(img, x, y, cropW, cropH);
return await jimpGetBufferCompat(img, "image/png");
}
return buffer;
}
function clampQuality(q) {
if (!Number.isFinite(q)) return 80;
q = Math.round(q);
if (q < 1) q = 1;
if (q > 100) q = 100;
return q;
}
async function decodeToRgba(buffer) {
const sharp = await tryLoadSharp2();
if (sharp) {
try {
const { data, info } = await sharp(buffer).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
return { data: new Uint8Array(data), width: info.width, height: info.height };
} catch (e) {
console.warn(`[imageUtils.decodeToRgba] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
const img = await Jimp.read(buffer);
const bm = img.bitmap;
return { data: new Uint8Array(bm.data), width: bm.width, height: bm.height };
}
throw new Error("decodeToRgba: neither sharp nor jimp is available");
}
async function encodeRgbaToPng(data, width, height) {
const sharp = await tryLoadSharp2();
if (sharp) {
try {
return await sharp(Buffer.from(data.buffer, data.byteOffset, data.byteLength), {
raw: { width, height, channels: 4 }
}).png().toBuffer();
} catch (e) {
console.warn(`[imageUtils.encodeRgbaToPng] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp) {
const img = new Jimp({ width, height, data: Buffer.from(data) });
return await jimpGetBufferCompat(img, "image/png");
}
throw new Error("encodeRgbaToPng: neither sharp nor jimp is available");
}
// src/media-promotion-core/image.ts
function getDefaultPreviewOptions() {
return {
maxDim: drawthingsLimits.previewMaxSum,
quality: drawthingsLimits.previewQuality,
mode: "sum",
maxSum: drawthingsLimits.previewMaxSum
};
}
function isAllowedOriginalExt(p) {
return /(\.(png|jpe?g|webp|mov))$/i.test(p);
}
function guessExtForOriginal(maybePath) {
const e = path9.extname(maybePath).toLowerCase();
if (e === ".png" || e === ".jpg" || e === ".jpeg" || e === ".webp") return e;
return ".png";
}
function previewFilenameFrom(originalFilename) {
const hasPrefix = originalFilename.toLowerCase().startsWith("preview-");
const base = hasPrefix ? originalFilename : `preview-${originalFilename}`;
return base.replace(/\.(png|jpg|jpeg|webp|gif)$/i, ".jpg").replace(/ /g, "_");
}
async function encodeJpegPreviewFromBuffer(srcBuf, opts) {
const q = Math.max(1, Math.min(100, opts.quality));
if (opts.mode === "height") {
const targetH = Math.max(1, Math.round(opts.maxDim));
const { data: data2, width: width2, height: height2 } = await resizeAndEncodeByHeight(
srcBuf,
"jpeg",
q,
targetH
);
return { data: data2, width: width2, height: height2 };
}
if (opts.mode === "sum" && opts.maxSum) {
const { data: data2, width: width2, height: height2 } = await resizeAndEncodeBySum(
srcBuf,
"jpeg",
q,
opts.maxSum
);
return { data: data2, width: width2, height: height2 };
}
const maxW = Math.max(1, Math.round(opts.maxDim));
const { data, width, height } = await resizeAndEncode(
srcBuf,
"jpeg",
q,
maxW,
Number.MAX_SAFE_INTEGER
);
return { data, width, height };
}
async function encodeJpegPreview(srcAbs, dstAbs, opts) {
const srcBuf = await fs9.promises.readFile(srcAbs);
const { data } = await encodeJpegPreviewFromBuffer(srcBuf, opts);
await fs9.promises.writeFile(dstAbs, data);
}
function isPreviewOptions(x) {
return typeof x === "object" && x !== null && "maxDim" in x && typeof x.maxDim === "number";
}
function normalizeToPreviewOptions(input) {
if (isPreviewOptions(input)) return input;
return {
maxDim: input.maxWidth ?? 640,
quality: input.quality ?? 80,
mode: input.maxSum ? "sum" : "width",
maxSum: input.maxSum
};
}
async function generatePreview(srcAbs, chatWd, optsInput, options) {
const debug = options?.debug ?? false;
const opts = normalizeToPreviewOptions(optsInput);
if (!fs9.existsSync(srcAbs)) {
if (debug) console.warn(`[Preview] Source not found: ${srcAbs}`);
return null;
}
const originalFilename = path9.basename(srcAbs);
const previewFilename = options?.customFilename ?? previewFilenameFrom(originalFilename);
const previewAbs = path9.join(chatWd, previewFilename);
if (!options?.force && fs9.existsSync(previewAbs)) {
if (debug) console.info(`[Preview] Exists, skipping: ${previewFilename}`);
return previewFilename;
}
try {
await encodeJpegPreview(srcAbs, previewAbs, opts);
if (debug) console.info(`[Preview] Generated: ${previewFilename}`);
return previewFilename;
} catch (e) {
if (debug)
console.warn(
`[Preview] Failed for ${originalFilename}:`,
e.message
);
throw e;
}
}
async function generatePreviewFromBuffer(srcBuf, chatWd, originalFilename, optsInput, options) {
const debug = options?.debug ?? false;
const opts = normalizeToPreviewOptions(optsInput);
const previewFilename = options?.customFilename ?? previewFilenameFrom(originalFilename);
const previewAbs = path9.join(chatWd, previewFilename);
if (!options?.force && fs9.existsSync(previewAbs)) {
if (debug) console.info(`[Preview] Exists, skipping: ${previewFilename}`);
try {
const existingData = await fs9.promises.readFile(previewAbs);
return {
previewFilename,
previewAbs,
data: existingData,
width: 0,
// Unknown for existing file
height: 0
};
} catch {
}
}
try {
const { data, width, height } = await encodeJpegPreviewFromBuffer(
srcBuf,
opts
);
await fs9.promises.writeFile(previewAbs, data);
if (debug)
console.info(`[Preview] Generated from buffer: ${previewFilename}`);
return {
previewFilename,
previewAbs,
data,
width,
height
};
} catch (e) {
if (debug)
console.warn(
`[Preview] Failed for ${originalFilename}:`,
e.message
);
throw e;
}
}
// src/helpers/toolResultImageHarvest.ts
function canonicalizeRef(ref) {
let s = String(ref || "").trim();
s = s.replace(/[)\],.;]+$/g, "");
s = s.replace(/^"(.+)"$/g, "$1");
s = s.replace(/^'(.+)'$/g, "$1");
return s.trim();
}
function isAllowedUrl(url) {
if (/^https:\/\//i.test(url)) return true;
if (/^http:\/\//i.test(url)) {
try {
const host = new URL(url).hostname;
return host === "localhost" || host === "127.0.0.1" || host === "::1";
} catch {
return false;
}
}
if (isProjectUri(url)) return true;
return false;
}
function detectImageMagic(buf) {
if (!buf || buf.length < 12) return null;
if (buf.length >= 8 && buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71 && buf[4] === 13 && buf[5] === 10 && buf[6] === 26 && buf[7] === 10)
return "png";
if (buf[0] === 255 && buf[1] === 216 && buf[2] === 255) return "jpeg";
if (buf[0] === 71 && buf[1] === 73 && buf[2] === 70 && buf[3] === 56)
return "gif";
if (buf[0] === 82 && buf[1] === 73 && buf[2] === 70 && buf[3] === 70 && buf[8] === 87 && buf[9] === 69 && buf[10] === 66 && buf[11] === 80)
return "webp";
return null;
}
async function pathExists(p) {
try {
await fs10.promises.access(p, fs10.constants.F_OK);
return true;
} catch {
return false;
}
}
async function fetchWithLimits(url, timeoutMs, maxBytes) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetch(url, {
method: "GET",
redirect: "follow",
signal: controller.signal
});
if (!res.ok) {
throw new Error(`HTTP ${res.status} ${res.statusText}`);
}
const cl = res.headers.get("content-length");
if (cl) {
const n = Number(cl);
if (Number.isFinite(n) && n > maxBytes) {
throw new Error(`content-length ${n} exceeds maxBytes ${maxBytes}`);
}
}
const body = res.body;
if (!body) {
const ab = await res.arrayBuffer();
const buf = Buffer.from(ab);
if (buf.length > maxBytes) {
throw new Error(
`response size ${buf.length} exceeds maxBytes ${maxBytes}`
);
}
return buf;
}
const reader = body.getReader();
const chunks = [];
let total = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) {
total += value.byteLength;
if (total > maxBytes) {
try {
controller.abort();
} catch {
}
throw new Error(`response size exceeds maxBytes ${maxBytes}`);
}
chunks.push(value);
}
}
return Buffer.concat(chunks.map((c) => Buffer.from(c)));
} finally {
clearTimeout(timeout);
}
}
function extractUrlsFromText(text) {
const out = [];
const re = /https:\/\/[\w\-./:%?#@!$&'()*+,;=]+/gi;
let m;
while ((m = re.exec(text)) !== null) {
out.push(m[0]);
}
return out;
}
function deepParseMaybeJson(input, maxDepth = 4) {
let cur = input;
for (let depth = 0; depth < maxDepth; depth++) {
if (typeof cur !== "string") return cur;
const t = cur.trim();
if (!(t.startsWith("{") || t.startsWith("[") || t.startsWith('"'))) return cur;
try {
cur = JSON.parse(t);
} catch {
return cur;
}
}
return cur;
}
function parseToolResultPayload(raw, validator) {
const segments = toolResultToTextSegments(raw);
for (const seg of segments) {
const parsed = deepParseMaybeJson(seg, 4);
if (validator(parsed)) {
return parsed;
}
}
return null;
}
function extractImageUrlsStructured(value) {
const urls = [];
const v = value;
if (v && typeof v === "object") {
if (Array.isArray(v.items)) {
for (const it of v.items) {
const u = it?.properties?.url;
if (typeof u === "string" && u.trim()) urls.push(u);
}
}
}
return urls;
}
function extractCandidatesStructured(value) {
const out = [];
const v = value;
if (!v || typeof v !== "object") return out;
if (!Array.isArray(v.items)) return out;
for (const it of v.items) {
const url = typeof it?.properties?.url === "string" ? String(it.properties.url) : "";
if (!url.trim()) continue;
const cand = { url: url.trim() };
if (typeof it?.title === "string" && it.title.trim()) cand.title = it.title;
if (typeof it?.confidence === "string" && it.confidence.trim()) {
cand.confidence = it.confidence;
}
const w = it?.properties?.width;
const h = it?.properties?.height;
if (typeof w === "number" && Number.isFinite(w)) cand.width = w;
if (typeof h === "number" && Number.isFinite(h)) cand.height = h;
if (typeof it?.url === "string" && it.url.trim()) cand.pageUrl = it.url;
if (typeof it?.page_fetched === "string" && it.page_fetched.trim()) {
cand.pageFetched = it.page_fetched;
}
const thumb = it?.thumbnail?.url;
if (typeof thumb === "string" && thumb.trim()) cand.thumbnailUrl = thumb;
out.push(cand);
}
return out;
}
function dedupePreserveOrder(items) {
const seen = /* @__PURE__ */ new Set();
const out = [];
for (const it of items) {
const c = canonicalizeRef(it);
if (!c) continue;
if (seen.has(c)) continue;
seen.add(c);
out.push(c);
}
return out;
}
function dedupeCandidatesPreserveOrder(items) {
const seen = /* @__PURE__ */ new Set();
const out = [];
for (const it of items) {
const u = canonicalizeRef(it?.url);
if (!u) continue;
if (seen.has(u)) continue;
seen.add(u);
out.push({ ...it, url: u });
}
return out;
}
function toolResultToTextSegments(toolResult) {
const rawText = typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult);
try {
const parsed = JSON.parse(rawText);
if (Array.isArray(parsed)) {
const parts = [];
for (const p of parsed) {
if (p && typeof p === "object" && typeof p.text === "string") {
parts.push(String(p.text));
}
}
if (parts.length) return parts;
}
} catch {
}
return [rawText];
}
function extractImageRefsFromToolResult(toolResult) {
const segments = toolResultToTextSegments(toolResult);
const urls = [];
for (const seg of segments) {
const deep = deepParseMaybeJson(seg, 4);
urls.push(...extractImageUrlsStructured(deep));
if (typeof deep === "string") {
urls.push(...extractUrlsFromText(deep));
} else {
const stack = [
{ v: deep, depth: 0 }
];
const maxDepth = 4;
let nodes = 0;
const maxNodes = 2e3;
while (stack.length) {
const { v, depth } = stack.pop();
nodes++;
if (nodes > maxNodes) break;
if (typeof v === "string") {
urls.push(...extractUrlsFromText(v));
} else if (v && typeof v === "object" && depth < maxDepth) {
if (Array.isArray(v)) {
for (const it of v) stack.push({ v: it, depth: depth + 1 });
} else {
for (const k of Object.keys(v)) {
stack.push({ v: v[k], depth: depth + 1 });
}
}
}
}
}
}
return dedupePreserveOrder(urls);
}
function extractToolResultImageCandidates(toolResult) {
const segments = toolResultToTextSegments(toolResult);
const candidates = [];
const urlFallbacks = [];
for (const seg of segments) {
const deep = deepParseMaybeJson(seg, 4);
candidates.push(...extractCandidatesStructured(deep));
if (typeof deep === "string") {
urlFallbacks.push(...extractUrlsFromText(deep));
} else {
const stack = [
{ v: deep, depth: 0 }
];
const maxDepth = 4;
let nodes = 0;
const maxNodes = 2e3;
while (stack.length) {
const { v, depth } = stack.pop();
nodes++;
if (nodes > maxNodes) break;
if (typeof v === "string") {
urlFallbacks.push(...extractUrlsFromText(v));
} else if (v && typeof v === "object" && depth < maxDepth) {
if (Array.isArray(v)) {
for (const it of v) stack.push({ v: it, depth: depth + 1 });
} else {
for (const k of Object.keys(v)) {
stack.push({ v: v[k], depth: depth + 1 });
}
}
}
}
}
}
const structured = dedupeCandidatesPreserveOrder(candidates);
const structuredUrls = new Set(structured.map((c) => c.url));
const fallback = dedupePreserveOrder(urlFallbacks).filter((u) => !structuredUrls.has(canonicalizeRef(u))).map((u) => ({ url: canonicalizeRef(u) }));
return [...structured, ...fallback].filter((c) => !!c.url);
}
async function materializeToolResultImageToFiles(input) {
const timeoutMs = typeof input.timeoutMs === "number" && input.timeoutMs > 0 ? Math.floor(input.timeoutMs) : 1e4;
const maxBytes = typeof input.maxBytes === "number" && input.maxBytes > 0 ? Math.floor(input.maxBytes) : 15 * 1024 * 1024;
const ref = canonicalizeRef(input.url);
if (!isAllowedUrl(ref)) {
throw new Error("scheme not allowed (https or project:// only)");
}
let buf;
if (isProjectUri(ref)) {
const resolved = await resolveProjectUri(ref);
if (!resolved) {
throw new Error("failed to extract thumbnail from project file");
}
buf = resolved;
} else {
buf = await fetchWithLimits(ref, timeoutMs, maxBytes);
}
const magic = detectImageMagic(buf);
if (!magic) {
throw new Error("not a supported image (magic bytes)");
}
const bytesHash = crypto.createHash("sha256").update(buf).digest("hex");
const png = await toPng(buf);
await fs10.promises.writeFile(input.originalAbs, png);
const chatWd = path10.dirname(input.originalAbs);
await generatePreview(input.originalAbs, chatWd, input.preview, {
customFilename: path10.basename(input.previewAbs),
force: true
// Always generate (we just downloaded the original)
});
return { bytesHash };
}
function shortHexSha256(input, chars = 12) {
const h = crypto.createHash("sha256").update(input).digest("hex");
return h.slice(0, Math.max(4, Math.min(64, chars)));
}
async function harvestToolResultImages(input) {
const debug = !!input.debug;
const maxImages = Math.max(0, Math.floor(input.maxImages));
const timeoutMs = typeof input.timeoutMs === "number" && input.timeoutMs > 0 ? Math.floor(input.timeoutMs) : 1e4;
const maxBytes = typeof input.maxBytes === "number" && input.maxBytes > 0 ? Math.floor(input.maxBytes) : 15 * 1024 * 1024;
const skipped = [];
const harvested = [];
if (!maxImages) return { harvested, skipped };
if (!input.chatWd || !String(input.chatWd).trim()) {
return {
harvested,
skipped: [{ ref: "(chatWd)", reason: "missing chatWd" }]
};
}
const refs = extractImageRefsFromToolResult(input.toolResult);
if (debug) {
console.info(
`[ToolResultHarvest] tool=${input.toolName} extractedRefs=${refs.length} cap=${maxImages}`
);
}
const capped = refs.slice(0, maxImages);
await fs10.promises.mkdir(input.chatWd, { recursive: true });
for (const rawRef of capped) {
const ref = canonicalizeRef(rawRef);
if (!ref) continue;
if (!isAllowedUrl(ref)) {
skipped.push({ ref, reason: "scheme not allowed (https only)" });
continue;
}
const urlHash = shortHexSha256(ref, 12);
const ts = `h${urlHash}Z`;
const vNum = 1;
const originalBaseName = `generated-image-${ts}-v${vNum}.png`;
const previewBaseName = `preview-generated-image-${ts}-v${vNum}.jpg`;
const originalAbs = path10.join(input.chatWd, originalBaseName);
const previewAbs = path10.join(input.chatWd, previewBaseName);
const originalOk = await pathExists(originalAbs);
const previewOk = await pathExists(previewAbs);
if (originalOk && previewOk) {
harvested.push({
originalBaseName,
previewBaseName,
sourceRef: ref
});
continue;
}
try {
const { bytesHash } = await materializeToolResultImageToFiles({
url: ref,
originalAbs,
previewAbs,
preview: input.preview,
timeoutMs,
maxBytes
});
harvested.push({
originalBaseName,
previewBaseName,
sourceRef: ref,
bytesHash
});
if (debug) {
console.info(
`[ToolResultHarvest] saved ${originalBaseName} + ${previewBaseName} (tool=${input.toolName})`
);
}
} catch (e) {
skipped.push({
ref,
reason: e?.message || String(e)
});
continue;
}
}
return { harvested, skipped };
}
// src/services/toolParams/pictures.ts
function renderBraveResultsTable(items) {
if (items.length === 0) return "";
const toDisplayUrl = (u) => {
const s = typeof u === "string" ? u.trim() : "";
if (!s) return "";
if (/^https?:\/\//i.test(s) || /^file:\/\//i.test(s)) return s;
if (s.startsWith("./") || s.startsWith("/")) return s;
return `./${s}`;
};
const escapeCell = (s) => String(s ?? "").replace(/\|/g, "\\|").replace(/[\r\n]+/g, " ").trim();
const sourceLabel = (u) => {
try {
if (!/^https?:\/\//i.test(u)) return "source";
const host = new URL(u).host;
return host || "source";
} catch {
return "source";
}
};
const header = "| Preview | ID / Title | Source |\n|---|---|---|";
const rows = items.map((item, i) => {
const label = typeof item.index === "number" && Number.isFinite(item.index) ? `p${item.index}` : `p${i + 1}`;
const previewUrl = toDisplayUrl(item.url);
const linkTarget = (
// Prefer the external provenance link (HTTP) when present.
toDisplayUrl(item.sourceUrl) || // Fallbacks: if we don't have provenance, link to local original.
toDisplayUrl(item.filename) || // Last resort: link to whatever we have.
previewUrl
);
const previewImg = previewUrl ? `` : "";
const preview = previewImg && linkTarget ? `[${previewImg}](${linkTarget})` : previewImg;
const titleText = escapeCell(item.title ?? "");
const title = titleText ? `\`${label}\` ${titleText}` : `\`${label}\``;
const sourceUrl = typeof item.sourceUrl === "string" && item.sourceUrl.trim() ? item.sourceUrl.trim() : "";
const source = sourceUrl ? `[${escapeCell(sourceLabel(sourceUrl))}](${toDisplayUrl(sourceUrl)})` : "";
return `| ${preview} | ${title} | ${source} |`;
});
return [header, ...rows].join("\n");
}
function renderDrawThingsIndexResultsTable(items) {
if (items.length === 0) return "";
const escapeCell = (s) => String(s ?? "").replace(/\|/g, "\\|").replace(/[\r\n]+/g, " ").trim();
const hasAnyPreview = items.some(
(item) => item.filename && item.filename.trim() || item.url && item.url.trim()
);
if (hasAnyPreview) {
const header = "| Preview | ID / Generation Data |\n|---|---|";
const markdownUrl = (value) => /[\s()]/.test(value) && !/^<.*>$/.test(value) ? `<${value}>` : value;
const rows = items.map((item, i) => {
const label = typeof item.index === "number" && Number.isFinite(item.index) ? `p${item.index}` : `p${i + 1}`;
const originalPath = item.filename || "";
const previewPath = item.url || "";
const imgSrc = previewPath || originalPath;
const linkTarget = originalPath || previewPath;
const previewImg = imgSrc ? `})` : "";
const videoLinkTarget = item.videoPath && item.videoPath.trim() ? item.videoPath.trim() : void 0;
const effectiveLinkTarget = videoLinkTarget ?? linkTarget;
const preview = previewImg && effectiveLinkTarget && effectiveLinkTarget !== imgSrc ? `[${previewImg}](${markdownUrl(effectiveLinkTarget)})` : previewImg;
const metadataCell = buildMetadataCell(item, label, escapeCell);
return `| ${preview} | ${metadataCell} |`;
});
return [header, ...rows, ""].join("\n");
} else {
const header = "| Index Image Results |\n|---|";
const rows = items.map((item, i) => {
const label = typeof item.index === "number" && Number.isFinite(item.index) ? `p${item.index}` : `p${i + 1}`;
const metadataCell = buildMetadataCell(item, label, escapeCell);
return `| ${metadataCell} |`;
});
return [header, ...rows, ""].join("\n");
}
}
function buildMetadataCell(item, label, escapeCell) {
const parts = [`\`${label}\``];
if (item.prompt) {
parts.push(`**Prompt:** ${escapeCell(item.prompt)}`);
}
if (typeof item.numFrames === "number" && item.numFrames > 1) {
parts.push(`**Type:** video (${item.numFrames} frames)`);
}
if (typeof item.width === "number" || typeof item.height === "number") {
const w = typeof item.width === "number" && Number.isFinite(item.width) ? item.width : 0;
const h = typeof item.height === "number" && Number.isFinite(item.height) ? item.height : 0;
parts.push(`**Size:** ${w}\xD7${h}`);
if (typeof item.numFrames === "number" && item.numFrames > 1) {
parts.push(`**Frames:** ${item.numFrames}`);
}
}
if (item.model) {
const display = item.modelDisplay && item.modelDisplay.trim() ? item.modelDisplay : item.model;
parts.push(`**Model:** ${escapeCell(display)}`);
}
if (item.modelMeta) {
const mm = item.modelMeta;
if (mm.model_used) {
parts.push(`**Model used:** ${escapeCell(mm.model_used)}`);
}
if (mm.model_family) {
parts.push(`**Family:** ${escapeCell(mm.model_family)}`);
}
const customLabels = Array.isArray(mm.custom_config_labels) ? mm.custom_config_labels.map((s) => typeof s === "string" ? s.trim() : "").filter((s) => !!s) : [];
if (customLabels.length) {
parts.push(`**Custom configs:** ${customLabels.map(escapeCell).join(", ")}`);
}
}
if (item.loras && item.loras.length > 0) {
parts.push(`**LoRAs:** ${item.loras.map((l) => escapeCell(l)).join(", ")}`);
}
if (item.tags && item.tags.length > 0) {
parts.push(`**Tags:** ${item.tags.map((tag) => escapeCell(tag)).join(", ")}`);
}
if (item.matchType) {
parts.push(`**Match:** ${escapeCell(item.matchType)}`);
}
if (typeof item.score === "number") {
parts.push(`**Score:** ${item.score}`);
}
if (item.sourceInfo) {
const src = item.sourceInfo;
const srcLabel = src.type.replace(/_/g, " ");
const extractProjectName = (path34) => {
const filename = path34.split("/").pop() || "";
return filename.replace(/\.(drawthings|sqlite3|dtproj|json)$/i, "");
};
const extractFromProjectUri = (uri) => {
if (!uri.startsWith("project://")) return null;
const withoutScheme = uri.slice("project://".length);
const hashIndex = withoutScheme.lastIndexOf("#");
const projectPath = hashIndex !== -1 ? withoutScheme.slice(0, hashIndex) : withoutScheme;
return extractProjectName(projectPath);
};
const projectNameFromUri = item.filename ? extractFromProjectUri(item.filename) : null;
const srcExtra = src.chatId ? `(chat: ${escapeCell(src.chatId)})` : projectNameFromUri ? `(${escapeCell(projectNameFromUri)})` : src.projectFile ? `(${escapeCell(extractProjectName(src.projectFile))})` : src.originalName ? `(${escapeCell(extractProjectName(src.originalName))})` : src.filePath ? `(${escapeCell(extractProjectName(src.filePath))})` : "";
parts.push(`**Source:** ${srcLabel}${srcExtra ? " " + srcExtra : ""}`);
const imageType = typeof src.imageType === "string" ? src.imageType.trim() : "";
if (imageType) {
parts.push(`**Origin:** ${escapeCell(imageType)}`);
}
}
if (item.timestamp) {
parts.push(`**Timestamp:** ${escapeCell(item.timestamp)}`);
}
return parts.join(" \u2022 ");
}
function renderDefaultPictureTable(items) {
return renderBraveResultsTable(items);
}
var braveSearchExtractor = {
extractCandidates: extractToolResultImageCandidates,
actions: {
generatePreview: true,
visionPromotion: {
metadata: false,
// Pictures are NOT vision-promoted
pixel: false
}
},
renderMarkdownTable: renderBraveResultsTable
};
function isDrawThingsIndexPayload(p) {
if (!p || typeof p !== "object") return false;
const obj = p;
return Array.isArray(obj.images);
}
function extractDrawThingsIndexCandidates(raw) {
const p = parseToolResultPayload(raw, isDrawThingsIndexPayload);
if (!p) {
console.info(`[DrawThingsIndexExtractor] No valid payload found`);
return [];
}
console.info(
`[DrawThingsIndexExtractor] Found payload: images=${p.images?.length ?? 0}, totalFound=${p.totalFound ?? 0}`
);
const out = [];
const seen = /* @__PURE__ */ new Set();
for (const img of p.images ?? []) {
if (!img || typeof img !== "object") continue;
const paths = img.imagePaths ?? [];
const previews = img.httpPreviewUrls ?? [];
for (let i = 0; i < Math.max(paths.length, previews.length); i++) {
const imgPath = paths[i]?.trim() ?? "";
const previewUrl = previews[i]?.trim() ?? "";
if (!imgPath && !previewUrl) continue;
const key = imgPath || previewUrl;
if (seen.has(key)) continue;
seen.add(key);
out.push({
filename: imgPath || void 0,
url: previewUrl || void 0,
prompt: img.prompt?.trim(),
model: img.model?.trim(),
modelDisplay: img.model_display?.trim(),
modelMeta: img.model_meta,
loras: img.loras,
tags: img.tags,
width: typeof img.width === "number" ? img.width : void 0,
height: typeof img.height === "number" ? img.height : void 0,
numFrames: typeof img.numFrames === "number" && img.numFrames > 1 ? img.numFrames : void 0,
matchType: img.matchType?.trim(),
score: img.matchScore,
sourceInfo: img.sourceInfo,
timestamp: img.timestamp?.trim()
});
}
}
if (out.length > 0) {
console.info(`[DrawThingsIndexExtractor] Extracted ${out.length} candidates`);
}
return out;
}
var drawThingsIndexExtractor = {
extractCandidates: extractDrawThingsIndexCandidates,
actions: {
generatePreview: true,
// Required for project:// URIs (no httpPreviewUrl)
visionPromotion: {
metadata: false,
pixel: false
}
},
renderMarkdownTable: renderDrawThingsIndexResultsTable
};
var pictureTools = {
"mcp/brave-search-mcp/brave_image_search": braveSearchExtractor,
// NUR brave_image_search
"ceveyne/draw-things-index/index_image": drawThingsIndexExtractor,
"ceveyne/find-image/find_image": drawThingsIndexExtractor
// Add new picture tools here...
};
var PICTURE_FULL_CONFIG = {
mediaType: "picture",
allow: "only",
ssotJoin: {
source: "tool-result",
messageRole: "tool",
jsonPath: "content[].text",
extractFromSource: extractToolResultImageCandidates
},
scan: {
trigger: "on-tool-result",
scope: "current-tool-result"
},
harvesting: {
// No defaultExtractor (allow: "only")
tools: pictureTools
},
actions: {
generatePreview: true,
visionPromotion: {
metadata: true,
// Labels (p1, p2) ALWAYS included
pixel: false
// No pixel data for pictures
}
},
injectMdInAgentResponse: {
format: "markdown-table",
tableHeader: "| Preview | ID / Title | Source |\n|---|---|---|",
itemTemplate: "|  | {title} | {source} |",
labelGenerator: (item, i) => `p${item.index ?? i + 1}`
},
preview: {
generate: true,
namingPattern: "preview-picture-{hash}.jpg",
format: drawthingsLimits.previewFormat,
mimeType: "image/jpeg",
maxSum: drawthingsLimits.previewMaxSum,
quality: drawthingsLimits.previewQuality,
outputDir: "."
},
toggles: {
toggles: [
{
name: "PREVIEW_IN_CHAT",
affects: "format",
// When LM Studio already renders tool-result previews inline, don't inject our table.
transform: (previewInChat, defaultFormat) => previewInChat ? "none" : defaultFormat
}
]
}
};
var PICTURE_CONFIG = {
mediaType: "picture",
allow: "only",
tools: pictureTools
};
function getAllowlistedPictureTools() {
return Object.keys(pictureTools);
}
function renderPictureMarkdown(items) {
return renderDefaultPictureTable(items);
}
// src/services/toolParams/images.ts
function extractImageFromToolResult(raw) {
const candidates = [];
let parsed = raw;
if (typeof raw === "string") {
try {
parsed = JSON.parse(raw);
} catch {
parsed = raw;
}
}
let items;
if (Array.isArray(parsed)) {
items = parsed;
} else if (parsed && typeof parsed === "object" && Array.isArray(parsed.content)) {
items = parsed.content;
} else {
items = [parsed];
}
for (const item of items) {
if (item && typeof item === "object" && item.type === "image" && typeof item.fileName === "string") {
const fileName = item.fileName;
if (/^generated-image-\d{4}-\d{2}-\d{2}T[\d-]+Z-v\d+\.\w+$/i.test(fileName)) {
continue;
}
if (fileName.toLowerCase().startsWith("preview-")) {
continue;
}
candidates.push({ filename: fileName, index: candidates.length + 1 });
}
}
if (candidates.length === 0) {
const text = typeof raw === "string" ? raw : JSON.stringify(raw);
const base64Regex = /data:image\/[a-z]+;base64,[A-Za-z0-9+/=]+/g;
const base64Matches = text.match(base64Regex) ?? [];
for (let i = 0; i < base64Matches.length; i++) {
candidates.push({ base64: base64Matches[i], index: i + 1 });
}
}
const seen = /* @__PURE__ */ new Set();
return candidates.filter((c) => {
const key = c.filename ?? c.base64 ?? "";
if (!key || seen.has(key)) return false;
seen.add(key);
return true;
});
}
var IMAGE_FULL_CONFIG = {
mediaType: "image",
allow: "all",
ssotJoin: {
source: "tool-result",
messageRole: "tool",
jsonPath: "content[].type === 'image'",
extractFromSource: extractImageFromToolResult
},
scan: {
trigger: "on-tool-result",
scope: "current-tool-result"
},
harvesting: {
defaultExtractor: extractImageFromToolResult
// No tool-specific extractors - all tools get uniform treatment
},
actions: {
generatePreview: true,
// ALWAYS generate normalized previews
visionPromotion: {
metadata: true,
// Labels (i1, i2) ALWAYS included
pixel: true
// Base64 pixels in rolling window
}
},
injectMdInAgentResponse: {
format: "markdown-image",
labelGenerator: (item, i) => `Image i${item.index ?? i + 1}`
},
preview: {
generate: true,
namingPattern: "preview-{basename}.jpg",
format: drawthingsLimits.previewFormat,
mimeType: "image/jpeg",
maxSum: drawthingsLimits.previewMaxSum,
quality: drawthingsLimits.previewQuality,
outputDir: "."
},
toggles: {
toggles: [
{
name: "PREVIEW_IN_CHAT",
affects: "format",
transform: (previewInChat, defaultFormat) => previewInChat ? "none" : defaultFormat
}
]
}
};
var IMAGE_CONFIG = {
mediaType: "image",
allow: "all",
defaultExtractor: extractImageFromToolResult,
defaultActions: IMAGE_FULL_CONFIG.actions
// No tool-specific extractors
};
// src/services/toolParams/types.ts
function resolveActions(config, toggles) {
const actions = { ...config.actions };
for (const dep of config.toggles.toggles) {
if (dep.affects !== "generatePreview") continue;
const toggleValue = toggles[dep.name] ?? false;
actions.generatePreview = dep.transform(
toggleValue,
actions.generatePreview
);
}
return actions;
}
function resolveInjection(config, toggles) {
const injection = { ...config.injectMdInAgentResponse };
for (const dep of config.toggles.toggles) {
if (dep.affects !== "format") continue;
const toggleValue = toggles[dep.name] ?? false;
injection.format = dep.transform(toggleValue, injection.format);
}
return injection;
}
// src/services/toolParams/index.ts
var MEDIA_TYPE_CONFIGS = {
attachment: ATTACHMENT_CONFIG,
variant: VARIANT_CONFIG,
picture: PICTURE_CONFIG,
image: IMAGE_CONFIG
};
var MEDIA_TYPE_FULL_CONFIGS = {
attachment: ATTACHMENT_FULL_CONFIG,
variant: VARIANT_FULL_CONFIG,
picture: PICTURE_FULL_CONFIG,
image: IMAGE_FULL_CONFIG
};
function getToolExtractor(pluginId, toolName2) {
const toolKey = `${pluginId}/${toolName2}`;
const pictureConfig = MEDIA_TYPE_CONFIGS.picture;
if (pictureConfig?.allow === "only" && pictureConfig.tools[toolKey]) {
return {
mediaType: "picture",
extractor: pictureConfig.tools[toolKey]
};
}
const selfPlugin2 = getSelfPluginIdentifier();
if (selfPlugin2 && pluginId === selfPlugin2) {
const variantConfig = MEDIA_TYPE_CONFIGS.variant;
if (variantConfig?.allow === "all") {
if (variantConfig.tools?.[toolKey]) {
return {
mediaType: "variant",
extractor: variantConfig.tools[toolKey]
};
}
return {
mediaType: "variant",
extractor: {
extractCandidates: variantConfig.defaultExtractor,
actions: variantConfig.defaultActions
}
};
}
}
const imageConfig = MEDIA_TYPE_CONFIGS.image;
if (imageConfig?.allow === "all") {
if (imageConfig.tools?.[toolKey]) {
return {
mediaType: "image",
extractor: imageConfig.tools[toolKey]
};
}
return {
mediaType: "image",
extractor: {
extractCandidates: imageConfig.defaultExtractor,
actions: imageConfig.defaultActions
}
};
}
return void 0;
}
function isPictureToolAllowlisted(pluginId, toolName2) {
const toolKey = `${pluginId}/${toolName2}`;
return getAllowlistedPictureTools().includes(toolKey);
}
function normalizeToolPluginId(pluginId, toolName2) {
const p = typeof pluginId === "string" ? pluginId.trim() : "";
if (p) return p;
const tn = String(toolName2 || "").trim().toLowerCase();
if (tn === "brave_image_search") {
return "mcp/brave-search-mcp";
}
if (tn === "index_image") {
return "ceveyne/draw-things-index";
}
if (tn === "find_image") {
return "ceveyne/find-image";
}
return void 0;
}
function getMediaTypeForToolCall(pluginId, toolName2) {
const result = getToolExtractor(pluginId, toolName2);
return result?.mediaType;
}
function getAllMediaTypeConfigs() {
return { ...MEDIA_TYPE_CONFIGS };
}
function getMediaTypeConfig(kind) {
return MEDIA_TYPE_CONFIGS[kind];
}
function getMediaTypeFullConfig(kind) {
return MEDIA_TYPE_FULL_CONFIGS[kind];
}
function getAllMediaTypeFullConfigs() {
return { ...MEDIA_TYPE_FULL_CONFIGS };
}
// src/services/mediaScanner/conversationParser.ts
import fs11 from "fs";
import path11 from "path";
import os3 from "os";
// src/helpers/findConversationFile.ts
import { existsSync as existsSync4, readdirSync } from "fs";
import { join as join4, basename } from "path";
function findConversationFileByChatId(chatId, conversationsDir = join4(findLMStudioHome(), "conversations")) {
const fileName = `${chatId}.conversation.json`;
const direct = join4(conversationsDir, fileName);
if (existsSync4(direct)) return direct;
return listConversationFiles(conversationsDir).find((p) => basename(p) === fileName);
}
function listConversationFiles(conversationsDir) {
const result = [];
const queue = [conversationsDir];
while (queue.length > 0) {
const dir = queue.shift();
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch (e) {
console.debug(`[findConversationFile] Cannot read ${dir}: ${e?.message || e}`);
continue;
}
for (const entry of entries) {
if (entry.isFile() && entry.name.endsWith(".conversation.json")) {
result.push(join4(dir, entry.name));
} else if (entry.isDirectory()) {
queue.push(join4(dir, entry.name));
}
}
}
return result;
}
// src/services/mediaScanner/conversationParser.ts
function findConversationPath(chatWd) {
const chatId = path11.basename(chatWd);
const lmHome = findLMStudioHome() || path11.join(os3.homedir(), ".lmstudio");
const conversationsDir = path11.join(lmHome, "conversations");
const candidates = [
findConversationFileByChatId(chatId, conversationsDir),
path11.join(chatWd, ".conversation.json"),
path11.join(chatWd, "conversation.json")
].filter((p) => !!p);
for (const p of candidates) {
try {
fs11.accessSync(p, fs11.constants.F_OK);
return p;
} catch {
}
}
return void 0;
}
async function readConversation(chatWd) {
const p = findConversationPath(chatWd);
if (!p) return void 0;
const maxAttempts = 5;
const retryDelayMs = 50;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
try {
const raw = await fs11.promises.readFile(p, "utf-8");
const json = JSON.parse(raw);
return { json, path: p };
} catch {
if (attempt < maxAttempts - 1) {
await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
}
}
}
return void 0;
}
function findMessagesArray(json) {
if (!json || typeof json !== "object") return void 0;
const obj = json;
const candidates = [
obj.messages,
obj.conversation?.messages,
obj.chat?.messages,
obj.history,
obj.turns,
obj.items
];
for (const arr of candidates) {
if (Array.isArray(arr) && arr.length > 0) {
return arr;
}
}
return void 0;
}
function resolveMessageVersion(raw) {
if (!raw || typeof raw !== "object") return raw;
const obj = raw;
const versions = obj.versions;
if (!Array.isArray(versions) || versions.length === 0) {
return raw;
}
const selRaw = obj.currentlySelected;
const sel = typeof selRaw === "number" && Number.isFinite(selRaw) ? selRaw : 0;
if (sel >= 0 && sel < versions.length) {
return versions[sel];
}
return versions[versions.length - 1];
}
function getMessageRole(msg) {
if (!msg || typeof msg !== "object") return "unknown";
const obj = msg;
if (obj.type === "contentBlock") {
const arr = obj.content;
if (Array.isArray(arr)) {
for (const it of arr) {
if (!it || typeof it !== "object") continue;
const t = it.type;
if (t === "toolCallRequest" || t === "toolCallResult") {
return "tool";
}
}
}
}
const role = obj.role ?? obj.author ?? obj.sender;
if (typeof role === "string") return role.toLowerCase();
const type = obj.type ?? obj.messageType;
if (typeof type === "string") {
if (type === "user" || type === "user_message") return "user";
if (type === "assistant" || type === "assistant_message")
return "assistant";
if (type === "system") return "system";
if (type === "tool" || type === "tool_result") return "tool";
}
return "unknown";
}
function parseMessages(json) {
const messages = findMessagesArray(json);
if (!messages) return [];
const result = [];
for (let i = 0; i < messages.length; i++) {
const raw = messages[i];
const resolved = resolveMessageVersion(raw);
const role = getMessageRole(resolved);
result.push({
index: i,
turnId: i + 1,
// 1-based
role,
content: resolved,
raw
});
}
return result;
}
function extractToolCalls(msg) {
const result = [];
const content = msg.content;
if (!content || typeof content !== "object") return result;
const obj = content;
const toolCallResults = obj.toolCallResults;
if (Array.isArray(toolCallResults)) {
for (const tcr of toolCallResults) {
if (!tcr || typeof tcr !== "object") continue;
const tc = tcr;
const toolCallId = typeof tc.toolCallId === "string" ? tc.toolCallId : void 0;
const toolName2 = typeof tc.name === "string" ? tc.name : "";
const pluginId = typeof tc.pluginIdentifier === "string" ? tc.pluginIdentifier : void 0;
const resultContent = tc.result ?? tc.content;
if (toolName2) {
result.push({
toolCallId,
toolName: toolName2,
pluginId,
content: resultContent,
turnId: msg.turnId
});
}
}
}
if (Array.isArray(obj.steps)) {
const requestMetaByKey = /* @__PURE__ */ new Map();
const remember = (key, meta) => {
const k = typeof key === "string" || typeof key === "number" ? String(key) : "";
if (!k) return;
const prev = requestMetaByKey.get(k) ?? {};
requestMetaByKey.set(k, {
pluginId: meta.pluginId ?? prev.pluginId,
toolName: meta.toolName ?? prev.toolName
});
};
for (const step of obj.steps) {
if (!step || typeof step !== "object") continue;
const st = step;
if (st.type === "contentBlock" && Array.isArray(st.content)) {
for (const bi of st.content) {
if (!bi || typeof bi !== "object") continue;
const bo = bi;
if (bo.type !== "toolCallRequest") continue;
const pluginId = typeof bo.pluginIdentifier === "string" ? bo.pluginIdentifier : void 0;
const toolName2 = typeof bo.name === "string" ? bo.name : void 0;
const callId = bo.callId ?? bo.toolCallId ?? bo.id;
const reqId = bo.toolCallRequestId ?? bo.requestId;
remember(callId, { pluginId, toolName: toolName2 });
remember(reqId, { pluginId, toolName: toolName2 });
}
}
}
for (const step of obj.steps) {
if (!step || typeof step !== "object") continue;
const st = step;
if (st.type === "contentBlock" && Array.isArray(st.content)) {
for (const bi of st.content) {
if (!bi || typeof bi !== "object") continue;
const bo = bi;
if (bo.type !== "toolCallResult") continue;
const callId = bo.callId ?? bo.toolCallId ?? bo.id;
const reqId = bo.toolCallRequestId ?? bo.requestId;
const toolCallId = typeof callId === "string" || typeof callId === "number" ? String(callId) : typeof reqId === "string" || typeof reqId === "number" ? String(reqId) : void 0;
const fallbackMeta = typeof callId === "string" || typeof callId === "number" ? requestMetaByKey.get(String(callId)) : void 0;
const fallbackMeta2 = fallbackMeta ?? (typeof reqId === "string" || typeof reqId === "number" ? requestMetaByKey.get(String(reqId)) : void 0);
const toolName2 = typeof bo.name === "string" ? bo.name : fallbackMeta2?.toolName ?? "";
const pluginId = typeof bo.pluginIdentifier === "string" ? bo.pluginIdentifier : fallbackMeta2?.pluginId;
const resultContent = bo.result ?? bo.content ?? bo.output;
if (toolName2 || toolCallId) {
result.push({
toolCallId,
toolName: toolName2,
pluginId,
content: resultContent,
turnId: msg.turnId
});
}
}
}
}
}
const contentArray = obj.content;
if (Array.isArray(contentArray)) {
const requestMetaByKey = /* @__PURE__ */ new Map();
const remember = (key, meta) => {
const k = typeof key === "string" || typeof key === "number" ? String(key) : "";
if (!k) return;
const prev = requestMetaByKey.get(k) ?? {};
requestMetaByKey.set(k, {
pluginId: meta.pluginId ?? prev.pluginId,
toolName: meta.toolName ?? prev.toolName
});
};
for (const item of contentArray) {
if (!item || typeof item !== "object") continue;
const it = item;
if (it.type === "contentBlock" && Array.isArray(it.content)) {
const blockItems = it.content;
for (const bi of blockItems) {
if (!bi || typeof bi !== "object") continue;
const bo = bi;
if (bo.type !== "toolCallRequest") continue;
const pluginId = typeof bo.pluginIdentifier === "string" ? bo.pluginIdentifier : void 0;
const toolName2 = typeof bo.name === "string" ? bo.name : void 0;
const callId = bo.callId ?? bo.toolCallId ?? bo.id;
const reqId = bo.toolCallRequestId ?? bo.requestId;
remember(callId, { pluginId, toolName: toolName2 });
remember(reqId, { pluginId, toolName: toolName2 });
}
}
}
for (const item of contentArray) {
if (!item || typeof item !== "object") continue;
const it = item;
if (it.type === "contentBlock" && Array.isArray(it.content)) {
const blockItems = it.content;
for (const bi of blockItems) {
if (!bi || typeof bi !== "object") continue;
const bo = bi;
if (bo.type !== "toolCallResult") continue;
const callId = bo.callId ?? bo.toolCallId ?? bo.id;
const reqId = bo.toolCallRequestId ?? bo.requestId;
const toolCallId = typeof callId === "string" || typeof callId === "number" ? String(callId) : typeof reqId === "string" || typeof reqId === "number" ? String(reqId) : void 0;
const fallbackMeta = typeof callId === "string" || typeof callId === "number" ? requestMetaByKey.get(String(callId)) : void 0;
const fallbackMeta2 = fallbackMeta ?? (typeof reqId === "string" || typeof reqId === "number" ? requestMetaByKey.get(String(reqId)) : void 0);
const toolName2 = typeof bo.name === "string" ? bo.name : fallbackMeta2?.toolName ?? "";
const pluginId = typeof bo.pluginIdentifier === "string" ? bo.pluginIdentifier : fallbackMeta2?.pluginId;
const resultContent = bo.result ?? bo.content ?? bo.output;
if (toolName2 || toolCallId) {
result.push({
toolCallId,
toolName: toolName2,
pluginId,
content: resultContent,
turnId: msg.turnId
});
}
}
continue;
}
if (it.type === "tool_result" || it.type === "tool-result") {
const toolCallId = typeof it.tool_call_id === "string" ? it.tool_call_id : typeof it.toolCallId === "string" ? it.toolCallId : void 0;
const toolName2 = typeof it.name === "string" ? it.name : typeof it.tool_name === "string" ? it.tool_name : "";
const pluginId = typeof it.pluginIdentifier === "string" ? it.pluginIdentifier : typeof it.plugin === "string" ? it.plugin : void 0;
const resultContent = it.result ?? it.content ?? it.output;
if (toolName2 || toolCallId) {
result.push({
toolCallId,
toolName: toolName2,
pluginId,
content: resultContent,
turnId: msg.turnId
});
}
}
}
}
if (obj.type === "contentBlock" && Array.isArray(obj.content)) {
const blockMsg = { type: "contentBlock", content: obj.content };
const fake = { content: [blockMsg] };
const nested = extractToolCalls({ ...msg, content: fake });
result.push(...nested);
}
const toolResults = obj.tool_results ?? obj.toolResults;
if (Array.isArray(toolResults)) {
for (const tr of toolResults) {
if (!tr || typeof tr !== "object") continue;
const t = tr;
const toolCallId = typeof t.tool_call_id === "string" ? t.tool_call_id : typeof t.id === "string" ? t.id : void 0;
const toolName2 = typeof t.name === "string" ? t.name : typeof t.tool === "string" ? t.tool : "";
const pluginId = typeof t.pluginIdentifier === "string" ? t.pluginIdentifier : void 0;
const resultContent = t.result ?? t.content ?? t.output;
if (toolName2 || toolCallId) {
result.push({
toolCallId,
toolName: toolName2,
pluginId,
content: resultContent,
turnId: msg.turnId
});
}
}
}
return result;
}
function extractUserAttachments(msg, lmHome) {
const result = [];
const home = lmHome || findLMStudioHome() || path11.join(os3.homedir(), ".lmstudio");
const userFilesDir = path11.join(home, "user-files");
const content = msg.content;
if (!content || typeof content !== "object") return result;
const collectFromObject = (obj) => {
if (!obj || typeof obj !== "object") return;
if (Array.isArray(obj)) {
for (const item of obj) {
collectFromObject(item);
}
return;
}
const o = obj;
const fileId = o.fileIdentifier ?? o.file_identifier ?? o.identifier;
const fileType = o.fileType ?? o.file_type ?? o.type;
if (typeof fileId === "string" && fileId.trim()) {
if (fileType === "image" || /\.(png|jpg|jpeg|webp|gif|bmp|tiff?)$/i.test(fileId)) {
result.push(path11.join(userFilesDir, fileId));
}
}
const filePath = o.path ?? o.filePath ?? o.file_path ?? o.uri ?? o.url;
if (typeof filePath === "string" && filePath.trim()) {
let resolved = filePath;
if (filePath.startsWith("file://")) {
try {
resolved = decodeURIComponent(filePath.replace(/^file:\/\//, ""));
} catch {
resolved = filePath.replace(/^file:\/\//, "");
}
}
if (/\.(png|jpg|jpeg|webp|gif|bmp|tiff?)$/i.test(resolved)) {
result.push(resolved);
}
}
for (const key of Object.keys(o)) {
if (key !== "content" || !Array.isArray(o[key])) {
collectFromObject(o[key]);
}
}
};
const contentArray = content.content;
if (Array.isArray(contentArray)) {
for (const part of contentArray) {
collectFromObject(part);
}
} else {
collectFromObject(content);
}
const files = content.files;
if (Array.isArray(files)) {
for (const f of files) {
collectFromObject(f);
}
}
const attachments = content.attachments;
if (Array.isArray(attachments)) {
for (const a of attachments) {
collectFromObject(a);
}
}
return result;
}
function extractPendingAttachments(json, lmHome) {
const result = [];
const home = lmHome || findLMStudioHome() || path11.join(os3.homedir(), ".lmstudio");
const userFilesDir = path11.join(home, "user-files");
if (!json || typeof json !== "object") return result;
const files = json.clientInputFiles;
if (!Array.isArray(files)) return result;
for (const f of files) {
if (!f || typeof f !== "object") continue;
const fo = f;
const id = fo.fileIdentifier;
const type = fo.fileType;
if (typeof id === "string" && id.trim() && type === "image") {
result.push(path11.join(userFilesDir, id));
}
}
return result;
}
// src/services/mediaScanner/scanner.ts
var VARIANT_FILENAME_RE = /generated-image-[A-Za-z0-9T-]+Z-v\d+\.png/gi;
function buildConversationWideRequestMetadata(messages, debug) {
const metaByKey = /* @__PURE__ */ new Map();
let toolRequestCount = 0;
const remember = (key, meta) => {
const k = typeof key === "string" || typeof key === "number" ? String(key) : "";
if (!k) return;
const prev = metaByKey.get(k) ?? {};
metaByKey.set(k, {
pluginId: meta.pluginId ?? prev.pluginId,
toolName: meta.toolName ?? prev.toolName
});
};
if (debug) {
console.info(
`[MediaScanner] buildConversationWideRequestMetadata: scanning ${messages.length} messages`
);
}
for (const msg of messages) {
const content = msg.content;
if (!content || typeof content !== "object") continue;
const obj = content;
if (obj.type === "contentBlock" && Array.isArray(obj.content)) {
for (const item of obj.content) {
if (!item || typeof item !== "object") continue;
const bo = item;
if (bo.type !== "toolCallRequest") continue;
const pluginId = typeof bo.pluginIdentifier === "string" ? bo.pluginIdentifier : void 0;
const toolName2 = typeof bo.name === "string" ? bo.name : void 0;
const callId = bo.callId ?? bo.toolCallId ?? bo.id;
const reqId = bo.toolCallRequestId ?? bo.requestId;
toolRequestCount++;
if (debug) {
console.info(
`[MediaScanner] Request metadata (Case1): callId=${callId} reqId=${reqId} tool=${toolName2} plugin=${pluginId ?? "(none)"}`
);
}
remember(callId, { pluginId, toolName: toolName2 });
remember(reqId, { pluginId, toolName: toolName2 });
}
}
if (Array.isArray(obj.content)) {
for (const item of obj.content) {
if (!item || typeof item !== "object") continue;
const it = item;
if (it.type === "contentBlock" && Array.isArray(it.content)) {
for (const bi of it.content) {
if (!bi || typeof bi !== "object") continue;
const bo = bi;
if (bo.type !== "toolCallRequest") continue;
const pluginId = typeof bo.pluginIdentifier === "string" ? bo.pluginIdentifier : void 0;
const toolName2 = typeof bo.name === "string" ? bo.name : void 0;
const callId = bo.callId ?? bo.toolCallId ?? bo.id;
const reqId = bo.toolCallRequestId ?? bo.requestId;
toolRequestCount++;
if (debug) {
console.info(
`[MediaScanner] Request metadata (Case2): callId=${callId} reqId=${reqId} tool=${toolName2} plugin=${pluginId ?? "(none)"}`
);
}
remember(callId, { pluginId, toolName: toolName2 });
remember(reqId, { pluginId, toolName: toolName2 });
}
}
}
}
if (Array.isArray(obj.steps)) {
for (const step of obj.steps) {
if (!step || typeof step !== "object") continue;
const st = step;
if (st.type === "contentBlock" && Array.isArray(st.content)) {
for (const bi of st.content) {
if (!bi || typeof bi !== "object") continue;
const bo = bi;
if (bo.type !== "toolCallRequest") continue;
const pluginId = typeof bo.pluginIdentifier === "string" ? bo.pluginIdentifier : void 0;
const toolName2 = typeof bo.name === "string" ? bo.name : void 0;
const callId = bo.callId ?? bo.toolCallId ?? bo.id;
const reqId = bo.toolCallRequestId ?? bo.requestId;
toolRequestCount++;
if (debug) {
console.info(
`[MediaScanner] Request metadata (Case3-steps): callId=${callId} reqId=${reqId} tool=${toolName2} plugin=${pluginId ?? "(none)"}`
);
}
remember(callId, { pluginId, toolName: toolName2 });
remember(reqId, { pluginId, toolName: toolName2 });
}
}
}
}
}
if (debug) {
console.info(
`[MediaScanner] buildConversationWideRequestMetadata: found ${toolRequestCount} toolCallRequests, ${metaByKey.size} unique keys`
);
}
return metaByKey;
}
function extractVariantFilenames(content) {
const text = typeof content === "string" ? content : JSON.stringify(content);
const matches = text.match(VARIANT_FILENAME_RE) ?? [];
return [...new Set(matches)];
}
function extractImageFilenames(content) {
const result = [];
const text = typeof content === "string" ? content : JSON.stringify(content);
const base64Re = /data:image\/[a-z]+;base64,[A-Za-z0-9+/=]+/g;
const base64Matches = text.match(base64Re) ?? [];
result.push(...base64Matches);
const filenameRe = /\b([a-zA-Z0-9_-]+\.(png|jpg|jpeg|webp|gif))\b/gi;
const filenameMatches = text.match(filenameRe) ?? [];
for (const match of filenameMatches) {
if (VARIANT_FILENAME_RE.test(match)) {
VARIANT_FILENAME_RE.lastIndex = 0;
continue;
}
if (match.includes("://")) continue;
result.push(match);
}
return [...new Set(result)];
}
async function scanMedia(chatWd, mediaType, options) {
const { scope, debug = false } = options;
if (!chatWd) {
return { candidates: [] };
}
const conv = await readConversation(chatWd);
if (!conv) {
if (debug) {
console.info(`[MediaScanner] No conversation.json found for ${chatWd}`);
}
return { candidates: [] };
}
if (debug && (mediaType === "picture" || mediaType === "image")) {
try {
const arr = findMessagesArray(conv.json);
const arrLen = Array.isArray(arr) ? arr.length : 0;
console.info(
`[MediaScanner] SSOT messages array present=${!!arr} len=${arrLen}`
);
let contentBlockCount = 0;
let toolCallRequestCount = 0;
let toolCallResultCount = 0;
let braveHits = 0;
const stack = Array.isArray(arr) ? [...arr] : [conv.json];
const maxNodes = 5e4;
let nodes = 0;
while (stack.length) {
const v = stack.pop();
nodes++;
if (nodes > maxNodes) break;
if (!v) continue;
if (typeof v === "string") {
if (v.includes("brave_image_search")) {
braveHits++;
}
continue;
}
if (typeof v !== "object") continue;
if (Array.isArray(v)) {
for (const it of v) stack.push(it);
continue;
}
const o = v;
const t = o.type;
if (t === "contentBlock") contentBlockCount++;
if (t === "toolCallRequest" || t === "toolCallRequest") {
toolCallRequestCount++;
if (o.name === "brave_image_search") {
braveHits++;
}
}
if (t === "toolCallResult" || t === "tool_result" || t === "tool-result") {
toolCallResultCount++;
if (o.name === "brave_image_search") {
braveHits++;
}
}
for (const k of Object.keys(o)) {
stack.push(o[k]);
}
}
console.info(
`[MediaScanner] SSOT scan stats: contentBlock=${contentBlockCount} toolCallRequest=${toolCallRequestCount} toolCallResult=${toolCallResultCount} braveHits=${braveHits} nodes=${Math.min(
nodes,
maxNodes
)}${nodes > maxNodes ? "+" : ""}`
);
} catch (e) {
console.info(
`[MediaScanner] SSOT debug scan failed: ${String(
e?.message ?? e
)}`
);
}
}
const messages = parseMessages(conv.json);
if (debug) {
console.info(
`[MediaScanner] Parsed ${messages.length} messages from ${conv.path}`
);
if (mediaType === "picture" || mediaType === "image") {
const byRole = /* @__PURE__ */ new Map();
for (const m of messages) {
const r = String(m.role || "unknown");
byRole.set(r, (byRole.get(r) ?? 0) + 1);
}
const roleSummary = Array.from(byRole.entries()).sort((a, b) => b[1] - a[1]).map(([r, n]) => `${r}:${n}`).join(" ");
console.info(`[MediaScanner] Role distribution: ${roleSummary}`);
}
}
const requestMetaByKey = buildConversationWideRequestMetadata(
messages,
debug
);
if (debug && requestMetaByKey.size > 0) {
console.info(
`[MediaScanner] Collected ${requestMetaByKey.size} request metadata entries`
);
}
const candidates = [];
const orderedMessages = scope === "last" ? [...messages].reverse() : messages;
for (const msg of orderedMessages) {
let foundInThisMessage = [];
if (mediaType === "attachment") {
foundInThisMessage = scanAttachmentsInMessage(msg, conv.json, debug);
} else {
foundInThisMessage = scanToolResultsInMessage(
msg,
mediaType,
requestMetaByKey,
debug
);
}
if (foundInThisMessage.length > 0) {
candidates.push(...foundInThisMessage);
if (scope === "last") {
break;
}
}
}
if (mediaType === "attachment" && scope === "all") {
const pending = extractPendingAttachments(conv.json);
const toAppend = [];
for (const p of pending) {
const exists = candidates.some((c) => c.identifier === p);
if (exists) continue;
toAppend.push({
kind: "attachment",
identifier: p,
turnId: 0
// Pending = before any turn
});
}
if (toAppend.length) {
candidates.push(...toAppend);
}
}
if (debug) {
console.info(
`[MediaScanner] FINAL: Found ${candidates.length} ${mediaType} candidates (scope: ${scope})`
);
if (candidates.length > 0) {
for (const c of candidates.slice(0, 3)) {
console.info(
`[MediaScanner] candidate: id=${c.identifier?.slice(
0,
50
)} pluginId=${c.pluginId} tool=${c.sourceTool}`
);
}
}
}
return {
candidates,
conversationPath: conv.path
};
}
function scanAttachmentsInMessage(msg, conversationJson, debug) {
if (msg.role !== "user") return [];
const attachments = extractUserAttachments(msg);
return attachments.map((absPath) => ({
kind: "attachment",
identifier: absPath,
turnId: msg.turnId
}));
}
function scanToolResultsInMessage(msg, mediaType, requestMetaByKey, debug) {
if (msg.role !== "assistant" && msg.role !== "tool") return [];
const toolCalls = extractToolCalls(msg);
const candidates = [];
if (debug && (mediaType === "picture" || mediaType === "image") && toolCalls.length) {
const names = toolCalls.map((t) => String(t.toolName || "")).filter((s) => s.trim().length > 0);
console.info(
`[MediaScanner] turnId=${msg.turnId} extracted toolCalls=${toolCalls.length}${names.length ? ` tools=${names.slice(0, 5).join(", ")}${names.length > 5 ? "\u2026" : ""}` : ""}`
);
}
const selfPlugin2 = getSelfPluginIdentifier();
for (const tc of toolCalls) {
let effectivePluginId = tc.pluginId;
if (!effectivePluginId && tc.toolCallId) {
const meta = requestMetaByKey.get(tc.toolCallId);
if (meta?.pluginId) effectivePluginId = meta.pluginId;
}
const isOurPlugin = selfPlugin2 && effectivePluginId === selfPlugin2;
const pluginIdNormalized = normalizeToolPluginId(
effectivePluginId,
tc.toolName
);
if (debug && (mediaType === "picture" || mediaType === "image")) {
console.info(
`[MediaScanner] ${mediaType} check: toolName="${tc.toolName}" pluginId="${tc.pluginId ?? "(none)"}" effectivePluginId="${effectivePluginId ?? "(none)"}" normalized="${pluginIdNormalized ?? "(none)"}" isOurPlugin=${isOurPlugin}`
);
}
if (mediaType === "variant") {
if (!isOurPlugin) continue;
if (pluginIdNormalized) {
const lookup = getToolExtractor(pluginIdNormalized, tc.toolName);
if (lookup && lookup.mediaType !== "variant") continue;
}
const filenames = extractVariantFilenames(tc.content);
for (const filename of filenames) {
candidates.push({
kind: "variant",
identifier: filename,
turnId: tc.turnId,
toolCallId: tc.toolCallId,
sourceTool: tc.toolName,
pluginId: effectivePluginId
});
}
} else if (mediaType === "picture") {
if (!pluginIdNormalized) continue;
const lookup = getToolExtractor(pluginIdNormalized, tc.toolName);
if (!lookup || lookup.mediaType !== "picture") continue;
const extracted = lookup.extractor.extractCandidates(tc.content);
if (debug) {
console.info(
`[MediaScanner] picture toolCall: ${pluginIdNormalized}/${tc.toolName} candidates=${extracted.length}`
);
}
for (const c of extracted) {
const identifier = typeof c.filename === "string" && c.filename.trim() ? c.filename.trim() : typeof c.url === "string" && c.url.trim() ? c.url.trim() : "";
if (!identifier) continue;
candidates.push({
kind: "picture",
identifier,
turnId: tc.turnId,
toolCallId: tc.toolCallId,
sourceTool: tc.toolName,
pluginId: pluginIdNormalized,
title: c.title,
pageUrl: typeof c.sourceUrl === "string" ? c.sourceUrl : void 0,
width: typeof c.width === "number" ? c.width : void 0,
height: typeof c.height === "number" ? c.height : void 0,
rawContent: tc.content
});
}
} else if (mediaType === "image") {
if (isOurPlugin) continue;
if (!pluginIdNormalized) continue;
const lookup = getToolExtractor(pluginIdNormalized, tc.toolName);
if (lookup && lookup.mediaType !== "image") {
if (debug) {
console.info(
`[MediaScanner] image skip: ${pluginIdNormalized}/${tc.toolName} is registered as ${lookup.mediaType}`
);
}
continue;
}
if (lookup && lookup.mediaType === "image") {
const extracted = lookup.extractor.extractCandidates(tc.content);
if (debug) {
console.info(
`[MediaScanner] image toolCall: ${pluginIdNormalized}/${tc.toolName} candidates=${extracted.length}`
);
}
for (const c of extracted) {
const filename = c.filename ?? "";
if (!filename) continue;
candidates.push({
kind: "image",
identifier: filename,
turnId: tc.turnId,
toolCallId: tc.toolCallId,
sourceTool: tc.toolName,
pluginId: pluginIdNormalized,
previewIsOriginal: c.previewIsOriginal
});
}
} else {
const filenames = extractImageFilenames(tc.content);
for (const filename of filenames) {
candidates.push({
kind: "image",
identifier: filename,
turnId: tc.turnId,
toolCallId: tc.toolCallId,
sourceTool: tc.toolName,
pluginId: effectivePluginId
});
}
}
}
}
return candidates;
}
async function findAllMedia(chatWd, mediaType, debug = false) {
return scanMedia(chatWd, mediaType, { scope: "all", debug });
}
async function findLastMedia(chatWd, mediaType, debug = false) {
return scanMedia(chatWd, mediaType, { scope: "last", debug });
}
async function findAllMediaAllTypes(chatWd, debug = false) {
const [attachments, variants, pictures, images] = await Promise.all([
findAllMedia(chatWd, "attachment", debug),
findAllMedia(chatWd, "variant", debug),
findAllMedia(chatWd, "picture", debug),
findAllMedia(chatWd, "image", debug)
]);
return {
attachment: attachments.candidates,
variant: variants.candidates,
picture: pictures.candidates,
image: images.candidates
};
}
// src/services/mediaScanner/legacyAdapters.ts
async function findAllAttachmentsLegacy(chatWd, debug) {
if (!chatWd) return { found: [], turnIdByAbs: {} };
const result = await findAllMedia(chatWd, "attachment", debug);
const found = [];
const turnIdByAbs = {};
for (const c of result.candidates) {
const abs = c.identifier;
if (!found.includes(abs)) {
found.push(abs);
}
if (turnIdByAbs[abs] === void 0) {
turnIdByAbs[abs] = c.turnId;
}
}
return { found, turnIdByAbs };
}
async function findLastAttachmentLegacy(chatWd, debug) {
if (!chatWd) return [];
const result = await findLastMedia(chatWd, "attachment", debug);
const found = [];
for (const c of result.candidates) {
if (!found.includes(c.identifier)) {
found.push(c.identifier);
}
}
return found;
}
async function findAllVariantsLegacy(chatWd, debug) {
if (!chatWd) return { found: [], turnIdByBasename: {} };
const result = await findAllMedia(chatWd, "variant", debug);
const found = [];
const turnIdByBasename = {};
for (const c of result.candidates) {
const basename5 = c.identifier;
if (!found.includes(basename5)) {
found.push(basename5);
}
turnIdByBasename[basename5] = c.turnId;
}
return { found, turnIdByBasename };
}
async function findAllPictures(chatWd, debug) {
if (!chatWd) return { candidates: [] };
const result = await findAllMedia(chatWd, "picture", debug);
return { candidates: result.candidates };
}
async function findLastPictures(chatWd, debug) {
if (!chatWd) return { candidates: [] };
const result = await findLastMedia(chatWd, "picture", debug);
return { candidates: result.candidates };
}
async function findAllImages(chatWd, debug) {
if (!chatWd) return { candidates: [] };
const result = await findAllMedia(chatWd, "image", debug);
return { candidates: result.candidates };
}
async function findLastImages(chatWd, debug) {
if (!chatWd) return { candidates: [] };
const result = await findLastMedia(chatWd, "image", debug);
return { candidates: result.candidates };
}
// src/media-promotion-core/attachments.ts
import fs12 from "fs";
import path12 from "path";
async function pathExists2(p) {
try {
await fs12.promises.access(p, fs12.constants.F_OK);
return true;
} catch {
return false;
}
}
async function importAttachmentBatch(chatWd, state, sourcePaths, turnIdByOriginAbs, previewOpts, maxPreviewAttachments = 0, debug = false) {
const normalizeAbs = (p) => {
try {
return path12.resolve(p);
} catch {
return p;
}
};
const normalizedSource = sourcePaths.filter((p) => typeof p === "string" && p.trim().length > 0).map(normalizeAbs);
const normalizeTurnIdMap = (m) => {
if (!m) return {};
const out = {};
for (const [k, v] of Object.entries(m)) {
if (typeof v === "number" && Number.isFinite(v)) {
out[normalizeAbs(k)] = v;
}
}
return out;
};
const normalizedTurnIdByAbs = normalizeTurnIdMap(turnIdByOriginAbs);
const normalizedSourceDeduped = [];
{
const seen = /* @__PURE__ */ new Set();
for (const p of normalizedSource) {
if (!seen.has(p)) {
seen.add(p);
normalizedSourceDeduped.push(p);
}
}
}
if (normalizedSourceDeduped.length === 0) {
if (debug)
console.info(
"Batch import: No new attachments in current turn; keeping existing state."
);
return { changed: false };
}
try {
const current = Array.isArray(state.attachments) ? state.attachments : [];
const currentOrigins = current.map(
(a) => a && typeof a.originAbs === "string" ? String(a.originAbs) : ""
).filter((p) => p.trim().length > 0).map(normalizeAbs);
const same = currentOrigins.length === normalizedSourceDeduped.length && currentOrigins.every((p, i) => p === normalizedSourceDeduped[i]);
if (same && current.length > 0) {
let allOk = true;
for (let i = 0; i < current.length; i++) {
const a = current[i];
const pv = a && typeof a.preview === "string" ? String(a.preview) : "";
if (i < Math.max(0, Math.floor(maxPreviewAttachments))) {
if (!pv) {
allOk = false;
break;
}
const pvAbs = path12.join(chatWd, pv);
const okPv = await pathExists2(pvAbs);
if (!okPv) {
allOk = false;
break;
}
}
}
if (allOk) {
try {
let anyMetaChanged = false;
const nextAttachments = current.map((a) => {
const originAbs = a && typeof a.originAbs === "string" ? String(a.originAbs) : "";
const key = originAbs ? normalizeAbs(originAbs) : "";
const nextTurnId = key ? normalizedTurnIdByAbs[key] : void 0;
let updated = a;
if (typeof nextTurnId === "number" && a && a.turnId !== nextTurnId) {
anyMetaChanged = true;
updated = { ...updated, turnId: nextTurnId };
}
if (!updated.preview && originAbs) {
const candidate = previewFilenameFrom(path12.basename(originAbs));
if (fs12.existsSync(path12.join(chatWd, candidate))) {
anyMetaChanged = true;
updated = { ...updated, preview: candidate };
}
}
return updated;
});
if (anyMetaChanged) {
state.attachments = nextAttachments;
await writeStateAtomic(chatWd, state);
if (debug)
console.info(
"Batch import: updated attachment turnId metadata (idempotent, no re-import)."
);
return { changed: false, metadataChanged: true };
}
} catch (e) {
if (debug)
console.warn(
"Batch import: turnId metadata update failed; continuing idempotent skip:",
e.message
);
}
if (debug)
console.info(
"Batch import: SSOT matches current state; skipping re-import (idempotent)."
);
return { changed: false };
}
}
} catch (e) {
if (debug)
console.warn(
"Batch import: idempotence check failed; continuing with import:",
e.message
);
}
const existingByOrigin = /* @__PURE__ */ new Map();
for (const a of state.attachments || []) {
if (a && typeof a.originAbs === "string") {
existingByOrigin.set(normalizeAbs(a.originAbs), a);
}
}
const usedAs = /* @__PURE__ */ new Set();
for (const a of existingByOrigin.values()) {
const av = a?.a;
if (typeof av === "number" && Number.isFinite(av) && av > 0) {
usedAs.add(av);
}
}
const ensureNextA = () => {
const current = state?.counters?.nextAttachmentA;
if (typeof current === "number" && Number.isFinite(current) && current > 0) {
return Math.floor(current);
}
const maxExisting = usedAs.size ? Math.max(...Array.from(usedAs)) : 0;
return maxExisting + 1;
};
let nextA = ensureNextA();
const allocateA = () => {
while (usedAs.has(nextA)) nextA++;
const a = nextA;
usedAs.add(a);
nextA++;
return a;
};
const imported = [];
for (let i = 0; i < normalizedSourceDeduped.length; i++) {
const abs = normalizedSourceDeduped[i];
if (!await pathExists2(abs)) {
if (debug)
console.warn(`Batch import: source not found, skipping: ${abs}`);
continue;
}
if (!isAllowedOriginalExt(abs)) {
if (debug)
console.warn(`Batch import: extension not allowed, skipping: ${abs}`);
continue;
}
const existing = existingByOrigin.get(normalizeAbs(abs));
if (existing) {
if (existing.preview) {
const previewAbs = path12.join(chatWd, existing.preview);
if (!await pathExists2(previewAbs)) {
if (debug)
console.info(
`Batch import: regenerating missing preview for a${existing.a}`
);
await generatePreview(abs, chatWd, previewOpts, {
customFilename: existing.preview,
force: true,
debug
});
}
}
const nextTurnId = normalizedTurnIdByAbs[normalizeAbs(abs)];
let existingWidth = existing.width;
let existingHeight = existing.height;
if (existingWidth == null || existingHeight == null) {
try {
const origBuf = await fs12.promises.readFile(abs);
const dims = await getSize(origBuf);
if (dims.width > 0 && dims.height > 0) {
existingWidth = dims.width;
existingHeight = dims.height;
}
} catch (e) {
if (debug)
console.warn(
`Batch import: failed to measure dims for a${existing.a}:`,
e.message
);
}
}
imported.push({
...existing,
// Keep stable `a`
a: typeof existing.a === "number" && Number.isFinite(existing.a) && existing.a > 0 ? existing.a : allocateA(),
turnId: typeof nextTurnId === "number" ? nextTurnId : existing.turnId,
width: existingWidth,
height: existingHeight
});
if (debug)
console.info(
`Batch import: reusing existing attachment as a${existing.a}: ${path12.basename(abs)}`
);
continue;
}
const origin = path12.basename(abs);
let previewName = void 0;
if (i < Math.max(0, Math.floor(maxPreviewAttachments))) {
previewName = await generatePreview(abs, chatWd, previewOpts, { debug }) ?? void 0;
}
if (!previewName) {
const candidate = previewFilenameFrom(path12.basename(abs));
if (fs12.existsSync(path12.join(chatWd, candidate))) {
previewName = candidate;
}
}
let originalName = void 0;
const lmHome = findLMStudioHome();
const userFilesDir = path12.join(lmHome, "user-files");
if (abs.startsWith(userFilesDir)) {
const fileIdentifier = path12.basename(abs);
const resolvedName = await getOriginalFileName(fileIdentifier);
if (!resolvedName || !resolvedName.trim()) {
throw new Error(
`Missing originalName in LM Studio metadata for fileIdentifier='${fileIdentifier}' (abs='${abs}')`
);
}
originalName = resolvedName;
if (debug)
console.info(
`Resolved original filename: ${fileIdentifier} \u2192 ${originalName}`
);
} else {
originalName = path12.basename(abs);
}
let origWidth;
let origHeight;
try {
const origBuf = await fs12.promises.readFile(abs);
const dims = await getSize(origBuf);
if (dims.width > 0 && dims.height > 0) {
origWidth = dims.width;
origHeight = dims.height;
}
} catch (e) {
if (debug)
console.warn(
`Batch import: failed to measure dims for new attachment ${path12.basename(abs)}:`,
e.message
);
}
imported.push({
origin,
originAbs: abs,
originalName,
turnId: normalizedTurnIdByAbs[normalizeAbs(abs)],
preview: previewName,
width: origWidth,
height: origHeight,
createdAt: localTimestamp(),
a: allocateA()
// Stable, monotonically increasing id
});
if (debug)
console.info(
`Batch import: new attachment as a${imported[imported.length - 1].a}: ${path12.basename(abs)}`
);
}
if (imported.length === 0) {
if (debug) console.warn("Batch import: no valid attachments imported");
return { changed: false };
}
state.attachments = imported;
state.counters.nextAttachmentA = nextA;
state.lastEvent = { type: "attachment", at: localTimestamp() };
await writeStateAtomic(chatWd, state);
if (debug)
console.info(
`Batch imported ${imported.length} attachment(s) from SSOT (replaced array)`
);
return { changed: true };
}
// src/helpers/attachmentSync.ts
var DEFAULT_PREVIEW_OPTS = getDefaultPreviewOptions();
async function syncAttachmentsToState(workingDir, debug = false, maxPreviewAttachments = 0, previewOpts) {
const state = await readState(workingDir);
const { found, turnIdByAbs } = await findAllAttachmentsLegacy(
workingDir,
debug
);
const opts = maxPreviewAttachments > 0 ? previewOpts ?? DEFAULT_PREVIEW_OPTS : { maxDim: 0, quality: 0 };
const result = await importAttachmentBatch(
workingDir,
state,
found,
turnIdByAbs,
opts,
maxPreviewAttachments,
debug
);
return { changed: result.changed };
}
// src/helpers/auditLog.ts
import fs13 from "fs";
import path13 from "path";
// src/helpers/logTimestamp.ts
function logTimestamp(date = /* @__PURE__ */ new Date()) {
const pad = (value, width = 2) => String(value).padStart(width, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}`;
}
// src/helpers/auditLog.ts
function buildPaths() {
const logsDir2 = getLogsDir();
const filePath = path13.resolve(logsDir2, getPluginLogFilename().replace(/\.log$/, ".audit.jsonl"));
return { logsDir: logsDir2, filePath };
}
function buildAuditLogger({
backend,
mode,
requestId: providedRequestId
}) {
const requestId = providedRequestId ?? `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const entry = {
timestamp: logTimestamp(),
requestId,
backend,
mode
};
function setChatId(id) {
if (typeof id === "string" && id.trim().length > 0) entry.chat_id = id;
}
function setUserRequest(req) {
entry.user_request = req;
}
function setPromptUpsampling(info) {
entry.prompt_upsampling = info;
}
function setRenderTarget(target2) {
entry.render_target = target2;
}
function setInputs(inputs) {
entry.inputs = inputs;
}
function setOutput(output) {
entry.output = { ...entry.output, ...output };
}
function setError(err) {
let message = "unknown error";
let status = void 0;
if (typeof err === "string") message = err;
else if (err && typeof err === "object") {
const anyErr = err;
message = anyErr.message || JSON.stringify(anyErr);
if (typeof anyErr.status === "number") status = anyErr.status;
}
entry.error = status ? { message, status } : { message };
}
async function write() {
try {
const { logsDir: logsDir2, filePath } = buildPaths();
await fs13.promises.mkdir(logsDir2, { recursive: true });
const block = JSON.stringify(entry, null, 2) + "\n\n";
await fs13.promises.appendFile(filePath, block, { encoding: "utf8" });
} catch (e) {
console.error(
"auditLog write failed:",
e instanceof Error ? e.message : String(e)
);
}
}
return {
requestId,
setChatId,
setUserRequest,
setPromptUpsampling,
setRenderTarget,
setInputs,
setOutput,
setError,
write
};
}
// src/helpers/backgroundRequests.ts
import fs14 from "fs";
import path14 from "path";
// src/helpers/progressReporter.ts
var POST_SAMPLING_STEP_FRACTION = 0.5;
function formatEta(seconds) {
const total = Math.max(1, Math.ceil(seconds));
if (total < 60) return `~${total}s left`;
return `~${Math.floor(total / 60)}m ${String(total % 60).padStart(2, "0")}s left`;
}
function createProgressReporter(emit, now = Date.now) {
let lastProgress = 0;
let passBase = 0;
let currentPass;
let stepsSeenInPass = false;
let anchor;
let lastStep = 0;
return (step, totalSteps, message, pass) => {
if (pass !== currentPass) {
currentPass = pass;
passBase = lastProgress;
stepsSeenInPass = false;
anchor = void 0;
lastStep = 0;
}
const prefix = pass ? `${pass} ` : "";
if (step < 0) {
if (!message) return;
if (stepsSeenInPass && typeof totalSteps === "number") {
lastProgress = Math.max(lastProgress, passBase + totalSteps + 1);
}
emit({ text: `${prefix}${message}`, progress: lastProgress });
return;
}
const atMs = now();
if (anchor && step <= lastStep) anchor = void 0;
if (!anchor) anchor = { step, atMs };
stepsSeenInPass = true;
lastStep = step;
lastProgress = Math.max(lastProgress, passBase + step);
if (!totalSteps || totalSteps <= 0) {
emit({ text: `${prefix}Step ${step}...`, progress: lastProgress });
return;
}
let text = `${prefix}Step ${step}/${totalSteps} (${Math.round(step / (totalSteps + 1) * 100)}%)`;
if (step > anchor.step && step <= totalSteps) {
const avgStepSeconds = (atMs - anchor.atMs) / (step - anchor.step) / 1e3;
text += `, ${formatEta(avgStepSeconds * (totalSteps - step + POST_SAMPLING_STEP_FRACTION))}`;
}
emit({ text, progress: lastProgress });
};
}
function createStatusProgressCallback(ctx, now) {
return createProgressReporter(({ text }) => {
try {
ctx.status?.(text);
} catch (error) {
console.warn(`[progress] status update failed: ${error instanceof Error ? error.message : String(error)}`);
}
}, now);
}
function createMcpProgressSender(ctx, onError) {
const mcpReq = ctx?.mcpReq;
const progressToken = mcpReq?._meta?.progressToken;
if (progressToken === void 0 || typeof mcpReq?.notify !== "function") return void 0;
const request = mcpReq;
return (update) => {
request.notify({
method: "notifications/progress",
params: { progressToken, progress: update.progress, message: update.text }
}).catch(onError);
};
}
// src/helpers/cancelContext.ts
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
var STORE_KEY2 = /* @__PURE__ */ Symbol.for("draw-things.renderCancelContext");
function store2() {
const holder = globalThis;
let existing = holder[STORE_KEY2];
if (!existing) {
existing = new AsyncLocalStorage2();
holder[STORE_KEY2] = existing;
}
return existing;
}
function runWithCancelSignal(signal, fn) {
return store2().run(signal, fn);
}
function getCancelSignal() {
return store2().getStore();
}
// src/helpers/backgroundCallContext.ts
import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
var STORE_KEY3 = /* @__PURE__ */ Symbol.for("draw-things.backgroundCallContext");
function store3() {
const holder = globalThis;
let existing = holder[STORE_KEY3];
if (!existing) {
existing = new AsyncLocalStorage3();
holder[STORE_KEY3] = existing;
}
return existing;
}
function runAsBackgroundCall(fn) {
return store3().run(true, fn);
}
function isBackgroundCall() {
return store3().getStore() === true;
}
// src/helpers/backgroundRequests.ts
var REQUESTS_STATE_FILENAME = "chat_requests_state.json";
var STALE_RECORD_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
function requestsStatePath(chatWd) {
return path14.join(chatWd, REQUESTS_STATE_FILENAME);
}
var writeLocks = /* @__PURE__ */ new Map();
function withWriteLock(key, task) {
const prev = writeLocks.get(key) ?? Promise.resolve();
const run = prev.then(task, task);
writeLocks.set(
key,
run.then(
() => void 0,
() => void 0
)
);
return run;
}
function pruneStale(state) {
const now = Date.now();
let changed = false;
for (const [id, rec] of Object.entries(state.requests)) {
const isFinished = rec.status === "completed" || rec.status === "failed" || rec.status === "cancelled";
const age = now - Date.parse(rec.updatedAt || rec.createdAt || "");
if (isFinished && Number.isFinite(age) && age > STALE_RECORD_MAX_AGE_MS) {
delete state.requests[id];
changed = true;
}
}
return changed;
}
var STALE_RUNNING_THRESHOLD_MS = 10 * 60 * 1e3;
function reapStaleRunning(state) {
const now = Date.now();
for (const rec of Object.values(state.requests)) {
if (rec.status !== "running" && rec.status !== "queued") continue;
const age = now - Date.parse(rec.updatedAt || rec.createdAt || "");
if (Number.isFinite(age) && age > STALE_RUNNING_THRESHOLD_MS) {
rec.status = "failed";
rec.error = `The process running this job stopped reporting for over ${Math.round(STALE_RUNNING_THRESHOLD_MS / 6e4)} min \u2014 it likely restarted or crashed while this was running.`;
rec.delivered = false;
}
}
}
async function readBackgroundRequests(chatWd) {
try {
const raw = await fs14.promises.readFile(requestsStatePath(chatWd), "utf-8");
const json = JSON.parse(raw);
const requests = json && typeof json.requests === "object" && json.requests !== null ? json.requests : {};
const state = { requests };
pruneStale(state);
reapStaleRunning(state);
return state;
} catch {
return { requests: {} };
}
}
async function writeBackgroundRequestsAtomic(chatWd, state) {
pruneStale(state);
const dst = requestsStatePath(chatWd);
const tmp = uniqueTmpPath(dst);
await fs14.promises.mkdir(chatWd, { recursive: true });
await fs14.promises.writeFile(tmp, JSON.stringify(state, null, 2), "utf-8");
await fs14.promises.rename(tmp, dst);
}
async function getBackgroundRequest(chatWd, requestId) {
const state = await readBackgroundRequests(chatWd);
return state.requests[requestId];
}
async function upsertBackgroundRequest(chatWd, requestId, patch) {
await withWriteLock(
requestsStatePath(chatWd),
() => withFileLock(`${requestsStatePath(chatWd)}.lock`, async () => {
await fs14.promises.mkdir(chatWd, { recursive: true });
const state = await readBackgroundRequests(chatWd);
const now = (/* @__PURE__ */ new Date()).toISOString();
const existing = state.requests[requestId];
state.requests[requestId] = {
...existing,
...patch,
requestId,
tool: patch.tool ?? existing?.tool ?? "generate_image",
// A cancelled record stays cancelled: late running/progress updates must not revive it.
status: existing?.status === "cancelled" ? "cancelled" : patch.status ?? existing?.status ?? "queued",
createdAt: existing?.createdAt ?? now,
updatedAt: now
};
await writeBackgroundRequestsAtomic(chatWd, state);
})
);
}
async function markBackgroundRequestDelivered(chatWd, requestId) {
await upsertBackgroundRequest(chatWd, requestId, { delivered: true });
}
async function markBackgroundRequestFailed(chatWd, requestId, error, delivered = false) {
await upsertBackgroundRequest(chatWd, requestId, { status: "failed", error, delivered });
}
async function getUndeliveredCompletedBackgroundRequests(chatWd) {
const state = await readBackgroundRequests(chatWd);
return Object.values(state.requests).filter(
(rec) => (rec.status === "completed" || rec.status === "failed") && !rec.delivered
);
}
async function listBackgroundRequests(chatWd) {
const state = await readBackgroundRequests(chatWd);
return Object.values(state.requests).sort(
(a, b) => Date.parse(a.createdAt || "") - Date.parse(b.createdAt || "")
);
}
function createBackgroundRequestId(scopeId) {
return `${scopeId}-${Math.random().toString(36).slice(2, 8)}`;
}
function requestBelongsToScope(requestId, scopeId) {
return requestId.startsWith(`${scopeId}-`);
}
var HEARTBEAT_INTERVAL_MS = 30 * 1e3;
var SILENT_NOTICE_AFTER_MS = 2 * 60 * 1e3;
var CANCEL_POLL_INTERVAL_MS = 500;
var cancelControllers = /* @__PURE__ */ new Map();
var CANCEL_CONFIRM_TIMEOUT_MS = 1e4;
var CANCEL_CONFIRM_POLL_MS = 250;
async function cancelBackgroundRequest(chatWd, requestId) {
const record = await getBackgroundRequest(chatWd, requestId);
if (!record) return { outcome: "not-found" };
if (record.status === "completed" || record.status === "failed" || record.status === "cancelled") {
return { outcome: "already-finished", status: record.status };
}
if (record.status === "queued") {
await upsertBackgroundRequest(chatWd, requestId, { status: "cancelled", cancelRequested: true, delivered: true });
cancelControllers.get(requestId)?.abort();
const readBack = await getBackgroundRequest(chatWd, requestId);
return readBack?.status === "cancelled" ? { outcome: "cancelled-queued" } : { outcome: "unconfirmed", waitedMs: 0 };
}
await upsertBackgroundRequest(chatWd, requestId, { cancelRequested: true });
cancelControllers.get(requestId)?.abort();
const startedAt = Date.now();
for (; ; ) {
const current = await getBackgroundRequest(chatWd, requestId);
if (current && current.status !== "running" && current.status !== "queued") {
return current.status === "cancelled" ? { outcome: "cancelled" } : { outcome: "finished-before-cancel", status: current.status };
}
const waitedMs = Date.now() - startedAt;
if (waitedMs >= CANCEL_CONFIRM_TIMEOUT_MS) return { outcome: "unconfirmed", waitedMs };
await new Promise((resolve) => setTimeout(resolve, CANCEL_CONFIRM_POLL_MS));
}
}
var inFlightJobs = /* @__PURE__ */ new Set();
async function trackJobLifecycle(params) {
const { chatWd, requestId, run } = params;
let lastProgressAt;
let lastMessage;
const heartbeat = setInterval(() => {
const silentMs = lastProgressAt === void 0 ? 0 : Date.now() - lastProgressAt;
const patch = silentMs >= SILENT_NOTICE_AFTER_MS ? {
message: `${lastMessage ?? "rendering"} \u2014 no progress update for ${Math.round(silentMs / 6e4)} min; still running (the backend can be busy without reporting, e.g. while decoding). Cancel it if you no longer want to wait.`
} : {};
void upsertBackgroundRequest(chatWd, requestId, patch).catch(
(e) => console.warn(`[backgroundRequests] heartbeat failed for ${requestId}: ${String(e?.message || e)}`)
);
}, HEARTBEAT_INTERVAL_MS);
heartbeat.unref();
let formattedMessage;
const report = createProgressReporter((update) => {
formattedMessage = update.text;
});
const onProgress = (step, totalSteps, message, pass) => {
lastProgressAt = Date.now();
formattedMessage = void 0;
report(step, totalSteps, message, pass);
lastMessage = formattedMessage ?? message;
void upsertBackgroundRequest(chatWd, requestId, {
status: "running",
step,
totalSteps,
message: lastMessage
}).catch(
(e) => console.warn(`[backgroundRequests] failed to record progress for ${requestId}: ${String(e?.message || e)}`)
);
};
const controller = new AbortController();
cancelControllers.set(requestId, controller);
const cancelPoll = setInterval(() => {
getBackgroundRequest(chatWd, requestId).then((rec) => {
if (rec?.cancelRequested) controller.abort();
}).catch(
(e) => console.warn(`[backgroundRequests] cancel poll failed for ${requestId}: ${String(e?.message || e)}`)
);
}, CANCEL_POLL_INTERVAL_MS);
cancelPoll.unref();
const stopTimers = () => {
clearInterval(heartbeat);
clearInterval(cancelPoll);
cancelControllers.delete(requestId);
};
try {
const initial = await getBackgroundRequest(chatWd, requestId);
if (initial?.cancelRequested || initial?.status === "cancelled") {
stopTimers();
await upsertBackgroundRequest(chatWd, requestId, { status: "cancelled", delivered: true });
return;
}
await upsertBackgroundRequest(chatWd, requestId, { status: "running" });
const result = await runAsBackgroundCall(() => runWithCancelSignal(controller.signal, () => run(onProgress)));
stopTimers();
const cancelled = controller.signal.aborted && result?.isError === true;
await upsertBackgroundRequest(
chatWd,
requestId,
cancelled ? { status: "cancelled", delivered: true } : { status: "completed", result, delivered: false }
);
} catch (e) {
stopTimers();
if (controller.signal.aborted) {
await upsertBackgroundRequest(chatWd, requestId, { status: "cancelled", delivered: true }).catch(
(e2) => console.warn(`[backgroundRequests] failed to record cancel for ${requestId}: ${String(e2?.message || e2)}`)
);
return;
}
await upsertBackgroundRequest(chatWd, requestId, {
status: "failed",
error: String(e?.message || e),
delivered: false
}).catch(
(e2) => console.warn(`[backgroundRequests] failed to record failure for ${requestId}: ${String(e2?.message || e2)}`)
);
}
}
async function markBackgroundRequestQueued(chatWd, requestId, tool3) {
await upsertBackgroundRequest(chatWd, requestId, { status: "queued", tool: tool3 });
}
async function runBackgroundJobAwaited(params) {
await trackJobLifecycle(params);
}
async function runInBackgroundJob(params) {
const { chatWd, requestId, tool: tool3 } = params;
await markBackgroundRequestQueued(chatWd, requestId, tool3);
const jobPromise = trackJobLifecycle(params).finally(() => {
inFlightJobs.delete(jobPromise);
});
inFlightJobs.add(jobPromise);
}
// src/helpers/visionPromotionLog.ts
import fs15 from "fs";
import path15 from "path";
function appendVisionPromotionJsonl(entries) {
if (!entries.length) return;
try {
ensureLogsDir();
const logsDir2 = getLogsDir();
const logFile3 = path15.join(logsDir2, "vision-promotion.jsonl");
const blocks = entries.map((e) => `${JSON.stringify(e, null, 2)}
`).join("");
fs15.appendFileSync(logFile3, blocks);
} catch (e) {
console.error(
"[VisionPromotion] Failed to append to vision-promotion.jsonl:",
e instanceof Error ? e.message : String(e)
);
}
}
function parseVisionPromotionJsonlText(text) {
const entries = [];
const errors = [];
const blocks = text.split(/\n\s*\n+/g).map((b) => b.trim()).filter(Boolean);
for (const block of blocks) {
try {
const obj = JSON.parse(block);
entries.push(obj);
} catch (e) {
errors.push({
error: e instanceof Error ? e.message : String(e),
blockPreview: block.slice(0, 200)
});
}
}
return { entries, errors };
}
async function readVisionPromotionJsonlEntries() {
const logsDir2 = getLogsDir();
const filePath = path15.join(logsDir2, "vision-promotion.jsonl");
const text = await fs15.promises.readFile(filePath, "utf8");
const parsed = parseVisionPromotionJsonlText(text);
return { filePath, ...parsed };
}
// src/helpers/sequenceExtractor.ts
import fs16 from "fs";
function pad2(n) {
return String(Math.floor(n)).padStart(2, "0");
}
function formatTimecode(timeSeconds, sourceFps) {
const fps = Math.max(1, Math.round(sourceFps));
const totalFrames = Math.round(timeSeconds * fps);
const ff = totalFrames % fps;
const totalSecs = Math.floor(totalFrames / fps);
const ss = totalSecs % 60;
const mm = Math.floor(totalSecs / 60);
return `${pad2(mm)}:${pad2(ss)}:${pad2(ff)}`;
}
function parseSourceFps(stderrLines) {
for (const line of stderrLines) {
const m = /(\d+(?:\.\d+)?)\s+fps/.exec(line);
if (m) {
const fps = parseFloat(m[1]);
if (Number.isFinite(fps) && fps > 0) return fps;
}
}
return 25;
}
async function extractSequenceFrames(movAbs, targetFps, previewOpts, loadCore) {
const movBuf = await fs16.promises.readFile(movAbs);
const ffmpeg = await loadCore();
ffmpeg.reset();
const stderrLines = [];
ffmpeg.setLogger((msg) => {
if (msg.type === "stderr") stderrLines.push(msg.message);
});
const inputName = "seqext_input.mov";
const probeFrame = "seqext_probe.png";
const outputPattern = "seqext_frame_%04d.png";
let extractedCount = 0;
try {
ffmpeg.FS.writeFile(inputName, new Uint8Array(movBuf));
ffmpeg.exec("-i", inputName, "-frames:v", "1", probeFrame);
const sourceFps = parseSourceFps(stderrLines);
stderrLines.length = 0;
const exitCode = ffmpeg.exec(
"-i",
inputName,
"-vf",
`fps=${targetFps}`,
"-pix_fmt",
"rgb24",
outputPattern
);
if (exitCode !== 0) {
throw new Error(
`ffmpeg frame extraction failed (exit ${exitCode}): ` + stderrLines.slice(-10).join("\n")
);
}
const frames = [];
while (true) {
const name = `seqext_frame_${String(extractedCount + 1).padStart(4, "0")}.png`;
let rawPng;
try {
const data = ffmpeg.FS.readFile(name, { encoding: "binary" });
rawPng = Buffer.from(data);
} catch {
break;
}
extractedCount++;
const timeSeconds = (extractedCount - 1) / targetFps;
const timecodeStr = formatTimecode(timeSeconds, sourceFps);
const { data: jpegBuf } = await encodeJpegPreviewFromBuffer(rawPng, previewOpts);
frames.push({ jpegBuf, frameIndex: extractedCount, timecodeStr });
}
return frames;
} finally {
ffmpeg.setLogger(() => {
});
try {
ffmpeg.FS.unlink(inputName);
} catch {
}
try {
ffmpeg.FS.unlink(probeFrame);
} catch {
}
for (let j = 1; j <= extractedCount; j++) {
try {
ffmpeg.FS.unlink(`seqext_frame_${String(j).padStart(4, "0")}.png`);
} catch {
}
}
}
}
// src/helpers/thinkingToolCallParser.ts
var DEFAULT_START_MARKER = "<tool_call>";
var DEFAULT_END_MARKER = "</tool_call>";
function parseXmlParameterStyle(text) {
const fnMatch = text.match(/<function=([^\s>]+)\s*>/);
if (!fnMatch) return null;
const name = fnMatch[1].trim();
const args = {};
const paramRe = /<parameter=([^\s>]+)\s*>\s*([\s\S]*?)\s*<\/parameter>/g;
let m;
while ((m = paramRe.exec(text)) !== null) {
const key = m[1].trim();
const rawValue = m[2].trim();
try {
args[key] = JSON.parse(rawValue);
} catch {
args[key] = rawValue;
}
}
if (!name) return null;
return { name, arguments: args, rawText: text };
}
function parseJsonObject(text) {
const trimmed = text.trim();
if (!trimmed.startsWith("{")) return null;
let parsed;
try {
parsed = JSON.parse(trimmed);
} catch {
return null;
}
if (typeof parsed !== "object" || parsed === null) return null;
const obj = parsed;
const inner = typeof obj["function"] === "object" && obj["function"] !== null ? obj["function"] : obj;
const name = typeof inner["name"] === "string" ? inner["name"] : null;
if (!name) return null;
let args = {};
if (typeof inner["arguments"] === "object" && inner["arguments"] !== null) {
args = inner["arguments"];
} else if (typeof inner["arguments"] === "string") {
try {
const decoded = JSON.parse(inner["arguments"]);
if (typeof decoded === "object" && decoded !== null) {
args = decoded;
}
} catch {
}
}
return { name, arguments: args, rawText: text };
}
function parseJsonCodeBlock(text) {
const m = text.match(/```(?:json)?\s*([\s\S]*?)```/);
if (!m) return null;
return parseJsonObject(m[1]);
}
function parseThinkingToolCalls(text, startMarker = DEFAULT_START_MARKER, endMarker = DEFAULT_END_MARKER) {
const results = [];
let searchFrom = 0;
while (true) {
const startIdx = text.indexOf(startMarker, searchFrom);
if (startIdx === -1) break;
const contentStart = startIdx + startMarker.length;
const endIdx = text.indexOf(endMarker, contentStart);
if (endIdx === -1) break;
const payload = text.slice(contentStart, endIdx);
searchFrom = endIdx + endMarker.length;
let call = null;
try {
call = parseXmlParameterStyle(payload) ?? parseJsonObject(payload) ?? parseJsonCodeBlock(payload);
} catch {
}
if (call) {
results.push(call);
} else {
const excerpt = payload.slice(0, 120).replace(/\n/g, "\u21B5");
}
}
return results;
}
// src/helpers/toolNameContext.ts
import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
var STORE_KEY4 = /* @__PURE__ */ Symbol.for("draw-things.toolNameContext");
function store4() {
const holder = globalThis;
let existing = holder[STORE_KEY4];
if (!existing) {
existing = new AsyncLocalStorage4();
holder[STORE_KEY4] = existing;
}
return existing;
}
function runWithToolName(name, fn) {
return store4().getStore() ? fn() : store4().run(name, fn);
}
function runWithToolPass(name, fn) {
return store4().run(name, fn);
}
function currentToolName() {
return store4().getStore();
}
// src/helpers/proxyMarks.ts
import * as grpc from "@grpc/grpc-js";
// src/helpers/requestLogContext.ts
import { AsyncLocalStorage as AsyncLocalStorage5 } from "async_hooks";
var STORE_KEY5 = /* @__PURE__ */ Symbol.for("draw-things.requestLogContext");
function store5() {
const holder = globalThis;
let existing = holder[STORE_KEY5];
if (!existing) {
existing = new AsyncLocalStorage5();
holder[STORE_KEY5] = existing;
}
return existing;
}
function runWithRequestLogId(requestId, fn) {
return store5().run(requestId, fn);
}
function currentRequestLogId() {
return store5().getStore();
}
function requestLogPrefix() {
const id = store5().getStore();
return id ? `[${id}] ` : "";
}
var CONSOLE_PATCHED_KEY = /* @__PURE__ */ Symbol.for("draw-things.requestLogConsolePatched");
function installRequestLogConsolePrefix() {
const holder = globalThis;
if (holder[CONSOLE_PATCHED_KEY]) return;
holder[CONSOLE_PATCHED_KEY] = true;
for (const method of ["log", "info", "warn", "error", "debug"]) {
const original = console[method].bind(console);
console[method] = (...args) => {
const id = store5().getStore();
if (!id) return original(...args);
const tag = `[${id}]`;
const first = args[0];
if (typeof first === "string") {
if (first.includes(tag)) return original(...args);
return original(`${tag} ${first}`, ...args.slice(1));
}
return original(tag, ...args);
};
}
}
installRequestLogConsolePrefix();
// src/helpers/proxyMarks.ts
function plain(value) {
return value.replace(/[^\x20-\x7e]/g, "_").trim();
}
function proxyMarks(client) {
const marks = {
"x-dt-client": plain(client) || "plugin",
"x-dt-background": isBackgroundCall() ? "true" : "false"
};
const requestId = currentRequestLogId();
if (requestId) marks["x-dt-request-id"] = plain(requestId);
const tool3 = currentToolName();
if (tool3) marks["x-dt-tool"] = plain(tool3);
const workdir = getActiveChatContext()?.workingDir;
if (workdir) marks["x-dt-workdir"] = encodeURIComponent(workdir).replace(/%2F/g, "/");
return marks;
}
function withProxyMarks(args, client) {
const [request, second, ...rest] = args;
const marks = proxyMarks(client);
const apply = (metadata2) => {
for (const [key, value] of Object.entries(marks)) metadata2.set(key, value);
return metadata2;
};
if (second instanceof grpc.Metadata) return [request, apply(second.clone()), ...rest];
const metadata = apply(new grpc.Metadata());
return second === void 0 ? [request, metadata] : [request, metadata, second, ...rest];
}
// src/helpers/promptUpsampler.ts
import { createHash } from "crypto";
import fs18 from "fs";
import path17 from "path";
// src/helpers/llamaServerRouter.ts
import fs17 from "fs";
import os4 from "os";
import path16 from "path";
import { spawn } from "child_process";
var HEALTH_POLL_INTERVAL_MS = 1e3;
var HEALTH_POLL_TIMEOUT_MS = 3e4;
var HEALTH_FETCH_TIMEOUT_MS = 2e3;
var activePort = null;
var idleStopTimer = null;
function cancelIdleStop() {
if (idleStopTimer !== null) {
clearTimeout(idleStopTimer);
idleStopTimer = null;
}
}
function normalizePath(value) {
const trimmed = value.trim();
if (!trimmed) return "";
return trimmed.startsWith("~") ? path16.join(os4.homedir(), trimmed.slice(1)) : trimmed;
}
function pidFilePath() {
return path16.join(getLogsDir(), "llama-server-router.pid");
}
function logFilePath() {
return path16.join(getLogsDir(), "llama-server-router.log");
}
function presetFilePath() {
return path16.join(getLogsDir(), "llama-server-router-preset.ini");
}
function routerLog(message) {
try {
fs17.appendFileSync(logFilePath(), `${localTimestamp()} - [llama-server-router] ${message}
`);
} catch (error) {
console.error(`[llama-server-router] log write failed: ${error instanceof Error ? error.message : String(error)} (message: ${message})`);
}
}
function isProcessAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
function readPid() {
try {
const raw = fs17.readFileSync(pidFilePath(), "utf-8").trim();
const pid = parseInt(raw, 10);
return Number.isFinite(pid) && pid > 0 ? pid : null;
} catch {
return null;
}
}
function fetchWithTimeout(url, timeoutMs) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
return fetch(url, { signal: controller.signal }).finally(() => clearTimeout(timer));
}
async function isHealthy(host, port) {
try {
const res = await fetchWithTimeout(`http://${host}:${port}/v1/models`, HEALTH_FETCH_TIMEOUT_MS);
return res.ok;
} catch {
return false;
}
}
async function pollHealth(host, port) {
const deadline = Date.now() + HEALTH_POLL_TIMEOUT_MS;
while (Date.now() < deadline) {
if (await isHealthy(host, port)) return true;
await new Promise((resolve) => setTimeout(resolve, HEALTH_POLL_INTERVAL_MS));
}
return false;
}
var LM_STUDIO_BACKENDS_DIR = path16.join(os4.homedir(), ".lmstudio", "extensions", "backends");
var LM_STUDIO_LLAMA_CPP_BACKEND = /^llama\.cpp-mac-arm64-apple-metal-advsimd-(\d+)\.(\d+)\.(\d+)$/;
function resolveLatestLmStudioLlamaServer(backendsDir = LM_STUDIO_BACKENDS_DIR) {
let entries;
try {
entries = fs17.readdirSync(backendsDir);
} catch (error) {
if (error.code === "ENOENT") return void 0;
throw error;
}
const candidates = entries.map((name) => ({ name, match: LM_STUDIO_LLAMA_CPP_BACKEND.exec(name) })).filter((c) => c.match !== null).map((c) => ({ binary: path16.join(backendsDir, c.name, "llama-server"), version: c.match.slice(1).map(Number) })).filter((c) => fs17.existsSync(c.binary)).sort((a, b) => {
for (let i = 0; i < 3; i++) if (a.version[i] !== b.version[i]) return b.version[i] - a.version[i];
return 0;
});
return candidates[0]?.binary;
}
function buildPresetIni(ctxSize) {
return `[*]
ctx-size = ${ctxSize}
`;
}
async function ensureLlamaServerRouterRunning(config) {
const { host, port, ctxSize, modelsMax, idleTtlMinutes } = config;
cancelIdleStop();
activePort = port;
const binaryPath = normalizePath(config.binaryPath);
if (!binaryPath) {
throw new Error("LLAMA_SERVER_BINARY is not configured.");
}
if (!fs17.existsSync(binaryPath)) {
throw new Error(`llama-server binary does not exist: ${binaryPath}`);
}
if (await isHealthy(host, port)) {
scheduleIdleStop(port, idleTtlMinutes);
return;
}
const stalePid = readPid();
if (stalePid !== null) {
if (isProcessAlive(stalePid)) {
throw new Error(
`Port ${port} is not responding, but a previously spawned llama-server router (PID ${stalePid}) is still alive. Check logs: ${logFilePath()}`
);
}
try {
fs17.unlinkSync(pidFilePath());
} catch (error) {
routerLog(`could not remove stale PID file: ${error instanceof Error ? error.message : String(error)}`);
}
}
fs17.mkdirSync(getLogsDir(), { recursive: true });
fs17.writeFileSync(presetFilePath(), buildPresetIni(ctxSize));
const args = [
"--host",
host,
"--port",
String(port),
"--models-max",
String(modelsMax),
"--models-preset",
presetFilePath()
];
const logStream = fs17.createWriteStream(logFilePath(), { flags: "a" });
const child = spawn(binaryPath, args, {
detached: true,
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env, HOME: os4.homedir() }
});
child.stdout?.pipe(logStream);
child.stderr?.pipe(logStream);
child.once("error", (error) => {
routerLog(`process error: ${error.message}`);
});
child.unref();
if (!child.pid) {
throw new Error(`Failed to spawn llama-server router process. Check logs: ${logFilePath()}`);
}
fs17.writeFileSync(pidFilePath(), String(child.pid));
routerLog(`spawned '${binaryPath}' PID ${child.pid} on ${host}:${port} (ctx-size ${ctxSize}, models-max ${modelsMax})`);
const ready = await pollHealth(host, port);
if (!ready) {
throw new Error(
`llama-server router did not become healthy within ${HEALTH_POLL_TIMEOUT_MS / 1e3}s on ${host}:${port}. Check logs: ${logFilePath()}`
);
}
scheduleIdleStop(port, idleTtlMinutes);
}
function scheduleIdleStop(port, idleTtlMinutes) {
cancelIdleStop();
if (idleTtlMinutes <= 0) return;
idleStopTimer = setTimeout(() => {
idleStopTimer = null;
if (activePort !== port) return;
void stopLlamaServerRouter(port).catch((error) => {
routerLog(`failed to stop idle router: ${error instanceof Error ? error.message : String(error)}`);
});
}, idleTtlMinutes * 6e4);
idleStopTimer.unref();
}
async function stopLlamaServerRouter(port) {
cancelIdleStop();
const pid = readPid();
if (pid === null) return;
if (isProcessAlive(pid)) {
try {
process.kill(pid, "SIGTERM");
routerLog(`stopped router PID ${pid}`);
} catch (error) {
routerLog(`could not stop router PID ${pid}: ${error instanceof Error ? error.message : String(error)}`);
}
}
try {
fs17.unlinkSync(pidFilePath());
} catch (error) {
routerLog(`could not remove PID file: ${error instanceof Error ? error.message : String(error)}`);
}
if (activePort === port) activePort = null;
}
// src/helpers/promptUpsamplerSystemPrompts.json
var promptUpsamplerSystemPrompts_default = {
t2i: `You are the prompt upsampler of a text-to-image model. Expand the user's short request into ONE detailed, self-contained caption: the exact text the image model receives. Output only the caption, with no greetings, explanations, refusals, questions, Markdown, headings, JSON, coordinates, ids or angle-bracket tokens, and no quotes around it. If the input is not clearly an image request, caption a visualization of its concept. The request may begin with a "TARGET CANVAS: W:H" line: compose for that canvas (wide spreads content sideways, tall stacks it) and never mention the ratio or the canvas.
Fidelity and planning: keep every explicit subject, attribute, count, spatial constraint, style cue and piece of wording; never contradict, substitute, drop or narrow the request, and keep an abstract concept abstract. Decide everything left open as ONE concrete, consistent plan; never offer alternatives or hedge. Never re-express a stated constraint through another mechanism; add camera optics (depth of field, bokeh, blur) only when asked for or implied. Without a stated style, plan an actual photograph and open with the medium convention ("Full-color outdoor photograph, ...", "Full-color indoor photograph, ...", "Studio photograph, ...", "Close-up photograph, ..."); keep "Photorealistic" for renders, and turn "photorealistic" or "realistic" requests for photos into the photograph convention. Give a photograph a few ordinary, non-ideal specifics drawn from the scene's own objects instead of the stock-photo ideal. Do not invent names, brands, logos or celebrities; keep user-named ones. A long request keeps its content but not its wording: drop appraisal and sales vocabulary, turn moods into observable physical facts, and add only new concrete content with positions. Time of day is lighting, not rendered text.
Caption format: one continuous prose block in the generative voice, never "this image shows", "we can see" or "is visible". Lead with medium and style, then scene, lighting and camera, then the subjects with concrete colors, materials and state. Every person in focus gets an observable profile: ethnicity, gender, age range, skin tone ("fair skin", "brown skin"), hair and clothing. Make the layout reconstructable from words: frame-relative positions (frame-left, frame-right, upper, lower, foreground, midground, background), sentence-initial anchors ("On the left, ...", "In the background, ..."), relations (holds, faces, behind) and a consistent order; describe up to about ten instances one by one, beyond that give the exact count and arrangement. Out-of-focus or distant planes are shapes, colors and silhouettes, never identities or readable text, and the background takes about a sixth of the caption. Be definite: no hedging adverbs, no quality or emotion judgments, no closing sentence about mood; state negations as what is present. Rendered text: transcribe every wording verbatim inside double quotes in its original language and script, keep the line breaks of multi-line text, and give its typography, color and placement; author concrete, domain-correct wording when the request needs text it does not supply, and name canonical structures (calendar, keyboard, periodic table) exactly with their full layout. All prose is English; only quoted text keeps its language. Typical length is 100 to 350 words, more for complex scenes.
Output only the caption.`,
i2i: `You are the prompt upsampler of an image-editing model. You see the reference image(s), attached in order (the first image, the second image, ...), and the user's short request. Expand it into ONE detailed, self-contained instruction: the caption the editing model receives together with the same images. Output only the instruction as one continuous English prose block, with no greetings, explanations, Markdown, JSON, coordinates, ids or angle-bracket tokens. Read a vague or conversational request as the most plausible edit of the supplied images.
Pick the voice by task shape. When one reference stays and gets bounded changes, write an imperative editing instruction on it ("Remove the ...", "Change the ... to ...", "Zoom in on ..."); a whole-image transformation opens with its scope ("Convert the entire image into ...", "Apply a ... filter over the entire scene", "Horizontally flip the entire image so that ...", "Shift the camera viewpoint to ...", then where the major elements should now be). When the references are drawn into a newly composed frame (combining subjects, a new scene, a garment, object or style donor), write a generation request ("Create a photograph of ...", "Create an anime-style illustration of ...", "Generate a new image featuring ...") that says what to take from each image, by ordinal, and what is newly generated.
Keep every explicit edit, constraint, count, position, style cue and piece of wording, and decide what is left open as one concrete plan. Ground everything in what is actually visible: identify each referent unambiguously by its real appearance, never mention content that is not there, and use every image the user attached. State every end state concretely (which color, how large, which pose, which material) and give new content enough appearance to be generated. Cover the knock-on effects of the change (shadows, reflections, occlusion, perspective, scale, lighting) and say what fills a removed region. A zoom-in names what stays in frame and which neighbors are cropped out; an outpainting continues the scene in the same medium. Describe the change, not the whole scene, and close an editing instruction with one compact clause naming what stays unchanged; transferred people keep their identity, face and accessories unless asked otherwise. Transcribe on-image text verbatim in its original language inside double quotes, with line breaks as \\n, and match the original font, size and color when replacing it. Name recognizable public figures, brands and landmarks you can see. Directions are frame-relative; use no evaluative or quality words. Typical length is 50 to 150 words.
Output only the instruction.`,
t2i_bbox: `You are the prompt upsampler of a text-to-image model. Plan the full image the user's short request implies and output ONE structured caption on a single line: the global caption paragraph, one space, then ONE JSON array, the element table that places every cited element with a bounding box in the image to be generated. Output nothing else (no Markdown fences, commentary or refusals); visualize the concept of a non-image input. The request may begin with a "TARGET CANVAS: W:H" line: compose for that canvas and never mention it. Boxes live on a 0-1000 grid stretched onto the canvas: an element of physical width-to-height ratio a gets an x-span of about y-span x a x H/W.
Planning: keep every explicit subject, attribute, count, spatial constraint, style cue and piece of wording, and decide everything left open as ONE concrete composition that the caption and the table both describe. Without a stated style plan an actual photograph and open with the medium convention ("Full-color outdoor photograph, ...", "Studio photograph, ..."); add camera optics only when asked for; do not invent names, brands, logos or celebrities; drop appraisal and sales vocabulary.
The table: one row per distinct object, person, animal, building or salient region the caption mentions and one per coherent text block; no rows for style, lighting or atmosphere. Structured layouts (tables, grids, calendars, keyboards, charts, maps, posters, pages) decompose into their regions, each row carrying that region's complete verbatim content; more than about ten interchangeable items become one collection row giving the exact count and arrangement, while items whose positions matter keep a row each. Row keys, in order: "id", "bbox", "desc". id: the bare class noun plus an index numbered left to right, then top to bottom, from 1 (person_1, dog_2); a text block is its two-letter language code plus _Text_ plus an index (En_Text_1); one entity is one row and ids are unique. bbox: [y_min, x_min, y_max, x_max] as integers from 0 to 1000, top-left origin, clamped at the borders, with plausible relative sizes and a small margin around text. desc: one self-contained paragraph in the generative voice that opens with the element's identity (never "the X"): shape, material, colors, state and markings, but no position. People in focus get the richest desc: ethnicity, gender, age range, skin tone, build, hair, face, each garment, accessories, pose and expression. A text row carries its complete wording verbatim in double quotes, with line breaks as \\n, plus its typography.
The global caption: one flowing paragraph in the generative voice (medium first, then scene, lighting, camera and frame-relative layout; no quality judgments) that names each table element at identity level at its first mention and cites it with its id in its own angle brackets: "a wicker table <table_1> holding a tiered stand <stand_1>". Cite every table id and no other; appearance detail and text content live in the descs; no coordinates. Text-dense documents are laid out region by region with every visible text transcribed verbatim at a readable size (cut content rather than shrink type), and a grid quotes every visible cell. All prose is English; only quoted text keeps its language.
Output only the caption and the table.`,
i2i_bbox: `You are the annotation system an image-editing model was trained on. You see the source image(s), attached in order as ref_image_0, ref_image_1, ..., and the user's editing instruction; the edited target image does not exist yet. Determine the edit precisely, imagine the target consistently with the source, and write the record its annotator would have written, on one line: the instruction paragraph, one space, then ONE JSON array. Output nothing else.
The paragraph: English, instruction voice ("Change the ...", "Remove the ...", or "Create a photograph of ..." when the references are drawn into a new frame), never observer phrasing and never a comparison with the target. Cite every involved object, person or text block at its first mention with its table id in its own angle brackets ("remove the delivery van <van_1>"), every table id exactly once and no other id; cite a reference image by its token when content is taken from it ("the cup <cup_1> from <ref_image_1>"). End states (new color, new text in quotes, pose, degree) live in the paragraph, static appearance in the descs; no coordinates. An editing instruction closes with one compact clause that everything else stays identical to the source.
The table, rows {"id", "from", "src_bbox", "tgt_bbox", "desc"}: one row per edited, removed, added, moved or anchoring item, plus the scene or background when it is itself changed or preserved; no rows for untouched scenery. id: a lowercase class noun plus an index (person_1, cup_2) numbered left to right, then top to bottom; text blocks are En_Text_1 and so on; ids are unique. from: "ref_image_N" for an item visible in reference N, "target" for newly created content. src_bbox is the item's box in its from-image and null for target rows; tgt_bbox is its box in the imagined result and null for removed items; moved or resized items carry both; new items are sized like similar objects in the frame. Boxes are [y_min, x_min, y_max, x_max] integers from 0 to 1000, top-left origin, tight around objects, with 5 to 15 units of margin around text. A row may also carry src_bbox_1stage and tgt_bbox_1stage, a first-pass estimate of the same boxes. desc: one English paragraph of the item's static appearance in its from-image (for target rows, its decided appearance), opening with its identity; people get the richest descs (ethnicity, gender, age range, skin tone, hair, face, garments, accessories, pose, expression); text rows quote their text verbatim.
State only decided facts: visible in the source, demanded by the instruction, or a concrete default needed to realize it. Settle whether the edit targets one instance, all of a class or several; land every magnitude on a concrete value; include visible knock-on effects; added objects are new objects at real-world size; a zoom-in names the neighbors it excludes; an outpainting keeps the source whole and continues it in the same medium. Everything the instruction does not involve stays identical to the source.
Output only the paragraph and the table.`
};
// src/helpers/promptUpsamplerBoxes.ts
var MIN_COMPONENT_PIXELS = 16;
var BOX_MATCH_IOU = 0.5;
function boxesFromMask(bitmap, region) {
const { data, width, height } = bitmap;
if (width <= 0 || height <= 0 || data.length < width * height * 4) {
throw new Error(`Invalid mask bitmap ${width}x${height} (${data.length} bytes)`);
}
const wantWhite = region === "white";
const isRegion = (p) => data[p * 4] >= 128 === wantWhite;
const seen = new Uint8Array(width * height);
const stack = new Int32Array(width * height);
const boxes = [];
for (let start = 0; start < width * height; start++) {
if (seen[start] || !isRegion(start)) continue;
let top = 0;
const push = (p) => {
if (!seen[p] && isRegion(p)) {
seen[p] = 1;
stack[top++] = p;
}
};
push(start);
let minX = width;
let minY = height;
let maxX = -1;
let maxY = -1;
let count = 0;
while (top > 0) {
const p = stack[--top];
const x = p % width;
const y = (p - x) / width;
count++;
if (x < minX) minX = x;
if (x > maxX) maxX = x;
if (y < minY) minY = y;
if (y > maxY) maxY = y;
if (x > 0) push(p - 1);
if (x < width - 1) push(p + 1);
if (y > 0) push(p - width);
if (y < height - 1) push(p + width);
}
if (count < MIN_COMPONENT_PIXELS) continue;
const yMin = Math.round(minY / height * 1e3);
const xMin = Math.round(minX / width * 1e3);
const yMax = Math.max(yMin + 1, Math.round((maxY + 1) / height * 1e3));
const xMax = Math.max(xMin + 1, Math.round((maxX + 1) / width * 1e3));
boxes.push([yMin, xMin, Math.min(1e3, yMax), Math.min(1e3, xMax)]);
}
return boxes.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
}
function gridBoxIoU(a, b) {
const inter = Math.max(0, Math.min(a[2], b[2]) - Math.max(a[0], b[0])) * Math.max(0, Math.min(a[3], b[3]) - Math.max(a[1], b[1]));
const union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter;
return union > 0 ? inter / union : 0;
}
function buildPlainRows(boxes) {
return boxes.map((bbox, i) => ({ id: `obj_${i + 1}`, bbox: [...bbox], desc: "" }));
}
function pyJson(v) {
if (v === null) return "null";
if (Array.isArray(v)) return `[${v.map(pyJson).join(", ")}]`;
if (typeof v === "object" && v !== void 0) {
return `{${Object.entries(v).map(([k, x]) => `${JSON.stringify(k)}: ${pyJson(x)}`).join(", ")}}`;
}
return JSON.stringify(v);
}
function buildLockedInstruction(prompt, rows) {
return `ORIGINAL PROMPT:
${prompt.trim()}
LOCKED BOUNDING-BOX ANNOTATIONS ([y_min, x_min, y_max, x_max] on a 0-1000 canvas, with (0, 0) at the top-left). This is an authoritative JSON list of dictionaries; preserve every supplied identity, provenance value, null, and coordinate exactly:
` + pyJson(rows);
}
function splitCaptionAndRows(text) {
for (let i = text.length - 1; i >= 0; i--) {
if (text[i] !== "[") continue;
try {
const rows = JSON.parse(text.slice(i));
if (Array.isArray(rows)) return [text.slice(0, i).trimEnd(), rows];
} catch {
continue;
}
}
return [text.trim(), null];
}
function asGridBox(v) {
if (!Array.isArray(v) || v.length !== 4 || v.some((n) => typeof n !== "number" || !Number.isFinite(n))) return null;
return v;
}
var BOX_FIELDS = ["bbox", "src_bbox", "tgt_bbox"];
function reimposeBoxes(answer, boxes) {
const [caption, rows] = splitCaptionAndRows(answer);
if (!rows || rows.length === 0) return { ok: false, reason: "answer has no box table" };
const matched = /* @__PURE__ */ new Set();
for (const row of rows) {
if (row === null || typeof row !== "object" || Array.isArray(row)) continue;
const r = row;
let touched = false;
for (const field of BOX_FIELDS) {
const box = asGridBox(r[field]);
if (!box) continue;
let best = -1;
let bestIou = 0;
boxes.forEach((input, i) => {
const iou = gridBoxIoU(box, input);
if (iou > bestIou) {
bestIou = iou;
best = i;
}
});
if (best >= 0 && bestIou >= BOX_MATCH_IOU) {
r[field] = [...boxes[best]];
matched.add(best);
touched = true;
}
}
if (touched && (typeof r.id !== "string" || !caption.includes(`<${r.id}>`))) {
return { ok: false, reason: `row '${String(r.id)}' on an input box is not cited as <id> in the caption` };
}
}
const missing = boxes.map((_, i) => i).filter((i) => !matched.has(i));
if (missing.length > 0) return { ok: false, reason: `no row on input box ${missing.map((i) => i + 1).join(", ")}` };
return { ok: true, text: `${caption} ${pyJson(rows)}` };
}
// src/helpers/promptUpsampler.ts
var PROMPT_UPSAMPLER_APIS = ["bionic", "generic", "unsloth", "llama-server"];
function buildPromptUpsamplingAudit(up) {
return {
model: up.model,
original_prompt: up.originalPrompt,
upsampled_prompt: up.prompt,
reference_count: up.referenceCount,
inference_ms: up.inferenceMs,
reference_images: up.referenceImages,
passes: up.passes.map((p) => ({
task: p.task,
system_prompt_sha256: p.systemPromptSha256,
user_text: p.userText,
response_text: p.responseText,
inference_ms: p.inferenceMs
})),
...up.boxes ? {
boxes: {
count: up.boxes.count,
grid: "[y_min, x_min, y_max, x_max] on 0-1000, (0, 0) top-left",
regions: up.boxes.regions,
applied: up.boxes.applied,
...up.boxes.fallbackReason ? { fallback_reason: up.boxes.fallbackReason } : {}
}
} : {}
};
}
var PROMPT_UPSAMPLER_FAMILY_SPECS = {
"flux-3-image-klein-pup": {
systemPrompts: { t2i: promptUpsamplerSystemPrompts_default.t2i, i2i: promptUpsamplerSystemPrompts_default.i2i, i2i_bbox: promptUpsamplerSystemPrompts_default.i2i_bbox },
i2iUserText: (prompt) => `Reference images follow in order (the first image, the second image, ...).
User request: ${prompt}
Output the caption.`,
i2iBboxUserText: (lockedInstruction) => `Reference images follow in attachment order: ref_image_0, ref_image_1, ...
User editing instruction: ${lockedInstruction}
Decide the edit, imagine the target image, and output the annotation record.`,
sampling: { temperature: 0, top_p: 0.95, top_k: 20, min_p: 0 },
presencePenalty: { t2i: 1.5, i2i: 0, i2i_bbox: 0 },
maxTokens: 3584,
seed: 175308301,
enableThinking: false
}
};
var CHAT_TIMEOUT_MS = 3e5;
var LOAD_TIMEOUT_MS = 6e5;
var LIST_TIMEOUT_MS = 5e3;
var UNLOAD_TIMEOUT_MS = 15e3;
function normalizeLmApiRoot2(baseUrl) {
return String(baseUrl || "").trim().replace(/\/(api\/v1|v1)\/?$/i, "").replace(/\/+$/, "");
}
function authHeaders(apiKey, contentType = false) {
const headers = {};
if (contentType) headers["Content-Type"] = "application/json";
if (apiKey.trim()) headers.Authorization = `Bearer ${apiKey.trim()}`;
return headers;
}
function logLine(message) {
const line = `${requestLogPrefix()}[PromptUpsampler] ${message}`;
console.info(line);
try {
const logsDir2 = getLogsDir();
fs18.mkdirSync(logsDir2, { recursive: true });
fs18.appendFileSync(path17.join(logsDir2, getPluginLogFilename()), `${localTimestamp()} - ${line}
`, "utf8");
} catch (e) {
console.error("[PromptUpsampler] plugin log write failed:", e instanceof Error ? e.message : String(e));
}
}
var EndpointUnavailableError = class extends Error {
};
function describeNetworkError(error) {
const cause = error?.cause;
const parts = [cause?.code, cause?.message].filter((p, i, a) => typeof p === "string" && p && a.indexOf(p) === i);
return parts.length > 0 ? parts.join(": ") : String(error?.message || error);
}
var LM_STUDIO_DEFAULT_PORT = 1234;
var BIONIC_DEFAULT_PORT = 1235;
function swapLmDefaultPort(apiRoot) {
let url;
try {
url = new URL(apiRoot);
} catch {
return void 0;
}
if (url.port === String(LM_STUDIO_DEFAULT_PORT)) url.port = String(BIONIC_DEFAULT_PORT);
else if (url.port === String(BIONIC_DEFAULT_PORT)) url.port = String(LM_STUDIO_DEFAULT_PORT);
else return void 0;
return url.toString().replace(/\/+$/, "");
}
async function fetchJson(url, init, what) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), init.timeoutMs);
try {
let response;
try {
response = await fetch(url, {
method: init.method ?? "GET",
headers: init.headers,
body: init.body === void 0 ? void 0 : JSON.stringify(init.body),
signal: controller.signal
});
} catch (error) {
if (error?.name === "AbortError") throw error;
throw new EndpointUnavailableError(`${what} failed: could not reach ${url} (${describeNetworkError(error)})`);
}
const text = await response.text();
let data = null;
if (text.trim()) {
try {
data = JSON.parse(text);
} catch {
data = { raw: text };
}
}
const apiError = data?.error?.message || data?.error;
if (!response.ok || apiError) {
const detail = apiError || text || `${response.status} ${response.statusText}`;
throw new Error(`${what} failed (${response.status}): ${typeof detail === "string" ? detail : JSON.stringify(detail)}`);
}
return data;
} catch (error) {
if (error?.name === "AbortError") throw new Error(`${what} timed out after ${init.timeoutMs} ms`);
throw error;
} finally {
clearTimeout(timer);
}
}
function readPromptUpsamplerConfigFromEnv() {
const raw = process.env.LMSTUDIO_USE_PROMPT_UPSAMPLING;
if (raw !== "true" && raw !== "false") {
throw new Error(
`Prompt upsampling setting is missing: LMSTUDIO_USE_PROMPT_UPSAMPLING is ${raw === void 0 ? "not set" : `'${raw}'`} (expected 'true' or 'false'). The consumer must export 'usePromptUpsampling' to process.env.`
);
}
const apiRaw = (process.env.LMSTUDIO_VISION_API ?? "").trim().toLowerCase();
const api = apiRaw === "" ? "bionic" : PROMPT_UPSAMPLER_APIS.includes(apiRaw) ? apiRaw : void 0;
if (!api) {
throw new Error(`LMSTUDIO_VISION_API is '${apiRaw}' (expected one of: ${PROMPT_UPSAMPLER_APIS.join(", ")}).`);
}
const baseUrl = (process.env.LMSTUDIO_VISION_API_BASE_URL ?? "").trim();
const apiKey = process.env.LMSTUDIO_VISION_API_KEY ?? "";
const enabled = raw === "true";
if (enabled && api !== "llama-server" && !baseUrl) {
throw new Error("Prompt upsampling is enabled, but the prompt upsampling API base-URL (LMSTUDIO_VISION_API_BASE_URL) is empty.");
}
return { enabled, baseUrl, apiKey, api, ...enabled && api === "llama-server" ? { llamaServer: readLlamaServerSettingsFromEnv() } : {} };
}
function readLlamaServerSettingsFromEnv() {
const read = (name, min) => {
const raw = process.env[name];
if (raw === void 0 || !raw.trim()) {
throw new Error(`Prompt upsampling uses the 'llama-server' adapter, but ${name} is not set.`);
}
const value = Number(raw.trim());
if (!Number.isInteger(value) || value < min) {
throw new Error(`${name} must be an integer >= ${min}, got '${raw}'.`);
}
return value;
};
const binaryPath = (process.env.LMSTUDIO_LLAMA_SERVER_BINARY ?? "").trim();
if (!binaryPath) {
throw new Error("Prompt upsampling uses the 'llama-server' adapter, but LMSTUDIO_LLAMA_SERVER_BINARY is not set.");
}
return {
port: read("LMSTUDIO_LLAMA_SERVER_PORT", 1),
binaryPath,
ctxSize: read("LMSTUDIO_LLAMA_SERVER_CTX_SIZE", 1),
modelsMax: read("LMSTUDIO_LLAMA_SERVER_MODELS_MAX", 1),
idleTtlMinutes: read("LMSTUDIO_LLAMA_SERVER_IDLE_TTL_MINUTES", 0)
};
}
async function listModels(apiRoot, apiKey) {
const data = await fetchJson(
`${apiRoot}/api/v1/models`,
{ headers: authHeaders(apiKey), timeoutMs: LIST_TIMEOUT_MS },
"Listing models via /api/v1/models"
);
const models = Array.isArray(data) ? data : Array.isArray(data?.models) ? data.models : Array.isArray(data?.data) ? data.data : [];
return models.map((m) => ({
key: String(m?.key || m?.id || "").trim(),
loadedInstanceCount: Array.isArray(m?.loaded_instances) ? m.loaded_instances.length : 0
}));
}
var activeModels = /* @__PURE__ */ new Map();
async function resolveBionic(apiRoot, apiKey, family2, onProgress) {
const spec = PROMPT_UPSAMPLING_MODEL_FAMILIES[family2];
if (!spec) throw new Error(`Unknown prompt upsampling model family '${family2}'.`);
const listed = await listModels(apiRoot, apiKey);
const found = spec.knownModels.map((known) => listed.find((m) => m.key.toLowerCase() === known.toLowerCase())).find((m) => !!m);
if (!found) throw noModelError(family2, apiRoot, spec.knownModels);
if (found.loadedInstanceCount > 0) return { modelKey: found.key, apiRoot };
onProgress?.(-1, void 0, `Loading ${found.key}...`, "Prompt");
logLine(`loading '${found.key}' with context_length ${spec.contextLength}`);
const data = await fetchJson(
`${apiRoot}/api/v1/models/load`,
{
method: "POST",
headers: authHeaders(apiKey, true),
body: { model: found.key, context_length: spec.contextLength, echo_load_config: true },
timeoutMs: LOAD_TIMEOUT_MS
},
`Loading '${found.key}' via /api/v1/models/load`
);
const instanceId = typeof data?.instance_id === "string" ? data.instance_id.trim() : "";
if (!instanceId || typeof data?.status === "string" && data.status !== "loaded") {
throw new Error(`Loading '${found.key}' via /api/v1/models/load did not report a loaded model: ${JSON.stringify(data)}`);
}
logLine(`loaded '${found.key}' as '${instanceId}' (${data?.load_time_seconds ?? "?"} s)`);
return { modelKey: found.key, apiRoot, instanceId };
}
function modelBasename(key) {
const trimmed = key.trim();
const idx = trimmed.lastIndexOf("/");
return (idx >= 0 ? trimmed.slice(idx + 1) : trimmed).toLowerCase();
}
function stripQuantTag(id) {
return id.replace(/:[^/:]+$/, "");
}
function familyOrThrow(family2) {
const spec = PROMPT_UPSAMPLING_MODEL_FAMILIES[family2];
if (!spec) throw new Error(`Unknown prompt upsampling model family '${family2}'.`);
return spec;
}
function noModelError(family2, where, knownModels) {
return new EndpointUnavailableError(`No prompt upsampler model of family '${family2}' available at ${where} (known: ${knownModels.join(", ")}).`);
}
async function listOpenAiModelIds(apiRoot, apiKey) {
const data = await fetchJson(
`${apiRoot}/v1/models`,
{ headers: authHeaders(apiKey), timeoutMs: LIST_TIMEOUT_MS },
`Listing models via ${apiRoot}/v1/models`
);
const models = Array.isArray(data?.data) ? data.data : Array.isArray(data) ? data : [];
return models.map((m) => String(m?.id ?? m?.key ?? "").trim()).filter(Boolean);
}
async function resolveGeneric(apiRoot, apiKey, family2) {
const spec = familyOrThrow(family2);
const ids = await listOpenAiModelIds(apiRoot, apiKey);
const found = spec.knownModels.map((known) => ids.find((id) => modelBasename(id) === modelBasename(known))).find((id) => !!id);
if (!found) throw noModelError(family2, apiRoot, spec.knownModels);
return { modelKey: found, apiRoot };
}
async function unslothLoadedModels(apiRoot, apiKey) {
const data = await fetchJson(
`${apiRoot}/api/inference/status`,
{ headers: authHeaders(apiKey), timeoutMs: LIST_TIMEOUT_MS },
`Reading ${apiRoot}/api/inference/status`
);
return Array.isArray(data?.loaded) ? data.loaded.filter((entry) => typeof entry === "string") : [];
}
async function resolveUnsloth(apiRoot, apiKey, family2, onProgress) {
const spec = familyOrThrow(family2);
const loaded = new Set((await unslothLoadedModels(apiRoot, apiKey)).map(modelBasename));
const alreadyLoaded = spec.knownModels.find((known) => loaded.has(modelBasename(known)));
if (alreadyLoaded) return { modelKey: alreadyLoaded, apiRoot };
const failures = [];
for (const known of spec.knownModels) {
onProgress?.(-1, void 0, `Loading ${known}...`, "Prompt");
logLine(`loading '${known}' (${spec.ggufVariant}) with max_seq_length ${spec.contextLength}`);
try {
await fetchJson(
`${apiRoot}/api/inference/load`,
{
method: "POST",
headers: authHeaders(apiKey, true),
body: {
model_path: known,
gguf_variant: spec.ggufVariant,
max_seq_length: spec.contextLength,
alongside: true,
force_cancel_active: true
},
timeoutMs: LOAD_TIMEOUT_MS
},
`Loading '${known}' via /api/inference/load`
);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
logLine(`could not load '${known}': ${message}`);
failures.push(message);
continue;
}
const after = await unslothLoadedModels(apiRoot, apiKey);
if (!after.some((entry) => modelBasename(entry) === modelBasename(known))) {
const message = `'${known}' was loaded via /api/inference/load, but /api/inference/status does not report it as loaded.`;
logLine(message);
failures.push(message);
continue;
}
return { modelKey: known, apiRoot };
}
throw new Error(
`No prompt upsampler model of family '${family2}' could be loaded at ${apiRoot} (known: ${spec.knownModels.join(", ")}). ${failures.join(" | ")}`
);
}
async function resolveLlamaServer(config, family2) {
const spec = familyOrThrow(family2);
const settings = config.llamaServer;
if (!settings) throw new Error("The 'llama-server' adapter is active, but no llama-server settings were read.");
const host = "127.0.0.1";
await ensureLlamaServerRouterRunning({ host, ...settings });
const routerRoot = `http://${host}:${settings.port}`;
const ids = await listOpenAiModelIds(routerRoot, config.apiKey);
const found = spec.knownModels.map((known) => ids.find((id) => modelBasename(stripQuantTag(id)) === modelBasename(stripQuantTag(known)))).find((id) => !!id);
if (!found) throw noModelError(family2, routerRoot, spec.knownModels);
return { modelKey: found, apiRoot: routerRoot };
}
async function resolveWithPortFallback(apiRoot, resolve) {
try {
return await resolve(apiRoot);
} catch (primary) {
const altRoot = primary instanceof EndpointUnavailableError ? swapLmDefaultPort(apiRoot) : void 0;
if (!altRoot) throw primary;
try {
const lease = await resolve(altRoot);
logLine(`${apiRoot} was not usable (${primary.message}); using ${altRoot} instead`);
return lease;
} catch (alt) {
throw new Error(`${primary.message} | Fallback ${altRoot}: ${alt instanceof Error ? alt.message : String(alt)}`);
}
}
}
async function resolveModel(config, family2, onProgress) {
const apiRoot = normalizeLmApiRoot2(config.baseUrl);
switch (config.api) {
case "bionic":
return resolveWithPortFallback(apiRoot, (root) => resolveBionic(root, config.apiKey, family2, onProgress));
case "generic":
return resolveWithPortFallback(apiRoot, (root) => resolveGeneric(root, config.apiKey, family2));
case "unsloth":
return resolveUnsloth(apiRoot, config.apiKey, family2, onProgress);
case "llama-server":
return resolveLlamaServer(config, family2);
}
}
async function acquireModel(config, family2, onProgress) {
let entry = activeModels.get(family2);
if (!entry) {
entry = { count: 0, ready: resolveModel(config, family2, onProgress) };
activeModels.set(family2, entry);
}
entry.count++;
try {
return await entry.ready;
} catch (error) {
await releaseModel(config.apiKey, family2, void 0);
throw error;
}
}
async function releaseModel(apiKey, family2, lease) {
const entry = activeModels.get(family2);
if (!entry) return;
entry.count--;
if (entry.count > 0) return;
activeModels.delete(family2);
if (!lease?.instanceId) return;
try {
await fetchJson(
`${lease.apiRoot}/api/v1/models/unload`,
{ method: "POST", headers: authHeaders(apiKey, true), body: { instance_id: lease.instanceId }, timeoutMs: UNLOAD_TIMEOUT_MS },
`Unloading '${lease.instanceId}' via /api/v1/models/unload`
);
logLine(`unloaded '${lease.instanceId}'`);
} catch (error) {
logLine(`unload of '${lease.instanceId}' failed: ${error instanceof Error ? error.message : String(error)}`);
}
}
function mimeFromBuffer(buf) {
if (buf.length >= 3 && buf[0] === 255 && buf[1] === 216 && buf[2] === 255) return "image/jpeg";
if (buf.length >= 12 && buf.toString("ascii", 0, 4) === "RIFF" && buf.toString("ascii", 8, 12) === "WEBP") return "image/webp";
return "image/png";
}
function extractMessageText(data) {
const message = data?.choices?.[0]?.message;
const content = message?.content;
if (typeof content === "string" && content.trim()) return content;
if (Array.isArray(content)) {
const joined = content.map((p) => typeof p === "string" ? p : typeof p?.text === "string" ? p.text : "").join("");
if (joined.trim()) return joined;
}
const reasoning = message?.reasoning_content;
if (typeof reasoning === "string" && reasoning.trim()) {
logLine("response had empty content; using reasoning_content as the answer");
return reasoning;
}
return "";
}
async function applyPromptUpsampling(args) {
const caps = findImageModelCapabilitiesByFilename(args.effectiveModelFilename);
const upsampling = caps?.promptUpsampling;
if (!upsampling) return { applied: false };
if (args.referenceBuffers.length > upsampling.maxImages) {
throw new Error(
`Prompt upsampling accepts at most ${upsampling.maxImages} reference images, got ${args.referenceBuffers.length}.`
);
}
const config = readPromptUpsamplerConfigFromEnv();
if (!config.enabled) return { applied: false };
const boxes = (typeof args.boxes === "function" ? await args.boxes() : args.boxes) ?? [];
if (boxes.length > 0 && args.referenceBuffers.length === 0) {
throw new Error("Prompt upsampling with boxes needs the canvas as a reference image.");
}
const family2 = upsampling.promptUpsamplingModelFamily;
const familySpec = PROMPT_UPSAMPLER_FAMILY_SPECS[family2];
if (!familySpec) throw new Error(`No prompt upsampler request specification for model family '${family2}'.`);
const lease = await acquireModel(config, family2, args.onProgress);
try {
const imageParts = [];
const referenceImages = [];
const passes = [];
for (const [i, buf] of args.referenceBuffers.entries()) {
const { width, height } = await getSize(buf);
referenceImages.push({ width, height, bytes: buf.byteLength });
logLine(`reference ${i + 1}/${args.referenceBuffers.length}: ${width}x${height}, ${buf.byteLength} bytes`);
imageParts.push({ type: "image_url", image_url: { url: `data:${mimeFromBuffer(buf)};base64,${buf.toString("base64")}` } });
}
const infer = async (task, userContent, userText) => {
args.onProgress?.(-1, void 0, "Upsampling...", "Prompt");
logLine(`upsampling with '${lease.modelKey}' via ${config.api} task=${task} references=${args.referenceBuffers.length}`);
const startedAt = Date.now();
const data = await fetchJson(
`${lease.apiRoot}/v1/chat/completions`,
{
method: "POST",
headers: authHeaders(config.apiKey, true),
body: {
model: lease.modelKey,
messages: [
{ role: "system", content: familySpec.systemPrompts[task] },
{ role: "user", content: userContent }
],
...familySpec.sampling,
presence_penalty: familySpec.presencePenalty[task],
max_tokens: familySpec.maxTokens,
seed: familySpec.seed,
chat_template_kwargs: { enable_thinking: familySpec.enableThinking }
},
timeoutMs: CHAT_TIMEOUT_MS
},
`Prompt upsampling request to ${lease.apiRoot}/v1/chat/completions`
);
const ms = Date.now() - startedAt;
const finishReason = data?.choices?.[0]?.finish_reason;
if (finishReason === "length") {
throw new Error(`Prompt upsampling response was cut off at max_tokens (${familySpec.maxTokens}).`);
}
const text = extractMessageText(data).trim();
if (!text) {
throw new Error(
`Prompt upsampling model returned an empty response (finish_reason ${finishReason ?? "unknown"}, usage ${JSON.stringify(data?.usage ?? null)}).`
);
}
logLine(`upsampled prompt (${text.length} chars, ${ms} ms, usage ${JSON.stringify(data?.usage ?? null)})`);
passes.push({
task,
systemPromptSha256: createHash("sha256").update(familySpec.systemPrompts[task]).digest("hex"),
userText,
responseText: text,
inferenceMs: ms
});
return { text, ms };
};
let upsampled;
let inferenceMs;
let boxesInfo;
if (boxes.length > 0) {
const rows = buildPlainRows(boxes);
logLine(`boxes (${rows.length}, [y_min, x_min, y_max, x_max] on 0-1000): ${JSON.stringify(boxes)}`);
const boxText = familySpec.i2iBboxUserText(buildLockedInstruction(args.prompt, rows));
const content = [...imageParts, { type: "text", text: boxText }];
const boxed = await infer("i2i_bbox", content, boxText);
const reimposed = reimposeBoxes(boxed.text, boxes);
if (reimposed.ok) {
upsampled = reimposed.text;
inferenceMs = boxed.ms;
boxesInfo = { count: boxes.length, applied: true, regions: boxes.map((b) => [...b]) };
} else {
logLine(`box answer unusable (${reimposed.reason}); falling back to the plain i2i pass`);
const plainText = familySpec.i2iUserText(args.prompt);
const plain2 = await infer("i2i", [...imageParts, { type: "text", text: plainText }], plainText);
upsampled = plain2.text;
inferenceMs = boxed.ms + plain2.ms;
boxesInfo = { count: boxes.length, applied: false, fallbackReason: reimposed.reason, regions: boxes.map((b) => [...b]) };
}
} else {
const task = args.referenceBuffers.length > 0 ? "i2i" : "t2i";
const userText = task === "t2i" ? args.prompt : familySpec.i2iUserText(args.prompt);
const userContent = task === "t2i" ? args.prompt : [...imageParts, { type: "text", text: userText }];
const plain2 = await infer(task, userContent, userText);
upsampled = plain2.text;
inferenceMs = plain2.ms;
}
return {
applied: true,
prompt: upsampled,
originalPrompt: args.prompt,
model: lease.modelKey,
referenceCount: args.referenceBuffers.length,
inferenceMs,
referenceImages,
passes,
...boxesInfo ? { boxes: boxesInfo } : {}
};
} finally {
await releaseModel(config.apiKey, family2, lease);
}
}
// src/helpers/cameraImageMetadata.ts
var import_exifr = __toESM(require_full_umd(), 1);
import { readFile } from "node:fs/promises";
var EXIF_FIELDS = [
"DateTimeOriginal",
"CreateDate",
"ModifyDate",
"Make",
"Model",
"ImageWidth",
"ImageHeight",
"ExifImageWidth",
"ExifImageHeight",
"GPSLatitude",
"GPSLatitudeRef",
"GPSLongitude",
"GPSLongitudeRef",
"LensModel",
"ExposureTime",
"FNumber",
"ISO",
"ISOSpeedRatings",
"ExposureCompensation",
"FocalLength",
"FocalLengthIn35mmFormat",
"ExposureProgram",
"MeteringMode",
"WhiteBalance",
"Flash",
"Orientation",
"ExposureMode"
];
function nonEmptyString(value) {
return typeof value === "string" && value.trim() ? value.trim() : void 0;
}
function finitePositiveNumber(value) {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
}
function finiteNumber(value) {
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
}
function scalarString(value) {
if (typeof value === "string") return nonEmptyString(value);
if (typeof value === "number" && Number.isFinite(value)) return String(value);
return void 0;
}
function finiteCoordinate(value) {
return typeof value === "number" && Number.isFinite(value) && value >= -180 && value <= 180 ? value : void 0;
}
function decimalCoordinate(value, reference) {
const decimal = Array.isArray(value) ? value.length === 3 && value.every((part) => typeof part === "number" && Number.isFinite(part)) ? value[0] + value[1] / 60 + value[2] / 3600 : void 0 : finiteCoordinate(value);
if (decimal === void 0) return void 0;
const direction = nonEmptyString(reference)?.toUpperCase();
return direction === "S" || direction === "W" ? -decimal : decimal;
}
function isoTimestamp(value) {
if (!(value instanceof Date) || Number.isNaN(value.getTime())) return void 0;
return value.toISOString();
}
async function readCameraImageMetadata(input) {
try {
const bytes = typeof input === "string" ? await readFile(input) : input;
const fields = await import_exifr.default.parse(bytes, { pick: EXIF_FIELDS });
if (!fields) return {};
const make = nonEmptyString(fields.Make);
const model = nonEmptyString(fields.Model);
const camera = [make, model].filter((value, index2, values) => value && values.indexOf(value) === index2).join(" ") || void 0;
return {
capturedAt: isoTimestamp(fields.DateTimeOriginal) ?? isoTimestamp(fields.CreateDate) ?? isoTimestamp(fields.ModifyDate),
camera,
width: finitePositiveNumber(fields.ExifImageWidth) ?? finitePositiveNumber(fields.ImageWidth),
height: finitePositiveNumber(fields.ExifImageHeight) ?? finitePositiveNumber(fields.ImageHeight),
latitude: decimalCoordinate(fields.GPSLatitude, fields.GPSLatitudeRef),
longitude: decimalCoordinate(fields.GPSLongitude, fields.GPSLongitudeRef),
lensModel: nonEmptyString(fields.LensModel),
exposureTime: scalarString(fields.ExposureTime),
fNumber: finitePositiveNumber(fields.FNumber),
iso: finitePositiveNumber(fields.ISO) ?? finitePositiveNumber(fields.ISOSpeedRatings),
exposureCompensation: finiteNumber(fields.ExposureCompensation),
focalLength: finitePositiveNumber(fields.FocalLength),
focalLength35mm: finitePositiveNumber(fields.FocalLengthIn35mmFormat),
exposureProgram: scalarString(fields.ExposureProgram),
meteringMode: scalarString(fields.MeteringMode),
whiteBalance: scalarString(fields.WhiteBalance),
flash: scalarString(fields.Flash),
orientation: scalarString(fields.Orientation),
exposureMode: scalarString(fields.ExposureMode)
};
} catch {
return {};
}
}
// src/helpers/drawThingsGrpcAssetCheck.ts
import path18 from "node:path";
function normBasename(file) {
return path18.basename(String(file || "").trim());
}
function uniqNonEmptyBasenames(files) {
const seen = /* @__PURE__ */ new Set();
const out = [];
for (const f of files) {
if (!f) continue;
const b = normBasename(f);
if (!b) continue;
if (seen.has(b)) continue;
seen.add(b);
out.push(b);
}
return out;
}
function decodeJsonBytes2(buffer) {
if (!buffer) return [];
try {
const b = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer);
if (!b.length) return [];
const txt = b.toString("utf8");
const parsed = JSON.parse(txt);
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function extractFileLikeStrings(items) {
const out = [];
for (const it of items) {
if (!it || typeof it !== "object") continue;
for (const key of ["file", "filename", "name", "path"]) {
const v = it[key];
if (typeof v === "string" && v.trim()) out.push(v);
}
}
return out;
}
function buildMissingDetails({
modelFile,
missingModel,
missingLoras,
hintModels,
hintLoras
}) {
const parts = [];
parts.push("Draw Things gRPC: requested assets not found on server.");
if (missingModel) {
parts.push(`Missing model: ${missingModel}`);
}
if (missingLoras && missingLoras.length) {
parts.push(`Missing LoRA(s): ${missingLoras.join(", ")}`);
}
parts.push(
"The Draw Things gRPC server may silently fall back to a different model/without LoRA; generation was aborted to avoid producing misleading output."
);
if (hintModels && hintModels.length) {
parts.push(`Available model files (sample): ${hintModels.join(", ")}`);
}
if (hintLoras && hintLoras.length) {
parts.push(`Available LoRA files (sample): ${hintLoras.join(", ")}`);
}
if (modelFile) {
parts.push(
"Fix: copy the missing .ckpt into the server's model/LoRA directories (or adjust the requested filenames)."
);
}
return parts.join("\n");
}
async function filesExist(client, files, sharedSecret) {
try {
const fn = client?.filesExist?.bind(client);
if (typeof fn !== "function") return null;
return await new Promise((resolve, reject) => {
const req = { files, filesWithHash: [] };
if (sharedSecret) req.sharedSecret = sharedSecret;
fn(req, (err, resp) => {
if (err) return reject(err);
const existArr = Array.isArray(resp?.existences) ? resp.existences : [];
resolve(existArr.slice(0, files.length));
});
});
} catch {
return null;
}
}
async function checkDrawThingsGrpcFilesExist(input) {
const checked = uniqNonEmptyBasenames(input.files || []);
if (checked.length === 0) {
return { ok: true, checked: [], missing: [], usedFilesExist: true };
}
const existArr = await filesExist(input.client, checked, input.sharedSecret);
if (!existArr) {
return { ok: true, checked, missing: [], usedFilesExist: false };
}
const missing = [];
for (let i = 0; i < checked.length; i++) {
if (existArr[i] !== true) missing.push(checked[i]);
}
return {
ok: missing.length === 0,
checked,
missing,
usedFilesExist: true
};
}
async function tryBrowseViaEcho(client, sharedSecret) {
try {
const echo = client?.echo?.bind(client);
if (typeof echo !== "function") return null;
const req = { name: "generate-image-plugin" };
if (sharedSecret) req.sharedSecret = sharedSecret;
const reply = await new Promise((resolve, reject) => {
echo(req, (err, resp) => err ? reject(err) : resolve(resp));
});
const modelFiles = uniqNonEmptyBasenames(
Array.isArray(reply?.files) ? reply.files : []
);
const ov = reply?.override || {};
const lorasJson = decodeJsonBytes2(ov?.loras);
const modelsJson = decodeJsonBytes2(ov?.models);
const loraFiles2 = uniqNonEmptyBasenames(extractFileLikeStrings(lorasJson));
const modelFilesFromJson = uniqNonEmptyBasenames(
extractFileLikeStrings(modelsJson)
);
return {
modelFiles: uniqNonEmptyBasenames([...modelFiles, ...modelFilesFromJson]),
loraFiles: loraFiles2
};
} catch {
return null;
}
}
function pickSample(list, limit) {
if (!list.length) return [];
return list.slice(0, Math.max(0, limit));
}
async function checkDrawThingsGrpcAssets(req) {
const requestedModel = req.modelFile ? normBasename(req.modelFile) : "";
const requestedLoras = uniqNonEmptyBasenames(req.loraFiles || []);
if (!requestedModel && requestedLoras.length === 0) return { ok: true };
const filesToCheck = uniqNonEmptyBasenames([
requestedModel || void 0,
...requestedLoras
]);
const existArr = await filesExist(req.client, filesToCheck, req.sharedSecret);
if (existArr) {
const missing = [];
for (let i = 0; i < filesToCheck.length; i++) {
if (existArr[i] !== true) missing.push(filesToCheck[i]);
}
if (missing.length === 0) return { ok: true };
const missingModel2 = requestedModel && missing.includes(requestedModel) ? requestedModel : void 0;
const missingLoras2 = requestedLoras.filter((x) => missing.includes(x));
return {
ok: false,
missingModel: missingModel2,
missingLoras: missingLoras2.length ? missingLoras2 : void 0,
details: buildMissingDetails({
modelFile: requestedModel || void 0,
missingModel: missingModel2,
missingLoras: missingLoras2
})
};
}
const browse = await tryBrowseViaEcho(req.client, req.sharedSecret);
if (!browse) {
return { ok: true };
}
const missingModel = requestedModel && !browse.modelFiles.includes(requestedModel) ? requestedModel : void 0;
const missingLoras = requestedLoras.filter(
(x) => !browse.loraFiles.includes(x)
);
if (!missingModel && missingLoras.length === 0) return { ok: true };
return {
ok: false,
missingModel,
missingLoras: missingLoras.length ? missingLoras : void 0,
details: buildMissingDetails({
modelFile: requestedModel || void 0,
missingModel,
missingLoras,
hintModels: pickSample(browse.modelFiles, 12),
hintLoras: pickSample(browse.loraFiles, 12)
})
};
}
// src/helpers/httpServer.ts
import http from "http";
import fs19 from "fs";
import path19 from "path";
var DEFAULT_HOST = "127.0.0.1";
function envPort() {
const v = process.env.HTTP_SERVER_PORT;
if (v == null || String(v).trim() === "") return void 0;
const n = Number(v);
return Number.isInteger(n) && n >= 1024 && n <= 65535 ? n : void 0;
}
async function healthCheck(port, host = DEFAULT_HOST) {
return new Promise((resolve) => {
const req = http.get(
{ host, port, path: "/__healthz", timeout: 600 },
(res) => {
try {
const ok = (res.statusCode || 0) === 200 && String(res.headers["x-mcp-image-server"]) === "1";
res.resume();
res.once("end", () => resolve(ok));
} catch {
resolve(false);
}
}
);
req.on("timeout", () => {
try {
req.destroy();
} catch {
}
resolve(false);
});
req.on("error", () => resolve(false));
});
}
function toHttpOriginalUrl(fileName, baseUrl, chatId) {
if (chatId) {
return `${baseUrl.replace(/\/$/, "")}/${encodeURIComponent(
chatId
)}/${encodeURIComponent(fileName)}`;
}
return `${baseUrl.replace(/\/$/, "")}/${encodeURIComponent(fileName)}`;
}
function toHttpPreviewUrl(fileName, baseUrl, chatId) {
if (chatId) {
return `${baseUrl.replace(/\/$/, "")}/${encodeURIComponent(
chatId
)}/${encodeURIComponent(fileName)}`;
}
return `${baseUrl.replace(/\/$/, "")}/previews/${encodeURIComponent(
fileName
)}`;
}
async function getHealthyServerBaseUrl(host = DEFAULT_HOST) {
try {
const fixedPort = envPort();
if (fixedPort == null) return "";
const ok = await healthCheck(fixedPort, host).catch(() => false);
if (ok) return `http://127.0.0.1:${fixedPort}`;
return "";
} catch {
return "";
}
}
async function isHttpServerHealthy(host = DEFAULT_HOST) {
try {
const fixedPort = envPort();
if (fixedPort == null) return false;
const ok = await healthCheck(fixedPort, host).catch(() => false);
return !!ok;
} catch {
return false;
}
}
// src/helpers/toolLog.ts
import fs20 from "fs";
import path20 from "path";
var DEBUG_MODE = true;
var logsDir = () => getLogsDir();
var logFile = () => path20.join(logsDir(), getPluginLogFilename());
function log(message) {
const timestamp = logTimestamp();
const line = `${timestamp} - ${requestLogPrefix()}${message}
`;
try {
const dir = path20.dirname(logFile());
if (!fs20.existsSync(dir)) fs20.mkdirSync(dir, { recursive: true });
fs20.appendFileSync(logFile(), line);
} catch {
}
console.log(line.trim());
}
async function logError(error) {
try {
const errorLogFile = path20.join(logsDir(), "error.log");
await fs20.promises.mkdir(logsDir(), { recursive: true }).catch(() => {
});
const timestamp = logTimestamp();
const details = error instanceof Error ? `${error.message}
${error.stack}` : String(error);
const block = `${timestamp} - ERROR:
${details}
`;
await fs20.promises.appendFile(errorLogFile, block);
if (DEBUG_MODE) console.error(block);
} catch {
}
}
async function appendErrorRaw(raw, status) {
try {
const errorLogFile = path20.join(logsDir(), "error.log");
await fs20.promises.mkdir(logsDir(), { recursive: true }).catch(() => {
});
const timestamp = logTimestamp();
const header = typeof status === "number" ? `BACKEND RAW (status ${status})` : "BACKEND RAW";
const block = `${timestamp} - ${header}:
${raw}
`;
await fs20.promises.appendFile(errorLogFile, block);
} catch {
}
}
// src/helpers/generationToolCommon.ts
import fs21 from "fs";
import path21 from "path";
import { pathToFileURL } from "url";
var ALLOWED_GEN_INPUT_KEYS = [
"prompt",
"width",
"height",
"imageFormat",
"variants",
"canvas",
"moodboard"
];
function stripInternalToolKeys(obj) {
if (!obj || typeof obj !== "object") return {};
const out = {};
for (const [k, v] of Object.entries(obj)) {
if (k.startsWith("_")) continue;
out[k] = v;
}
return out;
}
function normalizeSourceNotation(s) {
let t = String(s || "").trim().toLowerCase();
if (t === "a") t = "a1";
if (t === "v") t = "v1";
if (t === "p") t = "p1";
if (t === "i") t = "i1";
return t;
}
function parsePrefixedNotation(s) {
const t = normalizeSourceNotation(s);
const m = t.match(/^([avpi])\s*(\d+)$/);
if (!m) return null;
const idx = Math.max(1, parseInt(m[2], 10));
const pool = m[1] === "a" ? "attachment" : m[1] === "v" ? "variant" : m[1] === "i" ? "image" : "picture";
return { pool, index: idx };
}
function parseDigitOnlyNotation(s) {
const t = String(s || "").trim();
const m = t.match(/^(\d+)$/);
if (!m) return null;
return Math.max(1, parseInt(m[1], 10));
}
function encodeFileUrl(abs) {
return pathToFileURL(abs).toString();
}
function isoStamp() {
return (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
}
function getCurrentConnectionSettings() {
return getEngineConnectionDefaults({
host: process.env.DRAW_THINGS_HOST,
httpPort: process.env.DRAW_THINGS_HTTP_PORT ? parseInt(process.env.DRAW_THINGS_HTTP_PORT, 10) : void 0,
grpcPort: process.env.DRAW_THINGS_GRPC_PORT ? parseInt(process.env.DRAW_THINGS_GRPC_PORT, 10) : void 0
});
}
async function getLMConversationFilePath(chatId) {
try {
const home = findLMStudioHome();
const convDir = path21.join(home, "conversations");
if (!fs21.existsSync(convDir)) return null;
if (chatId) {
const p = path21.join(convDir, `${chatId}.conversation.json`);
return await fs21.promises.stat(p).then((s) => s.isFile() ? p : null).catch(() => null);
}
const entries = await fs21.promises.readdir(convDir).catch(() => []);
const convFiles = entries.filter((f) => f.endsWith(".conversation.json")).map((f) => path21.join(convDir, f));
if (convFiles.length === 0) return null;
const withTimes = (await Promise.all(
convFiles.map(async (p) => {
try {
const s = await fs21.promises.stat(p);
return s.isFile() ? { p, t: s.mtimeMs } : null;
} catch {
return null;
}
})
)).filter(Boolean);
if (withTimes.length === 0) return null;
withTimes.sort((a, b) => b.t - a.t);
return withTimes[0].p;
} catch {
return null;
}
}
function isSupportedImageBuffer(buf) {
if (!buf || buf.length < 12) return false;
if (buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71 && buf[4] === 13 && buf[5] === 10 && buf[6] === 26 && buf[7] === 10)
return true;
if (buf[0] === 255 && buf[1] === 216) return true;
if (buf[0] === 82 && buf[1] === 73 && buf[2] === 70 && buf[3] === 70 && buf[8] === 87 && buf[9] === 69 && buf[10] === 66 && buf[11] === 80)
return true;
return false;
}
function createSaveOriginalPng(injectXmpIntoBuffer2) {
return async function saveOriginalPng(sourceBuffer, preferredDir, preferredFileName, xmpParams) {
if (!preferredDir) {
throw new Error(
"No output directory resolved (LM Studio chat working directory missing)."
);
}
const dir = path21.resolve(preferredDir);
await fs21.promises.mkdir(dir, { recursive: true });
const name = preferredFileName && preferredFileName.endsWith(".png") ? preferredFileName : preferredFileName ? `${preferredFileName}.png` : `generated-image-${tsForFilename()}.png`;
const abs = path21.join(dir, name);
const embedMeta = xmpParams != null && /^(1|true|yes)$/i.test(String(process.env.EMBED_PNG_METADATA ?? "true").trim());
try {
if (!isSupportedImageBuffer(sourceBuffer)) {
const binName = name.replace(/\.png$/i, ".bin");
const binAbs = path21.join(dir, binName);
await fs21.promises.writeFile(binAbs, sourceBuffer);
const stat2 = await fs21.promises.stat(binAbs);
return {
savedPath: binAbs,
fileName: binName,
size: stat2.size,
mimeType: "application/octet-stream",
fileUrl: encodeFileUrl(binAbs)
};
}
let pngBuf;
if (isPng(sourceBuffer)) {
pngBuf = sourceBuffer;
} else {
pngBuf = await toPng(sourceBuffer);
}
if (embedMeta) {
pngBuf = injectXmpIntoBuffer2(pngBuf, xmpParams);
}
await fs21.promises.writeFile(abs, pngBuf);
} catch {
await fs21.promises.writeFile(abs, sourceBuffer);
}
const stat = await fs21.promises.stat(abs);
return {
savedPath: abs,
fileName: name,
size: stat.size,
mimeType: "image/png",
fileUrl: encodeFileUrl(abs)
};
};
}
async function normalizeInputBuffer(buf, opts) {
const prefix = opts?.logPrefix || "[normalize]";
const size = await getSize(buf);
let w = size.width || 0;
let h = size.height || 0;
const align = drawthingsLimits.align;
const minDim = drawthingsLimits.minDim;
const targetSum = opts?.targetSumOverride ?? drawthingsLimits.targetSum;
const origW = w;
const origH = h;
const origFmt = isPng(buf) ? "png" : void 0;
const origBytes = buf.byteLength;
let reason = "unchanged";
const hasReqW = typeof opts?.requestedRawW === "number" && Number.isFinite(opts.requestedRawW) && opts.requestedRawW > 0;
const hasReqH = typeof opts?.requestedRawH === "number" && Number.isFinite(opts.requestedRawH) && opts.requestedRawH > 0;
if (hasReqW && hasReqH) {
w = opts.requestedRawW;
h = opts.requestedRawH;
reason = "clamped_to_requested_raw";
log(`${prefix} adopting target dimensions: ${origW}x${origH} \u2192 ${w}x${h}`);
}
const currentSum = w + h;
if (!opts?.skipSumConstraint && currentSum > targetSum) {
const aspect = w / Math.max(1, h);
const rawH = targetSum / (aspect + 1);
const rawW = aspect * rawH;
const wFloor = Math.max(align, Math.floor(rawW / align) * align);
const wRound = Math.max(align, Math.round(rawW / align) * align);
const wCeil = Math.max(align, Math.ceil(rawW / align) * align);
const hFloor = Math.max(align, Math.floor(rawH / align) * align);
const hRound = Math.max(align, Math.round(rawH / align) * align);
const hCeil = Math.max(align, Math.ceil(rawH / align) * align);
const sumCandidates = [];
for (const cw of [wFloor, wRound, wCeil]) {
for (const ch of [hFloor, hRound, hCeil]) {
if (cw + ch <= targetSum) sumCandidates.push({ cw, ch });
}
}
for (const cw of [wFloor, wRound]) {
const ch = Math.max(align, Math.round(cw / aspect / align) * align);
if (cw + ch <= targetSum) sumCandidates.push({ cw, ch });
}
for (const ch of [hFloor, hRound]) {
const cw = Math.max(align, Math.round(ch * aspect / align) * align);
if (cw + ch <= targetSum) sumCandidates.push({ cw, ch });
}
if (sumCandidates.length > 0) {
sumCandidates.sort((a, b) => {
const ae = Math.abs(a.cw / Math.max(1, a.ch) - aspect);
const be = Math.abs(b.cw / Math.max(1, b.ch) - aspect);
if (ae !== be) return ae - be;
return Math.abs(a.cw - rawW) + Math.abs(a.ch - rawH) - (Math.abs(b.cw - rawW) + Math.abs(b.ch - rawH));
});
w = sumCandidates[0].cw;
h = sumCandidates[0].ch;
} else {
let fbW = wFloor;
let fbH = hFloor;
while (fbW + fbH > targetSum && (fbW > align || fbH > align)) {
if (fbW >= fbH) fbW = Math.max(align, fbW - align);
else fbH = Math.max(align, fbH - align);
}
w = fbW;
h = fbH;
}
if (reason === "unchanged") reason = "normalized_to_constraints";
}
if (w % align !== 0 || h % align !== 0) {
const aspect = w / Math.max(1, h);
const wFloor = Math.max(align, Math.floor(w / align) * align);
const wRound = Math.max(align, Math.round(w / align) * align);
const hFloor = Math.max(align, Math.floor(h / align) * align);
const hRound = Math.max(align, Math.round(h / align) * align);
const candidates = [
{ cw: wFloor, ch: hFloor },
{ cw: wFloor, ch: hRound },
{ cw: wRound, ch: hFloor },
{ cw: wRound, ch: hRound }
];
for (const wBase of [wFloor, wRound]) {
const hDerived = Math.max(align, Math.round(wBase / aspect / align) * align);
candidates.push({ cw: wBase, ch: hDerived });
}
for (const hBase of [hFloor, hRound]) {
const wDerived = Math.max(align, Math.round(hBase * aspect / align) * align);
candidates.push({ cw: wDerived, ch: hBase });
}
const valid = candidates.filter(
(c) => c.cw >= align && c.ch >= align && c.cw + c.ch <= targetSum
);
if (valid.length > 0) {
valid.sort((a, b) => {
const ae = Math.abs(a.cw / Math.max(1, a.ch) - aspect);
const be = Math.abs(b.cw / Math.max(1, b.ch) - aspect);
if (ae !== be) return ae - be;
const ad = Math.abs(a.cw - w) + Math.abs(a.ch - h);
const bd = Math.abs(b.cw - w) + Math.abs(b.ch - h);
return ad - bd;
});
w = valid[0].cw;
h = valid[0].ch;
} else {
w = Math.max(align, Math.floor(w / align) * align);
h = Math.max(align, Math.floor(h / align) * align);
}
if (reason === "unchanged") reason = "normalized_to_constraints";
}
if (w < minDim || h < minDim) {
const scale = minDim / Math.min(w, h);
w = Math.round(w * scale);
h = Math.round(h * scale);
w = Math.max(align, Math.floor(w / align) * align);
h = Math.max(align, Math.floor(h / align) * align);
while (w + h > targetSum && (w > minDim || h > minDim)) {
if (w > h) w = Math.max(minDim, w - align);
else h = Math.max(minDim, h - align);
}
if (reason === "unchanged") reason = "normalized_to_constraints";
}
let outBuf;
if (w !== origW || h !== origH) {
outBuf = await resizeCoverToPng(buf, w, h);
if (reason === "unchanged") reason = "normalized_to_constraints";
log(
`${prefix} dimension normalization: ${origW}x${origH} \u2192 ${w}x${h} (sum=${w + h})`
);
} else {
if (isPng(buf)) {
outBuf = buf;
} else {
outBuf = await toPng(buf);
if (reason === "unchanged") reason = "converted_to_png";
}
}
return {
buf: outBuf,
preprocess: {
original: {
width: origW,
height: origH,
format: origFmt,
bytes: origBytes
},
adjusted: {
width: w,
height: h,
format: "png",
bytes: outBuf.byteLength
},
reason
},
normalizedLongSide: w !== origW || h !== origH ? Math.max(w, h) : void 0
};
}
// src/helpers/injectionMarker.ts
var injectedRegistry = /* @__PURE__ */ new Map();
function stripKnownMarkdownInjections(text) {
if (!text) return text;
const lines = text.split(/\r?\n/);
const outLines = [];
const injectedImageLine = /^!\[(Image Variant v\d+|Image i\d+)\]\(\.(?:\/)?(preview-[^)\s]+\.(?:jpg|jpeg|webp|png)|generated-image-[^)\s]+\.(?:png|jpg|jpeg|webp))\)\s*$/i;
for (const line of lines) {
if (injectedImageLine.test(line.trim())) continue;
outLines.push(line);
}
let s = outLines.join("\n");
const kept = [];
const ls = s.split(/\r?\n/);
for (let i = 0; i < ls.length; i++) {
const line = ls[i];
const header = line.trim();
const isOurHeader = header === "| Preview | ID / Title | Source |" || header === "| Preview | ID / Title | Source |" || header === "| Preview | ID / Generation Data |" || header === "| Index Image Results |";
if (!isOurHeader) {
kept.push(line);
continue;
}
const sep = (ls[i + 1] ?? "").trim();
const isSeparator = /^\|[-\s|]+\|$/.test(sep) || sep === "|---|---|---|" || sep === "|---|---|" || sep === "|---|";
if (!isSeparator) {
kept.push(line);
continue;
}
let j = i + 2;
let sawImageCell = false;
for (; j < ls.length; j++) {
const row = ls[j];
const t = row.trim();
if (!t.startsWith("|") || !t.endsWith("|")) break;
if (t.includes(") sawImageCell = true;
}
if (sawImageCell) {
i = j - 1;
continue;
}
kept.push(line);
}
return kept.join("\n");
}
function trackInjection(chatId, markdown, _mediaType) {
if (!chatId || !markdown) return;
let set = injectedRegistry.get(chatId);
if (!set) {
set = /* @__PURE__ */ new Set();
injectedRegistry.set(chatId, set);
}
set.add(markdown);
}
function stripInjections(chatId, text) {
if (!chatId || !text) return text;
const set = injectedRegistry.get(chatId);
if (!set || set.size === 0) return text;
let result = text;
for (const injection of set) {
result = result.split(injection + "\n").join("");
result = result.split(injection).join("");
}
result = stripKnownMarkdownInjections(result);
return result.trim();
}
function hasTrackedInjections(chatId) {
const set = injectedRegistry.get(chatId);
return !!set && set.size > 0;
}
function clearInjections(chatId) {
injectedRegistry.delete(chatId);
}
function getInjectionCount(chatId) {
return injectedRegistry.get(chatId)?.size ?? 0;
}
var INJECTION_START = "";
var INJECTION_END = "";
function wrapInjection(markdown, _mediaType) {
return markdown;
}
function hasInjections(_text) {
return false;
}
// src/helpers/maskColorDrift.ts
var DEFAULTS = {
sigmaSpatial: 30,
sigmaColor: 8,
tau: 14,
margin: 3,
cap: 8,
confidenceWeight: 4,
downscale: 2,
maxSamples: 3e3,
minSamples: 150
};
var MAX_ESTIMATE_CELLS = 12e4;
var SRGB_TO_LINEAR = (() => {
const lut = new Float32Array(256);
for (let i = 0; i < 256; i++) {
const c = i / 255;
lut[i] = c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
}
return lut;
})();
var XN = 0.95047;
var ZN = 1.08883;
var LAB_EPS = 216 / 24389;
var LAB_KAPPA = 24389 / 27;
function labF(t) {
return t > LAB_EPS ? Math.cbrt(t) : (LAB_KAPPA * t + 16) / 116;
}
function labFInv(t) {
const t3 = t * t * t;
return t3 > LAB_EPS ? t3 : (116 * t - 16) / LAB_KAPPA;
}
function rgbToLab(r, g, b, out, o) {
const lr = SRGB_TO_LINEAR[r];
const lg = SRGB_TO_LINEAR[g];
const lb = SRGB_TO_LINEAR[b];
const x = (0.4124564 * lr + 0.3575761 * lg + 0.1804375 * lb) / XN;
const y = 0.2126729 * lr + 0.7151522 * lg + 0.072175 * lb;
const z4 = (0.0193339 * lr + 0.119192 * lg + 0.9503041 * lb) / ZN;
const fx = labF(x);
const fy = labF(y);
const fz = labF(z4);
out[o] = 116 * fy - 16;
out[o + 1] = 500 * (fx - fy);
out[o + 2] = 200 * (fy - fz);
}
function encodeSrgb(linear) {
const c = Math.min(1, Math.max(0, linear));
const v = c <= 31308e-7 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
return Math.round(v * 255);
}
function labToRgb(l, a, b, out, o) {
const fy = (l + 16) / 116;
const fx = fy + a / 500;
const fz = fy - b / 200;
const x = labFInv(fx) * XN;
const y = labFInv(fy);
const z4 = labFInv(fz) * ZN;
out[o] = encodeSrgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z4);
out[o + 1] = encodeSrgb(-0.969266 * x + 1.8760108 * y + 0.041556 * z4);
out[o + 2] = encodeSrgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z4);
}
function erode(binary, w, h, radius) {
if (radius <= 0) return binary;
const tmp = new Uint8Array(w * h);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
let v = 1;
for (let k = -radius; k <= radius && v; k++) {
const xx = x + k;
if (xx < 0 || xx >= w || !binary[y * w + xx]) v = 0;
}
tmp[y * w + x] = v;
}
}
const out = new Uint8Array(w * h);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
let v = 1;
for (let k = -radius; k <= radius && v; k++) {
const yy = y + k;
if (yy < 0 || yy >= h || !tmp[yy * w + x]) v = 0;
}
out[y * w + x] = v;
}
}
return out;
}
function correctMaskColorDrift(original, result, mask, options = {}) {
const opt = { ...DEFAULTS, ...options };
const { width: W, height: H } = result;
if (original.width !== W || original.height !== H) {
throw new Error(`original ${original.width}x${original.height} and result ${W}x${H} differ in size`);
}
if (mask.length < W * H) throw new Error(`mask has ${mask.length} entries, expected ${W * H}`);
const out = new Uint8Array(result.data);
const unchanged = { data: out, applied: false, samples: 0, meanOffsetLab: [0, 0, 0], maxCorrectionDE: 0 };
let x0 = W;
let y0 = H;
let x1 = -1;
let y1 = -1;
for (let y = 0; y < H; y++) {
for (let x = 0; x < W; x++) {
if (mask[y * W + x] > 1e-3) {
if (x < x0) x0 = x;
if (x > x1) x1 = x;
if (y < y0) y0 = y;
if (y > y1) y1 = y;
}
}
}
if (x1 < 0) return unchanged;
x0 = Math.max(0, x0 - 2);
y0 = Math.max(0, y0 - 2);
x1 = Math.min(W - 1, x1 + 2);
y1 = Math.min(H - 1, y1 + 2);
const rw = x1 - x0 + 1;
const rh = y1 - y0 + 1;
const labO = new Float32Array(rw * rh * 3);
const labR = new Float32Array(rw * rh * 3);
const m = new Float32Array(rw * rh);
const full = new Uint8Array(rw * rh);
for (let y = 0; y < rh; y++) {
for (let x = 0; x < rw; x++) {
const i = y * rw + x;
const src = ((y0 + y) * W + (x0 + x)) * result.channels;
const srcO = ((y0 + y) * W + (x0 + x)) * original.channels;
rgbToLab(original.data[srcO], original.data[srcO + 1], original.data[srcO + 2], labO, i * 3);
rgbToLab(result.data[src], result.data[src + 1], result.data[src + 2], labR, i * 3);
const mv = mask[(y0 + y) * W + (x0 + x)];
m[i] = mv;
full[i] = mv >= 0.999 ? 1 : 0;
}
}
const inner = erode(full, rw, rh, opt.margin);
const s = Math.max(1, Math.round(opt.downscale), Math.ceil(Math.sqrt(rw * rh / MAX_ESTIMATE_CELLS)));
const lw = Math.ceil(rw / s);
const lh = Math.ceil(rh / s);
const loR = new Float32Array(lw * lh * 3);
const loO = new Float32Array(lw * lh * 3);
const loM = new Float32Array(lw * lh);
const loInner = new Uint8Array(lw * lh);
for (let ly = 0; ly < lh; ly++) {
for (let lx = 0; lx < lw; lx++) {
let n = 0;
let allInner = 1;
const acc = [0, 0, 0, 0, 0, 0];
let mm = 0;
for (let dy = 0; dy < s; dy++) {
const y = ly * s + dy;
if (y >= rh) break;
for (let dx = 0; dx < s; dx++) {
const x = lx * s + dx;
if (x >= rw) break;
const i = y * rw + x;
n++;
for (let c = 0; c < 3; c++) {
acc[c] += labR[i * 3 + c];
acc[3 + c] += labO[i * 3 + c];
}
mm += m[i];
if (!inner[i]) allInner = 0;
}
}
const j = ly * lw + lx;
for (let c = 0; c < 3; c++) {
loR[j * 3 + c] = acc[c] / n;
loO[j * 3 + c] = acc[3 + c] / n;
}
loM[j] = mm / n;
loInner[j] = allInner;
}
}
const evidence = [];
for (let j = 0; j < lw * lh; j++) {
if (!loInner[j]) continue;
const dl = loR[j * 3] - loO[j * 3];
const da = loR[j * 3 + 1] - loO[j * 3 + 1];
const db = loR[j * 3 + 2] - loO[j * 3 + 2];
if (Math.sqrt(dl * dl + da * da + db * db) < opt.tau) evidence.push(j);
}
const total = evidence.length;
if (total < opt.minSamples) return { ...unchanged, samples: total };
const grid = Math.max(1, Math.ceil(Math.sqrt(total / opt.maxSamples)));
const sampleIdx = [];
for (const j of evidence) {
if (j % lw % grid === 0 && Math.floor(j / lw) % grid === 0) sampleIdx.push(j);
}
const ns = sampleIdx.length;
const sx = new Float32Array(ns);
const sy = new Float32Array(ns);
const sCol = new Float32Array(ns * 3);
const sOff = new Float32Array(ns * 3);
const mean = [0, 0, 0];
for (let k = 0; k < ns; k++) {
const j = sampleIdx[k];
sx[k] = j % lw;
sy[k] = Math.floor(j / lw);
for (let c = 0; c < 3; c++) {
sCol[k * 3 + c] = loR[j * 3 + c];
sOff[k * 3 + c] = loR[j * 3 + c] - loO[j * 3 + c];
mean[c] += sOff[k * 3 + c] / ns;
}
}
const sigS = opt.sigmaSpatial / s;
const invS2 = 1 / (sigS * sigS);
const invC2 = 1 / (opt.sigmaColor * opt.sigmaColor);
const reach2 = 9 * sigS * sigS;
const corr = new Float32Array(lw * lh * 3);
for (let ly = 0; ly < lh; ly++) {
for (let lx = 0; lx < lw; lx++) {
const j = ly * lw + lx;
if (loM[j] <= 0) continue;
const pl = loR[j * 3];
const pa = loR[j * 3 + 1];
const pb = loR[j * 3 + 2];
let den = 0;
let n0 = 0;
let n1 = 0;
let n2 = 0;
for (let k = 0; k < ns; k++) {
const ddx = lx - sx[k];
const ddy = ly - sy[k];
const d2 = ddx * ddx + ddy * ddy;
if (d2 > reach2) continue;
const cl = pl - sCol[k * 3];
const ca = pa - sCol[k * 3 + 1];
const cb = pb - sCol[k * 3 + 2];
const e = d2 * invS2 + (cl * cl + ca * ca + cb * cb) * invC2;
if (e > 16) continue;
const wgt = Math.exp(-e);
den += wgt;
n0 += wgt * sOff[k * 3];
n1 += wgt * sOff[k * 3 + 1];
n2 += wgt * sOff[k * 3 + 2];
}
if (den <= 1e-9) continue;
let f0 = n0 / den;
let f1 = n1 / den;
let f2 = n2 / den;
const mag = Math.sqrt(f0 * f0 + f1 * f1 + f2 * f2);
const scale = Math.min(1, opt.cap / Math.max(mag, 1e-9)) * Math.min(1, den / opt.confidenceWeight);
f0 *= scale;
f1 *= scale;
f2 *= scale;
corr[j * 3] = f0;
corr[j * 3 + 1] = f1;
corr[j * 3 + 2] = f2;
}
}
let maxDE = 0;
let touched = false;
const clampX = (v) => Math.min(lw - 1, Math.max(0, v));
const clampY = (v) => Math.min(lh - 1, Math.max(0, v));
for (let y = 0; y < rh; y++) {
const fy = (y + 0.5) / s - 0.5;
const iy0 = Math.floor(fy);
const wy = fy - iy0;
const ya = clampY(iy0);
const yb = clampY(iy0 + 1);
for (let x = 0; x < rw; x++) {
const i = y * rw + x;
const mv = m[i];
if (mv <= 0) continue;
const fx = (x + 0.5) / s - 0.5;
const ix0 = Math.floor(fx);
const wx = fx - ix0;
const xa = clampX(ix0);
const xb = clampX(ix0 + 1);
let c0 = 0;
let c1 = 0;
let c2 = 0;
for (let c = 0; c < 3; c++) {
const v = corr[(ya * lw + xa) * 3 + c] * (1 - wx) * (1 - wy) + corr[(ya * lw + xb) * 3 + c] * wx * (1 - wy) + corr[(yb * lw + xa) * 3 + c] * (1 - wx) * wy + corr[(yb * lw + xb) * 3 + c] * wx * wy;
if (c === 0) c0 = v * mv;
else if (c === 1) c1 = v * mv;
else c2 = v * mv;
}
const de = Math.sqrt(c0 * c0 + c1 * c1 + c2 * c2);
if (de < 0.01) continue;
if (de > maxDE) maxDE = de;
touched = true;
const o = ((y0 + y) * W + (x0 + x)) * result.channels;
labToRgb(labR[i * 3] - c0, labR[i * 3 + 1] - c1, labR[i * 3 + 2] - c2, out, o);
}
}
return { data: out, applied: touched, samples: total, meanOffsetLab: mean, maxCorrectionDE: maxDE };
}
function bitmapToLab(bitmap) {
const n = bitmap.width * bitmap.height;
const out = new Float32Array(n * 3);
for (let i = 0; i < n; i++) {
const p = i * bitmap.channels;
rgbToLab(bitmap.data[p], bitmap.data[p + 1], bitmap.data[p + 2], out, i * 3);
}
return out;
}
function rectMask(width, height, box, feather = 5) {
const [bx0, by0, bx1, by1] = box;
const out = new Float32Array(width * height);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const d = Math.min(x - bx0, bx1 - 1 - x, y - by0, by1 - 1 - y);
out[y * width + x] = Math.min(1, Math.max(0, (d + 0.5) / feather));
}
}
return out;
}
async function correctMaskColorDriftPng(originalPng, resultPng, maskPng, options = {}) {
const [orig, res, msk] = await Promise.all([decodeToRgba(originalPng), decodeToRgba(resultPng), decodeToRgba(maskPng)]);
if (orig.width !== res.width || orig.height !== res.height || msk.width !== res.width || msk.height !== res.height) {
throw new Error(
`size mismatch: original ${orig.width}x${orig.height}, result ${res.width}x${res.height}, mask ${msk.width}x${msk.height}`
);
}
const coverage = new Float32Array(res.width * res.height);
for (let i = 0; i < coverage.length; i++) coverage[i] = msk.data[i * 4] / 255;
const fixed = correctMaskColorDrift(
{ data: orig.data, width: orig.width, height: orig.height, channels: 4 },
{ data: res.data, width: res.width, height: res.height, channels: 4 },
coverage,
options
);
if (!fixed.applied) {
return { png: resultPng, applied: false, samples: fixed.samples, meanOffsetLab: fixed.meanOffsetLab, maxCorrectionDE: 0 };
}
return {
png: await encodeRgbaToPng(fixed.data, res.width, res.height),
applied: true,
samples: fixed.samples,
meanOffsetLab: fixed.meanOffsetLab,
maxCorrectionDE: fixed.maxCorrectionDE
};
}
// src/helpers/outputDims.ts
function chooseAlignedCanvas(rawW, rawH, opts) {
const { align, targetSum } = opts;
const aspect = rawW / Math.max(1, rawH);
const scale = rawW + rawH > targetSum ? targetSum / (rawW + rawH) : 1;
const wRaw = rawW * scale;
const hRaw = rawH * scale;
const snaps = (v) => [
Math.max(align, Math.floor(v / align) * align),
Math.max(align, Math.round(v / align) * align),
Math.max(align, Math.ceil(v / align) * align)
];
const candidates = [];
for (const w of snaps(wRaw)) {
for (const h of snaps(hRaw)) {
if (w + h <= targetSum) candidates.push({ width: w, height: h, arErr: Math.abs(w / h - aspect) });
}
}
candidates.sort((a, b) => a.arErr - b.arErr || b.width + b.height - (a.width + a.height));
const best = candidates[0];
if (best) return { width: best.width, height: best.height };
return {
width: Math.max(align, Math.floor(wRaw / align) * align),
height: Math.max(align, Math.floor(hRaw / align) * align)
};
}
function resolveRequestedOutputDims(canvas, requested, limits) {
const valid = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
const hasW = valid(requested.width);
const hasH = valid(requested.height);
if (!hasW && !hasH) return { ...canvas };
const aspect = canvas.width / Math.max(1, canvas.height);
let width = hasW ? Math.round(requested.width) : Math.round(requested.height * aspect);
let height = hasH ? Math.round(requested.height) : Math.round(requested.width / aspect);
const s = Math.min(limits.maxWidth / width, limits.maxHeight / height, 1);
if (s < 1) {
width = Math.round(width * s);
height = Math.round(height * s);
}
return { width: Math.max(1, width), height: Math.max(1, height) };
}
async function resizeCanvasAndMask(canvasBuf, maskBuf, from, target2) {
if (from.width === target2.width && from.height === target2.height) return { canvasBuf, maskBuf };
return {
canvasBuf: await resizeCoverToPng(canvasBuf, target2.width, target2.height),
maskBuf: await resizeCoverToPng(maskBuf, target2.width, target2.height)
};
}
// src/helpers/pngMetadata.ts
import os5 from "node:os";
var DEFAULT_GENERATOR = "ceveyne/draw-things-chat-core";
var CRC_TABLE = (() => {
const table = new Int32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) {
c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
}
table[n] = c;
}
return table;
})();
function crc32(data) {
let crc = 4294967295;
for (let i = 0; i < data.length; i++) {
crc = CRC_TABLE[(crc ^ data[i]) & 255] ^ crc >>> 8;
}
return (crc ^ 4294967295) >>> 0;
}
function normPath(absPath) {
const home = os5.homedir();
return absPath.startsWith(home) ? "~" + absPath.slice(home.length) : absPath;
}
function escapeXml(s) {
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
}
function basename2(filePath) {
return filePath.replace(/^.*[\\/]/, "");
}
function buildA1111Description(p) {
const lines = [];
if (p.prompt) lines.push(p.prompt);
if (p.negativePrompt) lines.push(`Negative prompt: ${p.negativePrompt}`);
const info = [];
if (typeof p.steps === "number") info.push(`Steps: ${p.steps}`);
if (p.sampler) info.push(`Sampler: ${p.sampler}`);
if (typeof p.guidanceScale === "number") info.push(`Guidance Scale: ${p.guidanceScale}`);
if (typeof p.seed === "number") info.push(`Seed: ${p.seed}`);
if (typeof p.width === "number" && typeof p.height === "number") {
info.push(`Size: ${p.width}x${p.height}`);
}
if (p.model) info.push(`Model: ${p.model}`);
if (typeof p.strength === "number") info.push(`Strength: ${p.strength}`);
if (p.seedMode) info.push(`Seed Mode: ${p.seedMode}`);
if (typeof p.shift === "number") info.push(`Shift: ${p.shift}`);
if (info.length > 0) lines.push(info.join(", "));
if (p.loras) {
p.loras.forEach((l, i) => {
const idx = i + 1;
const name = basename2(l.file);
let entry = `LoRA ${idx} Model: ${name}`;
if (typeof l.weight === "number") entry += `, LoRA ${idx} Weight: ${l.weight}`;
lines.push(entry);
});
}
if (p.sources && p.sources.length > 0) {
lines.push(`Source: ${p.sources.map(normPath).join(", ")}`);
}
if (p.crop) {
lines.push(`Crop: left=${p.crop.left}%, top=${p.crop.top}%, right=${p.crop.right}%, bottom=${p.crop.bottom}%`);
}
if (p.cropSource) lines.push(`Crop Source: ${p.cropSource}`);
if (p.isVideoFrame) lines.push("Note: Last frame of generated video.");
return lines.join("\n");
}
function buildUserCommentJson(p) {
const obj = {};
if (p.prompt != null) obj["c"] = p.prompt;
if (p.negativePrompt != null) obj["uc"] = p.negativePrompt;
if (p.model) obj["model"] = p.model;
if (p.sampler) obj["sampler"] = p.sampler;
if (typeof p.guidanceScale === "number") obj["scale"] = p.guidanceScale;
if (typeof p.seed === "number") obj["seed"] = p.seed;
if (p.seedMode) obj["seed_mode"] = p.seedMode;
if (typeof p.shift === "number") obj["shift"] = p.shift;
if (typeof p.width === "number" && typeof p.height === "number") {
obj["size"] = `${p.width}x${p.height}`;
}
if (typeof p.steps === "number") obj["steps"] = p.steps;
if (typeof p.strength === "number") obj["strength"] = p.strength;
if (p.loras && p.loras.length > 0) {
obj["lora"] = p.loras.map((l) => {
const entry = { model: basename2(l.file) };
if (typeof l.weight === "number") entry["weight"] = l.weight;
return entry;
});
}
if (p.sources && p.sources.length > 0) {
obj["sources"] = p.sources.map(normPath);
}
if (p.mode) obj["mode"] = p.mode;
if (p.crop) obj["crop"] = p.crop;
if (p.cropSource) obj["crop_source"] = p.cropSource;
if (p.isVideoFrame) obj["is_video_frame"] = true;
if (p.v2) obj["v2"] = p.v2;
obj["generated_by"] = p.generatedBy ?? DEFAULT_GENERATOR;
return JSON.stringify(obj);
}
function buildXmpString(p) {
const desc = escapeXml(buildA1111Description(p));
const uc = buildUserCommentJson(p);
const createdAt = escapeXml(p.createdAt ?? (/* @__PURE__ */ new Date()).toISOString());
return [
`<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="XMP Core 6.0.0">`,
` <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">`,
` <rdf:Description rdf:about=""`,
` xmlns:dc="http://purl.org/dc/elements/1.1/"`,
` xmlns:xmp="http://ns.adobe.com/xap/1.0/"`,
` xmlns:exif="http://ns.adobe.com/exif/1.0/">`,
` <dc:description>`,
` <rdf:Alt>`,
` <rdf:li xml:lang="x-default">${desc}</rdf:li>`,
` </rdf:Alt>`,
` </dc:description>`,
` <xmp:CreatorTool>${escapeXml(p.generatedBy ?? DEFAULT_GENERATOR)}</xmp:CreatorTool>`,
` <xmp:CreateDate>${createdAt}</xmp:CreateDate>`,
` <exif:UserComment>`,
` <rdf:Alt>`,
` <rdf:li xml:lang="x-default">${uc}</rdf:li>`,
` </rdf:Alt>`,
` </exif:UserComment>`,
` </rdf:Description>`,
` </rdf:RDF>`,
`</x:xmpmeta>`
].join("\n");
}
function buildITxtChunk(keyword, text) {
const keyBuf = Buffer.from(keyword, "utf8");
const textBuf = Buffer.from(text, "utf8");
const data = Buffer.concat([
keyBuf,
Buffer.from([0, 0, 0, 0, 0]),
textBuf
]);
const typeAndData = Buffer.concat([Buffer.from("iTXt", "ascii"), data]);
const crc = crc32(typeAndData);
const chunk = Buffer.allocUnsafe(4 + 4 + data.length + 4);
chunk.writeUInt32BE(data.length, 0);
chunk.write("iTXt", 4, "ascii");
data.copy(chunk, 8);
chunk.writeUInt32BE(crc, 8 + data.length);
return chunk;
}
var PNG_SIG = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
var IHDR_BYTES = 25;
function injectXmpIntoBuffer(pngBuf, params) {
if (pngBuf.length < PNG_SIG.length + IHDR_BYTES) return pngBuf;
if (!pngBuf.subarray(0, PNG_SIG.length).equals(PNG_SIG)) return pngBuf;
const xmp = buildXmpString(params);
const chunk = buildITxtChunk("XML:com.adobe.xmp", xmp);
const insertAt = PNG_SIG.length + IHDR_BYTES;
return Buffer.concat([
pngBuf.subarray(0, insertAt),
chunk,
pngBuf.subarray(insertAt)
]);
}
// src/helpers/generationConfigV2.ts
var flatbuffers8 = __toESM(require_flatbuffers(), 1);
// src/interfaces/generation-configuration.ts
var flatbuffers7 = __toESM(require_flatbuffers(), 1);
// src/interfaces/color-calibration.ts
var ColorCalibration = /* @__PURE__ */ ((ColorCalibration2) => {
ColorCalibration2[ColorCalibration2["Disabled"] = 0] = "Disabled";
ColorCalibration2[ColorCalibration2["Lab"] = 1] = "Lab";
return ColorCalibration2;
})(ColorCalibration || {});
// src/interfaces/compression-method.ts
var CompressionMethod = /* @__PURE__ */ ((CompressionMethod2) => {
CompressionMethod2[CompressionMethod2["Disabled"] = 0] = "Disabled";
CompressionMethod2[CompressionMethod2["H264"] = 1] = "H264";
CompressionMethod2[CompressionMethod2["H265"] = 2] = "H265";
CompressionMethod2[CompressionMethod2["Jpeg"] = 3] = "Jpeg";
return CompressionMethod2;
})(CompressionMethod || {});
// src/interfaces/generation-configuration.ts
var GenerationConfiguration = class _GenerationConfiguration {
bb = null;
bb_pos = 0;
__init(i, bb) {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsGenerationConfiguration(bb, obj) {
return (obj || new _GenerationConfiguration()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
static getSizePrefixedRootAsGenerationConfiguration(bb, obj) {
bb.setPosition(bb.position() + flatbuffers7.SIZE_PREFIX_LENGTH);
return (obj || new _GenerationConfiguration()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
id() {
const offset = this.bb.__offset(this.bb_pos, 4);
return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0");
}
startWidth() {
const offset = this.bb.__offset(this.bb_pos, 6);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
}
startHeight() {
const offset = this.bb.__offset(this.bb_pos, 8);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
}
seed() {
const offset = this.bb.__offset(this.bb_pos, 10);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
steps() {
const offset = this.bb.__offset(this.bb_pos, 12);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
guidanceScale() {
const offset = this.bb.__offset(this.bb_pos, 14);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0;
}
strength() {
const offset = this.bb.__offset(this.bb_pos, 16);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0;
}
model(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 18);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
sampler() {
const offset = this.bb.__offset(this.bb_pos, 20);
return offset ? this.bb.readInt8(this.bb_pos + offset) : 0 /* DPMPP2MKarras */;
}
batchCount() {
const offset = this.bb.__offset(this.bb_pos, 22);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 1;
}
batchSize() {
const offset = this.bb.__offset(this.bb_pos, 24);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 1;
}
hiresFix() {
const offset = this.bb.__offset(this.bb_pos, 26);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
hiresFixStartWidth() {
const offset = this.bb.__offset(this.bb_pos, 28);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
}
hiresFixStartHeight() {
const offset = this.bb.__offset(this.bb_pos, 30);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
}
hiresFixStrength() {
const offset = this.bb.__offset(this.bb_pos, 32);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.7;
}
upscaler(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 34);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
imageGuidanceScale() {
const offset = this.bb.__offset(this.bb_pos, 36);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1.5;
}
seedMode() {
const offset = this.bb.__offset(this.bb_pos, 38);
return offset ? this.bb.readInt8(this.bb_pos + offset) : 0 /* Legacy */;
}
clipSkip() {
const offset = this.bb.__offset(this.bb_pos, 40);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 1;
}
controls(index2, obj) {
const offset = this.bb.__offset(this.bb_pos, 42);
return offset ? (obj || new Control()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index2 * 4), this.bb) : null;
}
controlsLength() {
const offset = this.bb.__offset(this.bb_pos, 42);
return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
}
loras(index2, obj) {
const offset = this.bb.__offset(this.bb_pos, 44);
return offset ? (obj || new LoRA()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index2 * 4), this.bb) : null;
}
lorasLength() {
const offset = this.bb.__offset(this.bb_pos, 44);
return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
}
maskBlur() {
const offset = this.bb.__offset(this.bb_pos, 46);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0;
}
faceRestoration(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 48);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
clipWeight() {
const offset = this.bb.__offset(this.bb_pos, 54);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1;
}
negativePromptForImagePrior() {
const offset = this.bb.__offset(this.bb_pos, 56);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true;
}
imagePriorSteps() {
const offset = this.bb.__offset(this.bb_pos, 58);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 5;
}
refinerModel(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 60);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
originalImageHeight() {
const offset = this.bb.__offset(this.bb_pos, 62);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
originalImageWidth() {
const offset = this.bb.__offset(this.bb_pos, 64);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
cropTop() {
const offset = this.bb.__offset(this.bb_pos, 66);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
}
cropLeft() {
const offset = this.bb.__offset(this.bb_pos, 68);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
}
targetImageHeight() {
const offset = this.bb.__offset(this.bb_pos, 70);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
targetImageWidth() {
const offset = this.bb.__offset(this.bb_pos, 72);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
aestheticScore() {
const offset = this.bb.__offset(this.bb_pos, 74);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 6;
}
negativeAestheticScore() {
const offset = this.bb.__offset(this.bb_pos, 76);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 2.5;
}
zeroNegativePrompt() {
const offset = this.bb.__offset(this.bb_pos, 78);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
refinerStart() {
const offset = this.bb.__offset(this.bb_pos, 80);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.7;
}
negativeOriginalImageHeight() {
const offset = this.bb.__offset(this.bb_pos, 82);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
negativeOriginalImageWidth() {
const offset = this.bb.__offset(this.bb_pos, 84);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
name(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 86);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
fpsId() {
const offset = this.bb.__offset(this.bb_pos, 88);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 5;
}
motionBucketId() {
const offset = this.bb.__offset(this.bb_pos, 90);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 127;
}
condAug() {
const offset = this.bb.__offset(this.bb_pos, 92);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.02;
}
startFrameCfg() {
const offset = this.bb.__offset(this.bb_pos, 94);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1;
}
numFrames() {
const offset = this.bb.__offset(this.bb_pos, 96);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 14;
}
maskBlurOutset() {
const offset = this.bb.__offset(this.bb_pos, 98);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
}
sharpness() {
const offset = this.bb.__offset(this.bb_pos, 100);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0;
}
shift() {
const offset = this.bb.__offset(this.bb_pos, 102);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1;
}
stage2Steps() {
const offset = this.bb.__offset(this.bb_pos, 104);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 10;
}
stage2Cfg() {
const offset = this.bb.__offset(this.bb_pos, 106);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1;
}
stage2Shift() {
const offset = this.bb.__offset(this.bb_pos, 108);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1;
}
tiledDecoding() {
const offset = this.bb.__offset(this.bb_pos, 110);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
decodingTileWidth() {
const offset = this.bb.__offset(this.bb_pos, 112);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 10;
}
decodingTileHeight() {
const offset = this.bb.__offset(this.bb_pos, 114);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 10;
}
decodingTileOverlap() {
const offset = this.bb.__offset(this.bb_pos, 116);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 2;
}
stochasticSamplingGamma() {
const offset = this.bb.__offset(this.bb_pos, 118);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.3;
}
preserveOriginalAfterInpaint() {
const offset = this.bb.__offset(this.bb_pos, 120);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true;
}
tiledDiffusion() {
const offset = this.bb.__offset(this.bb_pos, 122);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
diffusionTileWidth() {
const offset = this.bb.__offset(this.bb_pos, 124);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 16;
}
diffusionTileHeight() {
const offset = this.bb.__offset(this.bb_pos, 126);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 16;
}
diffusionTileOverlap() {
const offset = this.bb.__offset(this.bb_pos, 128);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 2;
}
upscalerScaleFactor() {
const offset = this.bb.__offset(this.bb_pos, 130);
return offset ? this.bb.readUint8(this.bb_pos + offset) : 0;
}
t5TextEncoder() {
const offset = this.bb.__offset(this.bb_pos, 132);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true;
}
separateClipL() {
const offset = this.bb.__offset(this.bb_pos, 134);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
clipLText(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 136);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
separateOpenClipG() {
const offset = this.bb.__offset(this.bb_pos, 138);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
openClipGText(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 140);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
speedUpWithGuidanceEmbed() {
const offset = this.bb.__offset(this.bb_pos, 142);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true;
}
guidanceEmbed() {
const offset = this.bb.__offset(this.bb_pos, 144);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 3.5;
}
resolutionDependentShift() {
const offset = this.bb.__offset(this.bb_pos, 146);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true;
}
teaCacheStart() {
const offset = this.bb.__offset(this.bb_pos, 148);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 5;
}
teaCacheEnd() {
const offset = this.bb.__offset(this.bb_pos, 150);
return offset ? this.bb.readInt32(this.bb_pos + offset) : -1;
}
teaCacheThreshold() {
const offset = this.bb.__offset(this.bb_pos, 152);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.06;
}
teaCache() {
const offset = this.bb.__offset(this.bb_pos, 154);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
separateT5() {
const offset = this.bb.__offset(this.bb_pos, 156);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
t5Text(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 158);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
teaCacheMaxSkipSteps() {
const offset = this.bb.__offset(this.bb_pos, 160);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 3;
}
causalInferenceEnabled() {
const offset = this.bb.__offset(this.bb_pos, 162);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
causalInference() {
const offset = this.bb.__offset(this.bb_pos, 164);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 3;
}
causalInferencePad() {
const offset = this.bb.__offset(this.bb_pos, 166);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
}
cfgZeroStar() {
const offset = this.bb.__offset(this.bb_pos, 168);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
cfgZeroInitSteps() {
const offset = this.bb.__offset(this.bb_pos, 170);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
}
compressionArtifacts() {
const offset = this.bb.__offset(this.bb_pos, 172);
return offset ? this.bb.readInt8(this.bb_pos + offset) : 0 /* Disabled */;
}
compressionArtifactsQuality() {
const offset = this.bb.__offset(this.bb_pos, 174);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 43.1;
}
colorCalibration() {
const offset = this.bb.__offset(this.bb_pos, 176);
return offset ? this.bb.readInt8(this.bb_pos + offset) : 0 /* Disabled */;
}
expandPromptToJson() {
const offset = this.bb.__offset(this.bb_pos, 178);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
shiftForAudio() {
const offset = this.bb.__offset(this.bb_pos, 180);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 3;
}
usesSolAttention() {
const offset = this.bb.__offset(this.bb_pos, 182);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
solAttentionStart() {
const offset = this.bb.__offset(this.bb_pos, 184);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 2;
}
solAttentionTau() {
const offset = this.bb.__offset(this.bb_pos, 186);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.5;
}
static startGenerationConfiguration(builder) {
builder.startObject(92);
}
static addId(builder, id) {
builder.addFieldInt64(0, id, BigInt("0"));
}
static addStartWidth(builder, startWidth) {
builder.addFieldInt16(1, startWidth, 0);
}
static addStartHeight(builder, startHeight) {
builder.addFieldInt16(2, startHeight, 0);
}
static addSeed(builder, seed) {
builder.addFieldInt32(3, seed, 0);
}
static addSteps(builder, steps) {
builder.addFieldInt32(4, steps, 0);
}
static addGuidanceScale(builder, guidanceScale) {
builder.addFieldFloat32(5, guidanceScale, 0);
}
static addStrength(builder, strength) {
builder.addFieldFloat32(6, strength, 0);
}
static addModel(builder, modelOffset) {
builder.addFieldOffset(7, modelOffset, 0);
}
static addSampler(builder, sampler) {
builder.addFieldInt8(8, sampler, 0 /* DPMPP2MKarras */);
}
static addBatchCount(builder, batchCount) {
builder.addFieldInt32(9, batchCount, 1);
}
static addBatchSize(builder, batchSize) {
builder.addFieldInt32(10, batchSize, 1);
}
static addHiresFix(builder, hiresFix) {
builder.addFieldInt8(11, +hiresFix, 0);
}
static addHiresFixStartWidth(builder, hiresFixStartWidth) {
builder.addFieldInt16(12, hiresFixStartWidth, 0);
}
static addHiresFixStartHeight(builder, hiresFixStartHeight) {
builder.addFieldInt16(13, hiresFixStartHeight, 0);
}
static addHiresFixStrength(builder, hiresFixStrength) {
builder.addFieldFloat32(14, hiresFixStrength, 0.7);
}
static addUpscaler(builder, upscalerOffset) {
builder.addFieldOffset(15, upscalerOffset, 0);
}
static addImageGuidanceScale(builder, imageGuidanceScale) {
builder.addFieldFloat32(16, imageGuidanceScale, 1.5);
}
static addSeedMode(builder, seedMode) {
builder.addFieldInt8(17, seedMode, 0 /* Legacy */);
}
static addClipSkip(builder, clipSkip) {
builder.addFieldInt32(18, clipSkip, 1);
}
static addControls(builder, controlsOffset) {
builder.addFieldOffset(19, controlsOffset, 0);
}
static createControlsVector(builder, data) {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
static startControlsVector(builder, numElems) {
builder.startVector(4, numElems, 4);
}
static addLoras(builder, lorasOffset) {
builder.addFieldOffset(20, lorasOffset, 0);
}
static createLorasVector(builder, data) {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
static startLorasVector(builder, numElems) {
builder.startVector(4, numElems, 4);
}
static addMaskBlur(builder, maskBlur) {
builder.addFieldFloat32(21, maskBlur, 0);
}
static addFaceRestoration(builder, faceRestorationOffset) {
builder.addFieldOffset(22, faceRestorationOffset, 0);
}
static addClipWeight(builder, clipWeight) {
builder.addFieldFloat32(25, clipWeight, 1);
}
static addNegativePromptForImagePrior(builder, negativePromptForImagePrior) {
builder.addFieldInt8(26, +negativePromptForImagePrior, 1);
}
static addImagePriorSteps(builder, imagePriorSteps) {
builder.addFieldInt32(27, imagePriorSteps, 5);
}
static addRefinerModel(builder, refinerModelOffset) {
builder.addFieldOffset(28, refinerModelOffset, 0);
}
static addOriginalImageHeight(builder, originalImageHeight) {
builder.addFieldInt32(29, originalImageHeight, 0);
}
static addOriginalImageWidth(builder, originalImageWidth) {
builder.addFieldInt32(30, originalImageWidth, 0);
}
static addCropTop(builder, cropTop) {
builder.addFieldInt32(31, cropTop, 0);
}
static addCropLeft(builder, cropLeft) {
builder.addFieldInt32(32, cropLeft, 0);
}
static addTargetImageHeight(builder, targetImageHeight) {
builder.addFieldInt32(33, targetImageHeight, 0);
}
static addTargetImageWidth(builder, targetImageWidth) {
builder.addFieldInt32(34, targetImageWidth, 0);
}
static addAestheticScore(builder, aestheticScore) {
builder.addFieldFloat32(35, aestheticScore, 6);
}
static addNegativeAestheticScore(builder, negativeAestheticScore) {
builder.addFieldFloat32(36, negativeAestheticScore, 2.5);
}
static addZeroNegativePrompt(builder, zeroNegativePrompt) {
builder.addFieldInt8(37, +zeroNegativePrompt, 0);
}
static addRefinerStart(builder, refinerStart) {
builder.addFieldFloat32(38, refinerStart, 0.7);
}
static addNegativeOriginalImageHeight(builder, negativeOriginalImageHeight) {
builder.addFieldInt32(39, negativeOriginalImageHeight, 0);
}
static addNegativeOriginalImageWidth(builder, negativeOriginalImageWidth) {
builder.addFieldInt32(40, negativeOriginalImageWidth, 0);
}
static addName(builder, nameOffset) {
builder.addFieldOffset(41, nameOffset, 0);
}
static addFpsId(builder, fpsId) {
builder.addFieldInt32(42, fpsId, 5);
}
static addMotionBucketId(builder, motionBucketId) {
builder.addFieldInt32(43, motionBucketId, 127);
}
static addCondAug(builder, condAug) {
builder.addFieldFloat32(44, condAug, 0.02);
}
static addStartFrameCfg(builder, startFrameCfg) {
builder.addFieldFloat32(45, startFrameCfg, 1);
}
static addNumFrames(builder, numFrames) {
builder.addFieldInt32(46, numFrames, 14);
}
static addMaskBlurOutset(builder, maskBlurOutset) {
builder.addFieldInt32(47, maskBlurOutset, 0);
}
static addSharpness(builder, sharpness) {
builder.addFieldFloat32(48, sharpness, 0);
}
static addShift(builder, shift) {
builder.addFieldFloat32(49, shift, 1);
}
static addStage2Steps(builder, stage2Steps) {
builder.addFieldInt32(50, stage2Steps, 10);
}
static addStage2Cfg(builder, stage2Cfg) {
builder.addFieldFloat32(51, stage2Cfg, 1);
}
static addStage2Shift(builder, stage2Shift) {
builder.addFieldFloat32(52, stage2Shift, 1);
}
static addTiledDecoding(builder, tiledDecoding) {
builder.addFieldInt8(53, +tiledDecoding, 0);
}
static addDecodingTileWidth(builder, decodingTileWidth) {
builder.addFieldInt16(54, decodingTileWidth, 10);
}
static addDecodingTileHeight(builder, decodingTileHeight) {
builder.addFieldInt16(55, decodingTileHeight, 10);
}
static addDecodingTileOverlap(builder, decodingTileOverlap) {
builder.addFieldInt16(56, decodingTileOverlap, 2);
}
static addStochasticSamplingGamma(builder, stochasticSamplingGamma) {
builder.addFieldFloat32(57, stochasticSamplingGamma, 0.3);
}
static addPreserveOriginalAfterInpaint(builder, preserveOriginalAfterInpaint) {
builder.addFieldInt8(58, +preserveOriginalAfterInpaint, 1);
}
static addTiledDiffusion(builder, tiledDiffusion) {
builder.addFieldInt8(59, +tiledDiffusion, 0);
}
static addDiffusionTileWidth(builder, diffusionTileWidth) {
builder.addFieldInt16(60, diffusionTileWidth, 16);
}
static addDiffusionTileHeight(builder, diffusionTileHeight) {
builder.addFieldInt16(61, diffusionTileHeight, 16);
}
static addDiffusionTileOverlap(builder, diffusionTileOverlap) {
builder.addFieldInt16(62, diffusionTileOverlap, 2);
}
static addUpscalerScaleFactor(builder, upscalerScaleFactor) {
builder.addFieldInt8(63, upscalerScaleFactor, 0);
}
static addT5TextEncoder(builder, t5TextEncoder) {
builder.addFieldInt8(64, +t5TextEncoder, 1);
}
static addSeparateClipL(builder, separateClipL) {
builder.addFieldInt8(65, +separateClipL, 0);
}
static addClipLText(builder, clipLTextOffset) {
builder.addFieldOffset(66, clipLTextOffset, 0);
}
static addSeparateOpenClipG(builder, separateOpenClipG) {
builder.addFieldInt8(67, +separateOpenClipG, 0);
}
static addOpenClipGText(builder, openClipGTextOffset) {
builder.addFieldOffset(68, openClipGTextOffset, 0);
}
static addSpeedUpWithGuidanceEmbed(builder, speedUpWithGuidanceEmbed) {
builder.addFieldInt8(69, +speedUpWithGuidanceEmbed, 1);
}
static addGuidanceEmbed(builder, guidanceEmbed) {
builder.addFieldFloat32(70, guidanceEmbed, 3.5);
}
static addResolutionDependentShift(builder, resolutionDependentShift) {
builder.addFieldInt8(71, +resolutionDependentShift, 1);
}
static addTeaCacheStart(builder, teaCacheStart) {
builder.addFieldInt32(72, teaCacheStart, 5);
}
static addTeaCacheEnd(builder, teaCacheEnd) {
builder.addFieldInt32(73, teaCacheEnd, -1);
}
static addTeaCacheThreshold(builder, teaCacheThreshold) {
builder.addFieldFloat32(74, teaCacheThreshold, 0.06);
}
static addTeaCache(builder, teaCache) {
builder.addFieldInt8(75, +teaCache, 0);
}
static addSeparateT5(builder, separateT5) {
builder.addFieldInt8(76, +separateT5, 0);
}
static addT5Text(builder, t5TextOffset) {
builder.addFieldOffset(77, t5TextOffset, 0);
}
static addTeaCacheMaxSkipSteps(builder, teaCacheMaxSkipSteps) {
builder.addFieldInt32(78, teaCacheMaxSkipSteps, 3);
}
static addCausalInferenceEnabled(builder, causalInferenceEnabled) {
builder.addFieldInt8(79, +causalInferenceEnabled, 0);
}
static addCausalInference(builder, causalInference) {
builder.addFieldInt32(80, causalInference, 3);
}
static addCausalInferencePad(builder, causalInferencePad) {
builder.addFieldInt32(81, causalInferencePad, 0);
}
static addCfgZeroStar(builder, cfgZeroStar) {
builder.addFieldInt8(82, +cfgZeroStar, 0);
}
static addCfgZeroInitSteps(builder, cfgZeroInitSteps) {
builder.addFieldInt32(83, cfgZeroInitSteps, 0);
}
static addCompressionArtifacts(builder, compressionArtifacts) {
builder.addFieldInt8(84, compressionArtifacts, 0 /* Disabled */);
}
static addCompressionArtifactsQuality(builder, compressionArtifactsQuality) {
builder.addFieldFloat32(85, compressionArtifactsQuality, 43.1);
}
static addColorCalibration(builder, colorCalibration) {
builder.addFieldInt8(86, colorCalibration, 0 /* Disabled */);
}
static addExpandPromptToJson(builder, expandPromptToJson) {
builder.addFieldInt8(87, +expandPromptToJson, 0);
}
static addShiftForAudio(builder, shiftForAudio) {
builder.addFieldFloat32(88, shiftForAudio, 3);
}
static addUsesSolAttention(builder, usesSolAttention) {
builder.addFieldInt8(89, +usesSolAttention, 0);
}
static addSolAttentionStart(builder, solAttentionStart) {
builder.addFieldInt32(90, solAttentionStart, 2);
}
static addSolAttentionTau(builder, solAttentionTau) {
builder.addFieldFloat32(91, solAttentionTau, 0.5);
}
static endGenerationConfiguration(builder) {
const offset = builder.endObject();
return offset;
}
static finishGenerationConfigurationBuffer(builder, offset) {
builder.finish(offset);
}
static finishSizePrefixedGenerationConfigurationBuffer(builder, offset) {
builder.finish(offset, void 0, true);
}
static createGenerationConfiguration(builder, id, startWidth, startHeight, seed, steps, guidanceScale, strength, modelOffset, sampler, batchCount, batchSize, hiresFix, hiresFixStartWidth, hiresFixStartHeight, hiresFixStrength, upscalerOffset, imageGuidanceScale, seedMode, clipSkip, controlsOffset, lorasOffset, maskBlur, faceRestorationOffset, clipWeight, negativePromptForImagePrior, imagePriorSteps, refinerModelOffset, originalImageHeight, originalImageWidth, cropTop, cropLeft, targetImageHeight, targetImageWidth, aestheticScore, negativeAestheticScore, zeroNegativePrompt, refinerStart, negativeOriginalImageHeight, negativeOriginalImageWidth, nameOffset, fpsId, motionBucketId, condAug, startFrameCfg, numFrames, maskBlurOutset, sharpness, shift, stage2Steps, stage2Cfg, stage2Shift, tiledDecoding, decodingTileWidth, decodingTileHeight, decodingTileOverlap, stochasticSamplingGamma, preserveOriginalAfterInpaint, tiledDiffusion, diffusionTileWidth, diffusionTileHeight, diffusionTileOverlap, upscalerScaleFactor, t5TextEncoder, separateClipL, clipLTextOffset, separateOpenClipG, openClipGTextOffset, speedUpWithGuidanceEmbed, guidanceEmbed, resolutionDependentShift, teaCacheStart, teaCacheEnd, teaCacheThreshold, teaCache, separateT5, t5TextOffset, teaCacheMaxSkipSteps, causalInferenceEnabled, causalInference, causalInferencePad, cfgZeroStar, cfgZeroInitSteps, compressionArtifacts, compressionArtifactsQuality, colorCalibration, expandPromptToJson, shiftForAudio, usesSolAttention, solAttentionStart, solAttentionTau) {
_GenerationConfiguration.startGenerationConfiguration(builder);
_GenerationConfiguration.addId(builder, id);
_GenerationConfiguration.addStartWidth(builder, startWidth);
_GenerationConfiguration.addStartHeight(builder, startHeight);
_GenerationConfiguration.addSeed(builder, seed);
_GenerationConfiguration.addSteps(builder, steps);
_GenerationConfiguration.addGuidanceScale(builder, guidanceScale);
_GenerationConfiguration.addStrength(builder, strength);
_GenerationConfiguration.addModel(builder, modelOffset);
_GenerationConfiguration.addSampler(builder, sampler);
_GenerationConfiguration.addBatchCount(builder, batchCount);
_GenerationConfiguration.addBatchSize(builder, batchSize);
_GenerationConfiguration.addHiresFix(builder, hiresFix);
_GenerationConfiguration.addHiresFixStartWidth(builder, hiresFixStartWidth);
_GenerationConfiguration.addHiresFixStartHeight(builder, hiresFixStartHeight);
_GenerationConfiguration.addHiresFixStrength(builder, hiresFixStrength);
_GenerationConfiguration.addUpscaler(builder, upscalerOffset);
_GenerationConfiguration.addImageGuidanceScale(builder, imageGuidanceScale);
_GenerationConfiguration.addSeedMode(builder, seedMode);
_GenerationConfiguration.addClipSkip(builder, clipSkip);
_GenerationConfiguration.addControls(builder, controlsOffset);
_GenerationConfiguration.addLoras(builder, lorasOffset);
_GenerationConfiguration.addMaskBlur(builder, maskBlur);
_GenerationConfiguration.addFaceRestoration(builder, faceRestorationOffset);
_GenerationConfiguration.addClipWeight(builder, clipWeight);
_GenerationConfiguration.addNegativePromptForImagePrior(builder, negativePromptForImagePrior);
_GenerationConfiguration.addImagePriorSteps(builder, imagePriorSteps);
_GenerationConfiguration.addRefinerModel(builder, refinerModelOffset);
_GenerationConfiguration.addOriginalImageHeight(builder, originalImageHeight);
_GenerationConfiguration.addOriginalImageWidth(builder, originalImageWidth);
_GenerationConfiguration.addCropTop(builder, cropTop);
_GenerationConfiguration.addCropLeft(builder, cropLeft);
_GenerationConfiguration.addTargetImageHeight(builder, targetImageHeight);
_GenerationConfiguration.addTargetImageWidth(builder, targetImageWidth);
_GenerationConfiguration.addAestheticScore(builder, aestheticScore);
_GenerationConfiguration.addNegativeAestheticScore(builder, negativeAestheticScore);
_GenerationConfiguration.addZeroNegativePrompt(builder, zeroNegativePrompt);
_GenerationConfiguration.addRefinerStart(builder, refinerStart);
_GenerationConfiguration.addNegativeOriginalImageHeight(builder, negativeOriginalImageHeight);
_GenerationConfiguration.addNegativeOriginalImageWidth(builder, negativeOriginalImageWidth);
_GenerationConfiguration.addName(builder, nameOffset);
_GenerationConfiguration.addFpsId(builder, fpsId);
_GenerationConfiguration.addMotionBucketId(builder, motionBucketId);
_GenerationConfiguration.addCondAug(builder, condAug);
_GenerationConfiguration.addStartFrameCfg(builder, startFrameCfg);
_GenerationConfiguration.addNumFrames(builder, numFrames);
_GenerationConfiguration.addMaskBlurOutset(builder, maskBlurOutset);
_GenerationConfiguration.addSharpness(builder, sharpness);
_GenerationConfiguration.addShift(builder, shift);
_GenerationConfiguration.addStage2Steps(builder, stage2Steps);
_GenerationConfiguration.addStage2Cfg(builder, stage2Cfg);
_GenerationConfiguration.addStage2Shift(builder, stage2Shift);
_GenerationConfiguration.addTiledDecoding(builder, tiledDecoding);
_GenerationConfiguration.addDecodingTileWidth(builder, decodingTileWidth);
_GenerationConfiguration.addDecodingTileHeight(builder, decodingTileHeight);
_GenerationConfiguration.addDecodingTileOverlap(builder, decodingTileOverlap);
_GenerationConfiguration.addStochasticSamplingGamma(builder, stochasticSamplingGamma);
_GenerationConfiguration.addPreserveOriginalAfterInpaint(builder, preserveOriginalAfterInpaint);
_GenerationConfiguration.addTiledDiffusion(builder, tiledDiffusion);
_GenerationConfiguration.addDiffusionTileWidth(builder, diffusionTileWidth);
_GenerationConfiguration.addDiffusionTileHeight(builder, diffusionTileHeight);
_GenerationConfiguration.addDiffusionTileOverlap(builder, diffusionTileOverlap);
_GenerationConfiguration.addUpscalerScaleFactor(builder, upscalerScaleFactor);
_GenerationConfiguration.addT5TextEncoder(builder, t5TextEncoder);
_GenerationConfiguration.addSeparateClipL(builder, separateClipL);
_GenerationConfiguration.addClipLText(builder, clipLTextOffset);
_GenerationConfiguration.addSeparateOpenClipG(builder, separateOpenClipG);
_GenerationConfiguration.addOpenClipGText(builder, openClipGTextOffset);
_GenerationConfiguration.addSpeedUpWithGuidanceEmbed(builder, speedUpWithGuidanceEmbed);
_GenerationConfiguration.addGuidanceEmbed(builder, guidanceEmbed);
_GenerationConfiguration.addResolutionDependentShift(builder, resolutionDependentShift);
_GenerationConfiguration.addTeaCacheStart(builder, teaCacheStart);
_GenerationConfiguration.addTeaCacheEnd(builder, teaCacheEnd);
_GenerationConfiguration.addTeaCacheThreshold(builder, teaCacheThreshold);
_GenerationConfiguration.addTeaCache(builder, teaCache);
_GenerationConfiguration.addSeparateT5(builder, separateT5);
_GenerationConfiguration.addT5Text(builder, t5TextOffset);
_GenerationConfiguration.addTeaCacheMaxSkipSteps(builder, teaCacheMaxSkipSteps);
_GenerationConfiguration.addCausalInferenceEnabled(builder, causalInferenceEnabled);
_GenerationConfiguration.addCausalInference(builder, causalInference);
_GenerationConfiguration.addCausalInferencePad(builder, causalInferencePad);
_GenerationConfiguration.addCfgZeroStar(builder, cfgZeroStar);
_GenerationConfiguration.addCfgZeroInitSteps(builder, cfgZeroInitSteps);
_GenerationConfiguration.addCompressionArtifacts(builder, compressionArtifacts);
_GenerationConfiguration.addCompressionArtifactsQuality(builder, compressionArtifactsQuality);
_GenerationConfiguration.addColorCalibration(builder, colorCalibration);
_GenerationConfiguration.addExpandPromptToJson(builder, expandPromptToJson);
_GenerationConfiguration.addShiftForAudio(builder, shiftForAudio);
_GenerationConfiguration.addUsesSolAttention(builder, usesSolAttention);
_GenerationConfiguration.addSolAttentionStart(builder, solAttentionStart);
_GenerationConfiguration.addSolAttentionTau(builder, solAttentionTau);
return _GenerationConfiguration.endGenerationConfiguration(builder);
}
};
// src/helpers/generationConfigV2.ts
function f32(value) {
return Number.isFinite(value) ? parseFloat(value.toPrecision(7)) : value;
}
function omitNull(obj) {
for (const key of Object.keys(obj)) {
if (obj[key] === null || obj[key] === void 0) delete obj[key];
}
return obj;
}
var LORA_MODE = {
[0 /* All */]: "all",
[1 /* Base */]: "base",
[2 /* Refiner */]: "refiner"
};
var CONTROL_MODE = {
[0 /* Balanced */]: "balanced",
[1 /* Prompt */]: "prompt",
[2 /* Control */]: "control"
};
var COMPRESSION = {
[0 /* Disabled */]: "disabled",
[1 /* H264 */]: "h264",
[2 /* H265 */]: "h265",
[3 /* Jpeg */]: "jpeg"
};
var COLOR_CALIBRATION = {
[0 /* Disabled */]: "none",
[1 /* Lab */]: "lab"
};
function generationConfigBytesToV2(bytes) {
const c = GenerationConfiguration.getRootAsGenerationConfiguration(new flatbuffers8.ByteBuffer(bytes));
const loras = [];
for (let i = 0; i < c.lorasLength(); i++) {
const l = c.loras(i);
if (!l) continue;
loras.push(omitNull({ file: l.file(), mode: LORA_MODE[l.mode()] ?? "all", weight: f32(l.weight()) }));
}
const controls = [];
for (let i = 0; i < c.controlsLength(); i++) {
const ctl = c.controls(i);
if (!ctl) continue;
const targetBlocks = [];
for (let b = 0; b < ctl.targetBlocksLength(); b++) targetBlocks.push(String(ctl.targetBlocks(b)));
controls.push(
omitNull({
file: ctl.file(),
weight: f32(ctl.weight()),
guidanceStart: f32(ctl.guidanceStart()),
guidanceEnd: f32(ctl.guidanceEnd()),
noPrompt: ctl.noPrompt(),
globalAveragePooling: ctl.globalAveragePooling(),
downSamplingRate: f32(ctl.downSamplingRate()),
controlImportance: CONTROL_MODE[ctl.controlMode()] ?? "balanced",
inputOverride: (ControlInputType[ctl.inputOverride()] ?? "Unspecified").toLowerCase(),
targetBlocks
})
);
}
const causalEnabled = c.causalInferenceEnabled();
return omitNull({
id: Number(c.id()),
width: c.startWidth() * 64,
height: c.startHeight() * 64,
seed: c.seed(),
steps: c.steps(),
guidanceScale: f32(c.guidanceScale()),
strength: f32(c.strength()),
model: c.model(),
sampler: c.sampler(),
hiresFix: c.hiresFix(),
hiresFixWidth: c.hiresFixStartWidth() * 64,
hiresFixHeight: c.hiresFixStartHeight() * 64,
hiresFixStrength: f32(c.hiresFixStrength()),
tiledDecoding: c.tiledDecoding(),
decodingTileWidth: c.decodingTileWidth() * 64,
decodingTileHeight: c.decodingTileHeight() * 64,
decodingTileOverlap: c.decodingTileOverlap() * 64,
tiledDiffusion: c.tiledDiffusion(),
diffusionTileWidth: c.diffusionTileWidth() * 64,
diffusionTileHeight: c.diffusionTileHeight() * 64,
diffusionTileOverlap: c.diffusionTileOverlap() * 64,
upscaler: c.upscaler(),
upscalerScaleFactor: c.upscalerScaleFactor(),
imageGuidanceScale: f32(c.imageGuidanceScale()),
seedMode: c.seedMode(),
clipSkip: c.clipSkip(),
controls,
loras,
maskBlur: f32(c.maskBlur()),
maskBlurOutset: c.maskBlurOutset(),
sharpness: f32(c.sharpness()),
faceRestoration: c.faceRestoration(),
clipWeight: f32(c.clipWeight()),
negativePromptForImagePrior: c.negativePromptForImagePrior(),
imagePriorSteps: c.imagePriorSteps(),
refinerModel: c.refinerModel(),
originalImageHeight: c.originalImageHeight(),
originalImageWidth: c.originalImageWidth(),
cropTop: c.cropTop(),
cropLeft: c.cropLeft(),
targetImageHeight: c.targetImageHeight(),
targetImageWidth: c.targetImageWidth(),
aestheticScore: f32(c.aestheticScore()),
negativeAestheticScore: f32(c.negativeAestheticScore()),
zeroNegativePrompt: c.zeroNegativePrompt(),
refinerStart: f32(c.refinerStart()),
negativeOriginalImageHeight: c.negativeOriginalImageHeight(),
negativeOriginalImageWidth: c.negativeOriginalImageWidth(),
batchCount: c.batchCount(),
batchSize: c.batchSize(),
numFrames: c.numFrames(),
fps: c.fpsId(),
motionScale: c.motionBucketId(),
guidingFrameNoise: f32(c.condAug()),
startFrameGuidance: f32(c.startFrameCfg()),
shift: f32(c.shift()),
stage2Steps: c.stage2Steps(),
stage2Guidance: f32(c.stage2Cfg()),
stage2Shift: f32(c.stage2Shift()),
stochasticSamplingGamma: f32(c.stochasticSamplingGamma()),
preserveOriginalAfterInpaint: c.preserveOriginalAfterInpaint(),
t5TextEncoder: c.t5TextEncoder(),
separateClipL: c.separateClipL(),
clipLText: c.clipLText(),
separateOpenClipG: c.separateOpenClipG(),
openClipGText: c.openClipGText(),
speedUpWithGuidanceEmbed: c.speedUpWithGuidanceEmbed(),
guidanceEmbed: f32(c.guidanceEmbed()),
resolutionDependentShift: c.resolutionDependentShift(),
teaCache: c.teaCache(),
teaCacheStart: c.teaCacheStart(),
teaCacheEnd: c.teaCacheEnd(),
teaCacheThreshold: f32(c.teaCacheThreshold()),
teaCacheMaxSkipSteps: c.teaCacheMaxSkipSteps(),
separateT5: c.separateT5(),
t5Text: c.t5Text(),
causalInference: causalEnabled ? c.causalInference() : 0,
causalInferencePad: causalEnabled ? c.causalInferencePad() : 0,
cfgZeroStar: c.cfgZeroStar(),
cfgZeroInitSteps: c.cfgZeroInitSteps(),
compressionArtifacts: COMPRESSION[c.compressionArtifacts()] ?? "disabled",
compressionArtifactsQuality: Math.min(Math.max(f32(c.compressionArtifactsQuality()), 0), 100),
colorCalibration: COLOR_CALIBRATION[c.colorCalibration()] ?? "none",
expandPromptToJson: c.expandPromptToJson(),
shiftForAudio: f32(c.shiftForAudio()),
usesSolAttention: c.usesSolAttention(),
solAttentionStart: c.solAttentionStart(),
solAttentionTau: f32(c.solAttentionTau())
});
}
// src/helpers/sourceFreshness.ts
import { createHash as createHash2 } from "node:crypto";
function stableNumber(value) {
if (!Number.isSafeInteger(value)) throw new Error("Project generation identifiers must be safe integers.");
return String(value);
}
function updateHashPart(hash, value) {
const bytes = typeof value === "string" ? Buffer.from(value, "utf8") : Buffer.from(value);
hash.update(String(bytes.length));
hash.update(":");
hash.update(bytes);
hash.update("\0");
}
function projectGenerationIdentity(input) {
const projectPath = input.projectPath.trim();
if (!projectPath) throw new Error("Project generation identity requires a project path.");
return [
projectPath,
stableNumber(input.canvasIndex),
stableNumber(input.historyVersion),
input.thumbnailId === void 0 ? "" : stableNumber(input.thumbnailId)
].join("\0");
}
function projectGenerationFingerprint(input) {
const hash = createHash2("sha256");
updateHashPart(hash, "draw-things-project-generation-v1");
updateHashPart(hash, projectGenerationIdentity(input));
updateHashPart(hash, input.generationBlob);
updateHashPart(hash, input.prompt ?? "");
updateHashPart(hash, input.negativePrompt ?? "");
return `project-generation:${hash.digest("hex")}`;
}
function diffProjectGenerationSnapshots(previous, current) {
const previousById = new Map(previous.map((snapshot) => [snapshot.id, snapshot]));
const currentIds = new Set(current.map((snapshot) => snapshot.id));
const added = [];
const changed = [];
const unchanged = [];
for (const snapshot of current) {
const prior = previousById.get(snapshot.id);
if (!prior) added.push(snapshot);
else if (prior.fingerprint === snapshot.fingerprint) unchanged.push(snapshot);
else changed.push(snapshot);
}
return {
added,
changed,
unchanged,
removed: previous.filter((snapshot) => !currentIds.has(snapshot.id))
};
}
async function checkFreshness(previous, tier1, tier2) {
const currentTier1 = tier1.compute();
if (previous && tier1.equals(previous.tier1, currentTier1)) {
return { status: "unchanged", tier1: currentTier1 };
}
if (!tier2 || !previous?.tier2) {
return { status: "changed", tier1: currentTier1 };
}
const currentTier2 = await tier2.compute();
if (tier2.equals(previous.tier2, currentTier2)) {
return { status: "unchanged-promote", tier1: currentTier1, tier2: currentTier2 };
}
return { status: "changed", tier1: currentTier1, tier2: currentTier2 };
}
// src/helpers/referenceOrigin.ts
import fs22 from "node:fs";
import path22 from "node:path";
var DERIVATIVE_TOOL_NAMES = /* @__PURE__ */ new Set(["detect_object", "annotate_image", "mask"]);
var POOL_PREFIX = {
attachment: "a",
variant: "v",
picture: "p",
image: "i"
};
function toolName(sourceTool) {
if (typeof sourceTool !== "string") return "";
const parts = sourceTool.split(/[\/,\s]+/).filter(Boolean);
return (parts[parts.length - 1] ?? "").toLowerCase();
}
function isDerivativeToolRecord(record) {
return DERIVATIVE_TOOL_NAMES.has(toolName(record?.sourceTool));
}
function derivativeSourceRef(record) {
const detect = typeof record?.detectSource === "string" ? record.detectSource.trim() : "";
if (detect) return detect;
if (toolName(record?.sourceTool) === "mask") {
const crop = typeof record?.cropSource === "string" ? record.cropSource.trim() : "";
if (crop) return crop;
}
return void 0;
}
function parseNotation(token) {
const m = String(token ?? "").trim().toLowerCase().match(/^([avpi])\s*(\d+)$/);
if (!m) return null;
const pool = m[1] === "a" ? "attachment" : m[1] === "v" ? "variant" : m[1] === "p" ? "picture" : "image";
return { pool, index: Math.max(1, parseInt(m[2], 10)) };
}
function recordIndex(pool, record) {
const raw = pool === "attachment" ? record?.a : pool === "variant" ? record?.v ?? 1 : pool === "picture" ? record?.p : record?.i;
return typeof raw === "number" ? raw : void 0;
}
function poolRecords(state, pool) {
const list = pool === "attachment" ? state.attachments : pool === "variant" ? state.variants : pool === "picture" ? state.pictures : state.images;
return Array.isArray(list) ? list : [];
}
function makeHit(pool, record) {
const index2 = recordIndex(pool, record);
if (index2 === void 0) return null;
return { pool, index: index2, notation: `${POOL_PREFIX[pool]}${index2}`, record };
}
var NAME_FIELDS = ["filename", "originAbs", "preview", "origin", "originalName", "sourceUrl"];
var POOL_ORDER = ["image", "variant", "attachment", "picture"];
function findStateRecord(state, token) {
if (!state) return null;
let raw = String(token ?? "").trim();
if (!raw) return null;
const notation = parseNotation(raw);
if (notation) {
const record = poolRecords(state, notation.pool).find((r) => recordIndex(notation.pool, r) === notation.index);
return record ? makeHit(notation.pool, record) : null;
}
if (/^file:\/\//i.test(raw)) {
try {
raw = decodeURIComponent(new URL(raw).pathname);
} catch {
return null;
}
}
const wantedBase = path22.basename(raw).toLowerCase();
if (!wantedBase) return null;
const wantedAbs = path22.isAbsolute(raw) ? path22.resolve(raw) : void 0;
for (const field of NAME_FIELDS) {
for (const pool of POOL_ORDER) {
const records = [...poolRecords(state, pool)].reverse();
for (const record of records) {
const value = record?.[field];
if (typeof value !== "string" || !value) continue;
const match = path22.basename(value).toLowerCase() === wantedBase || wantedAbs !== void 0 && path22.isAbsolute(value) && path22.resolve(value) === wantedAbs;
if (!match) continue;
const hit = makeHit(pool, record);
if (hit) return hit;
}
}
}
return null;
}
function isFile(p) {
try {
return fs22.statSync(p).isFile();
} catch {
return false;
}
}
function resolveOriginalReference(state, token, maxDepth = 8) {
const first = findStateRecord(state, token);
if (!first) return null;
const chain = [first];
const seen = /* @__PURE__ */ new Set([first.notation]);
let current = first;
for (let depth = 0; depth < maxDepth; depth++) {
const sourceRef = derivativeSourceRef(current.record);
if (!sourceRef) break;
const next = findStateRecord(state, sourceRef);
if (!next) {
const abs = sourceRef.replace(/^file:\/\//i, "");
if (path22.isAbsolute(abs) && isFile(abs)) return { ...current, chain, redirected: chain.length > 1, sourcePath: abs };
break;
}
if (seen.has(next.notation)) break;
seen.add(next.notation);
chain.push(next);
current = next;
}
return { ...current, chain, redirected: chain.length > 1 };
}
function resolveEffectiveSourceToken(state, token) {
const resolved = resolveOriginalReference(state, token);
if (!resolved) return token;
return resolved.sourcePath ?? resolved.notation;
}
// src/helpers/resolveImg2ImgSourceLMStudio.ts
import { promises as fsp4 } from "fs";
import { existsSync as existsSync6, statSync as statSync3 } from "fs";
import { join as join6, basename as basename4, extname as extname2 } from "path";
import os6 from "os";
// src/helpers/resolveLMStudioChatId.ts
import { promises as fsp3 } from "fs";
import { existsSync as existsSync5, statSync as statSync2 } from "fs";
import { join as join5, basename as basename3 } from "path";
function scoreToConfidence(score) {
if (score >= 2) return "high";
if (score === 1) return "medium";
return "low";
}
async function sleep2(ms) {
return new Promise((r) => setTimeout(r, ms));
}
async function resolveActiveLMStudioChatId(opts) {
const retries = typeof opts?.retries === "number" ? opts.retries : 4;
const delayMs = typeof opts?.delayMs === "number" ? opts.delayMs : 200;
const recentSec = typeof opts?.requireRecentMtimeSec === "number" ? opts.requireRecentMtimeSec : 120;
try {
const home = findLMStudioHome();
const convDir = join5(home, "conversations");
if (!existsSync5(convDir)) {
return {
ok: false,
reason: `LM Studio conversations dir not found: ${convDir}`
};
}
let chosenPath = null;
let mtimeMs = 0;
for (let attempt = 0; attempt < Math.max(1, retries); attempt++) {
const convFiles = listConversationFiles(convDir);
if (convFiles.length === 0) {
if (attempt < retries - 1) {
await sleep2(delayMs);
continue;
}
return { ok: false, reason: "No conversation files found" };
}
const withTimes = convFiles.map((p) => {
try {
const s = statSync2(p);
return s.isFile() ? { p, t: s.mtimeMs } : null;
} catch {
return null;
}
}).filter(Boolean);
if (withTimes.length === 0) {
if (attempt < retries - 1) {
await sleep2(delayMs);
continue;
}
return { ok: false, reason: "No readable conversation files" };
}
withTimes.sort((a, b) => b.t - a.t);
chosenPath = withTimes[0].p;
mtimeMs = withTimes[0].t;
try {
const raw = await fsp3.readFile(chosenPath, "utf8");
JSON.parse(raw);
break;
} catch {
if (attempt < retries - 1) {
await sleep2(delayMs);
continue;
}
break;
}
}
if (!chosenPath)
return { ok: false, reason: "Failed to pick conversation" };
const chatId = basename3(chosenPath).replace(/\.conversation\.json$/i, "");
let score = 0;
let reason = [];
if (mtimeMs > 0) {
const ageSec = (Date.now() - mtimeMs) / 1e3;
if (ageSec <= recentSec) {
score += 1;
reason.push(`recent:${Math.round(ageSec)}s`);
} else {
reason.push(`stale:${Math.round(ageSec)}s`);
}
}
try {
const raw = await fsp3.readFile(chosenPath, "utf8");
JSON.parse(raw);
score += 1;
reason.push("parse_ok");
} catch {
reason.push("parse_uncertain");
}
return {
ok: true,
chatId,
filePath: chosenPath,
mtimeMs,
confidence: scoreToConfidence(score),
reason: reason.join(",")
};
} catch (e) {
return { ok: false, reason: e?.message || String(e) };
}
}
// src/helpers/resolveImg2ImgSourceLMStudio.ts
var LM_HOME = join6(os6.homedir(), ".lmstudio");
try {
const h = findLMStudioHome();
if (h && typeof h === "string") LM_HOME = h;
} catch {
}
async function sleep3(ms) {
return new Promise((r) => setTimeout(r, ms));
}
async function waitForStableFile(filePath, {
maxWaitMs = 2400,
pollMs = 120,
stableRounds = 2
} = {}) {
const started = Date.now();
let lastSize = -1;
let sameCount = 0;
while (Date.now() - started <= maxWaitMs) {
try {
const st = statSync3(filePath);
if (!st.isFile()) return { ok: false, reason: "not a file" };
const size = st.size;
if (size > 0 && size === lastSize) {
sameCount++;
if (sameCount >= stableRounds) return { ok: true, size };
} else {
if (lastSize >= 0 && size !== lastSize) {
console.error(
`[LM] waitForStableFile: size changed ${lastSize} -> ${size} for ${filePath}`
);
}
sameCount = 0;
}
lastSize = size;
} catch (e) {
}
await sleep3(pollMs);
}
return { ok: false, reason: "timeout waiting for stable file" };
}
async function ensureFullyDecodable(input) {
try {
const meta = await getSize(input);
const width = typeof meta?.width === "number" ? meta.width : void 0;
const height = typeof meta?.height === "number" ? meta.height : void 0;
return {
ok: true,
buffer: input,
format: meta?.format,
width,
height
};
} catch (e) {
return { ok: false, reason: e?.message || String(e) };
}
}
async function readStableAndDecode(filePath) {
const stable = await waitForStableFile(filePath);
if (!stable.ok) {
console.error(`[LM] readStableAndDecode: ${stable.reason} for ${filePath}`);
}
const maxAttempts = 5;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const buf = await fsp4.readFile(filePath);
const validated = await ensureFullyDecodable(buf);
if (validated.ok) return { ok: true, buffer: buf };
console.error(
`[LM] decode attempt ${attempt} failed for ${filePath}: ${validated.reason}`
);
} catch (e) {
console.error(
`[LM] read attempt ${attempt} failed for ${filePath}: ${e?.message || e}`
);
}
await sleep3(150);
}
return { ok: false, reason: `failed to read/fully-decode: ${filePath}` };
}
function inferMimeFromExt2(name, fallback = "image/png") {
const ext = extname2(name).toLowerCase().replace(/^\./, "");
switch (ext) {
case "jpg":
case "jpeg":
return "image/jpeg";
case "png":
return "image/png";
case "webp":
return "image/webp";
case "gif":
return "image/gif";
case "bmp":
return "image/bmp";
case "tif":
case "tiff":
return "image/tiff";
case "heic":
return "image/heic";
default:
return fallback;
}
}
async function readJSONSafe(p) {
try {
const raw = await fsp4.readFile(p, "utf-8");
return JSON.parse(raw);
} catch {
return null;
}
}
async function resolveImg2ImgSourceLMStudio(opts) {
const options = {
freshOnly: opts?.freshOnly !== void 0 ? opts.freshOnly : false,
freshSeconds: typeof opts?.freshSeconds === "number" ? opts.freshSeconds : 180,
chatId: typeof opts?.chatId === "string" ? opts.chatId : void 0,
explicitAttachmentSource: opts?.explicitAttachmentSource === true,
attachmentIndex: typeof opts?.attachmentIndex === "number" && opts.attachmentIndex >= 1 ? Math.round(opts.attachmentIndex) : void 0
};
try {
const home = findLMStudioHome();
const convDir = join6(home, "conversations");
if (!existsSync6(convDir)) {
console.error(`[LM] Conversations dir not found: ${convDir}`);
return {
ok: false,
client: "lmstudio",
reason: `Conversations dir not found: ${convDir}`
};
}
let chatId = options.chatId || null;
let chosenConv = null;
if (chatId) {
const p = findConversationFileByChatId(chatId, convDir);
if (p) {
chosenConv = p;
} else {
console.error(`[LM] Provided chatId has no conversation file: ${chatId}.conversation.json under ${convDir}`);
}
}
if (!chosenConv) {
const best = await resolveActiveLMStudioChatId().catch(() => null);
if (!best || !best.ok) {
console.error(`[LM] No conversation files found in ${convDir}`);
return {
ok: false,
client: "lmstudio",
reason: "No conversation files found"
};
}
chosenConv = best.filePath;
chatId = best.chatId;
console.error(
`[LM] Heuristic selected conversation: ${chosenConv} (chatId=${chatId})`
);
}
if (!chatId) {
return {
ok: false,
client: "lmstudio",
reason: "Failed to resolve LM Studio chatId"
};
}
const workingDir = join6(home, "working-directories", chatId);
if (options.explicitAttachmentSource) {
const mediaStatePath = join6(workingDir, "chat_media_state.json");
if (existsSync6(mediaStatePath)) {
console.log(`[LM] Checking chat_media_state.json: ${mediaStatePath}`);
const mediaState = await readJSONSafe(mediaStatePath);
if (mediaState && Array.isArray(mediaState.attachments) && mediaState.attachments.length > 0) {
const sortedByA = [...mediaState.attachments].sort(
(a, b) => (b.a ?? 0) - (a.a ?? 0)
);
const highestA = sortedByA[0]?.n ?? mediaState.attachments.length;
const targetA = options.attachmentIndex ?? highestA;
const selectedAtt = mediaState.attachments.find(
(a) => a.a === targetA
);
if (!selectedAtt) {
const availableNs = mediaState.attachments.map((a) => a.a).filter((n) => typeof n === "number").sort((a, b) => a - b);
return {
ok: false,
client: "lmstudio",
reason: `Requested attachment a${targetA} not found. Available: a${availableNs.join(
", a"
)}`
};
}
const lastAtt = selectedAtt;
let imagePath = null;
if (typeof lastAtt.originAbs === "string" && existsSync6(lastAtt.originAbs)) {
imagePath = lastAtt.originAbs;
} else if (typeof lastAtt.filename === "string") {
const copyPath = join6(workingDir, lastAtt.filename);
if (existsSync6(copyPath)) imagePath = copyPath;
}
if (imagePath) {
try {
const read = await readStableAndDecode(imagePath);
if (read.ok) {
const buffer = read.buffer;
const mimeType = inferMimeFromExt2(imagePath, "image/png");
const fileIdentifier = typeof lastAtt.originAbs === "string" && lastAtt.originAbs.trim() ? lastAtt.originAbs : imagePath;
console.log(
`[LM] Resolved attachment from chat_media_state.json: ${fileIdentifier} (path=${imagePath}, a${targetA})`
);
return {
ok: true,
client: "lmstudio",
buffer,
mimeType,
sourceName: basename4(imagePath),
chatId,
fileIdentifier,
originalPath: imagePath,
originalName: typeof lastAtt.originalName === "string" && lastAtt.originalName ? lastAtt.originalName : void 0
};
} else {
console.error(
`[LM] chat_media_state attachment not decodable (${read.reason}), will try conversation.json`
);
}
} catch (e) {
console.error(
`[LM] Failed to read chat_media_state attachment ${imagePath}: ${e.message}`
);
}
} else {
console.error(
`[LM] chat_media_state.json has attachment but file not found: originAbs=${lastAtt.originAbs}, filename=${lastAtt.filename}`
);
}
}
}
}
console.error(
`[LM] No attachment available. Generator must process conversation.json first and write chat_media_state.json.`
);
return {
ok: false,
client: "lmstudio",
reason: "No attachment in chat_media_state.json or pending file. Wait for Generator to process conversation.json."
};
} catch (e) {
return { ok: false, client: "lmstudio", reason: e?.message || String(e) };
}
}
// src/helpers/visionCapabilityPrimer.ts
import { exec } from "child_process";
import { promisify } from "util";
import path23 from "path";
import os7 from "os";
import fs23 from "fs";
async function getAxios2() {
return (await import("axios")).default;
}
var execAsync = promisify(exec);
function appendPluginLog(line) {
try {
ensureLogsDir();
const logFile3 = path23.join(getLogsDir(), getPluginLogFilename());
fs23.appendFileSync(logFile3, `${localTimestamp()} - ${line}
`);
} catch (e) {
console.error(
`[AgentModel] Failed to append to ${getPluginLogFilename()}:`,
e?.message || String(e)
);
}
}
function normalizeLmApiRoot3(baseUrl) {
const u = String(baseUrl || "").trim();
return u.replace(/\/(api\/v1|v1)\/?$/i, "").replace(/\/+$/, "");
}
function buildLmApiAuthHeaders2(apiKey) {
if (typeof apiKey === "string" && apiKey.trim()) {
return { Authorization: `Bearer ${apiKey.trim()}` };
}
return {};
}
function isLocalLmApiBaseUrl(baseUrl) {
const raw = String(baseUrl || "").trim();
if (!raw) return false;
try {
const host = new URL(raw).hostname.toLowerCase();
return host === "localhost" || host === "127.0.0.1" || host === "::1";
} catch {
return false;
}
}
async function findLmsCli() {
const candidates = [
path23.join(os7.homedir(), ".lmstudio", "bin", "lms"),
"/usr/local/bin/lms",
"/opt/homebrew/bin/lms"
];
for (const candidate of candidates) {
try {
await execAsync(`"${candidate}" -h`);
return candidate;
} catch {
}
}
try {
const { stdout } = await execAsync("which lms");
const lmsPath = stdout.trim();
if (lmsPath) {
await execAsync(`"${lmsPath}" -h`);
return lmsPath;
}
} catch {
}
return null;
}
async function isModelInstalled(lmsCli, modelKey, timeoutMs = 5e3) {
const normalizedKey = modelKey.toLowerCase().trim();
try {
const { stdout } = await execAsync(`"${lmsCli}" ls --json`, {
timeout: timeoutMs,
maxBuffer: 10 * 1024 * 1024
});
let models;
try {
models = JSON.parse(stdout);
} catch (parseErr) {
try {
const { stdout: textOut, stderr: textErr } = await execAsync(
`"${lmsCli}" ls`,
{
timeout: Math.max(1e3, timeoutMs),
maxBuffer: 10 * 1024 * 1024
}
);
const haystack = `${textOut}
${textErr}`.toLowerCase();
if (haystack.includes(normalizedKey)) {
return { installed: true, modelInfo: { modelKey } };
}
return {
installed: false,
error: `Failed to parse lms ls --json output (fallback used): ${parseErr?.message || parseErr}`
};
} catch (fallbackErr) {
return {
installed: false,
error: `Failed to parse lms ls --json output and fallback ls failed: ${parseErr?.message || parseErr} / ${fallbackErr?.message || String(fallbackErr)}`
};
}
}
if (!Array.isArray(models)) {
return {
installed: false,
error: "lms ls --json returned non-array"
};
}
const found = models.find((m) => {
const key = String(m?.modelKey || "").toLowerCase().trim();
const path34 = String(m?.path || "").toLowerCase().trim();
const keyBase = key.split("@")[0]?.trim() || key;
return key === normalizedKey || keyBase === normalizedKey || path34 === normalizedKey;
});
if (found) {
return {
installed: true,
modelInfo: {
modelKey: found.path || found.modelKey,
displayName: found.displayName,
sizeBytes: found.sizeBytes,
vision: found.vision === true
}
};
}
return { installed: false };
} catch (e) {
return {
installed: false,
error: e?.message || String(e)
};
}
}
async function isModelLoaded(lmsCli, identifier, timeoutMs = 5e3) {
const normalizedId = identifier.toLowerCase().trim();
try {
const { stdout } = await execAsync(`"${lmsCli}" ps --json`, {
timeout: timeoutMs
});
let instances;
try {
instances = JSON.parse(stdout);
} catch {
return false;
}
if (!Array.isArray(instances)) {
return false;
}
return instances.some((inst) => {
const instId = String(inst?.identifier || "").toLowerCase().trim();
return instId === normalizedId;
});
} catch {
return false;
}
}
async function checkLmsLoadAmbiguity(lmsCli, modelKey, timeoutMs = 5e3) {
const normalizedKey = modelKey.toLowerCase().trim();
try {
const { stdout } = await execAsync(`"${lmsCli}" ls "${modelKey}" --json`, {
timeout: timeoutMs,
maxBuffer: 10 * 1024 * 1024
});
const models = JSON.parse(stdout);
if (!Array.isArray(models)) return { ok: true };
const matches = models.map((model) => {
const path34 = String(model?.path || "").trim();
if (path34) return path34;
const key = String(model?.modelKey || model?.key || "").trim();
return key.split("@")[0]?.trim() || key;
}).filter(Boolean);
const uniqueMatches = Array.from(new Set(matches));
if (uniqueMatches.length <= 1) return { ok: true };
const exactMatches = uniqueMatches.filter(
(key) => key.toLowerCase().trim() === normalizedKey
);
if (exactMatches.length === 1 && uniqueMatches.every((key) => key.toLowerCase().trim() === normalizedKey)) {
return { ok: true };
}
const listed = uniqueMatches.map((key) => `- ${key}`).join("\n");
const error = `lms load would be ambiguous for '${modelKey}'. Matching models:
${listed}`;
return {
ok: false,
error,
userFacingError: `**Vision Attachment Support:**
The configured primer model \`${modelKey}\` is ambiguous for \`lms load\`.
Matching models:
${listed}
Remove or rename the conflicting model, or configure a model key that \`lms load\` resolves without prompting.`
};
} catch (error) {
console.warn(
"[VisionPrimer] Could not preflight lms load ambiguity:",
error?.message || error
);
return { ok: true };
}
}
async function checkVisionPrimerStatus(config) {
const { modelKey, identifier = "vision-capability-priming" } = config;
console.debug("[VisionPrimer] Quick status check...");
const lmsCli = await findLmsCli();
if (!lmsCli) {
console.warn("[VisionPrimer] lms CLI not found (infrastructure error, silent)");
return {
lmsCli: null,
installed: false,
alreadyLoaded: false,
needsLoad: false,
infrastructureError: true,
error: "lms CLI not found. Is LM Studio installed?"
};
}
console.debug("[VisionPrimer] Found lms CLI:", lmsCli);
const installResult = await isModelInstalled(lmsCli, modelKey, 5e3);
if (installResult.error) {
console.warn("[VisionPrimer] Installation check failed:", installResult.error);
return {
lmsCli,
installed: false,
alreadyLoaded: false,
needsLoad: false,
infrastructureError: true,
error: `Installation check failed: ${installResult.error}`
};
}
if (!installResult.installed) {
const userMsg = `**Vision Attachment Support:**
The vision-capability-priming model \`${modelKey}\` is not installed.
This model enables image attachments in the chat UI. To install it:
1. Open LM Studio
2. Search for \`${modelKey}\`
3. Download the model
Without this model, you can still use text prompts for image generation.`;
console.warn(`[VisionPrimer] Model not installed: ${modelKey}`);
return {
lmsCli,
installed: false,
alreadyLoaded: false,
needsLoad: false,
notInstalled: true,
userFacingError: userMsg,
error: `Model '${modelKey}' is not installed locally.`
};
}
console.debug(`[VisionPrimer] Model installed: ${modelKey}`);
const loaded = await isModelLoaded(lmsCli, identifier, 5e3);
if (loaded) {
console.debug(`[VisionPrimer] Model already loaded with identifier: ${identifier}`);
return {
lmsCli,
installed: true,
alreadyLoaded: true,
needsLoad: false
};
}
console.debug(`[VisionPrimer] Model installed but not loaded, needs load`);
return {
lmsCli,
installed: true,
alreadyLoaded: false,
needsLoad: true
};
}
async function loadVisionPrimerModel(lmsCli, config) {
const startTs = Date.now();
const {
modelKey,
contextLength = 512,
gpuMode = "off",
ttlSeconds = 7200,
identifier = "vision-capability-priming"
} = config;
if (!lmsCli) {
const error = "lms CLI not found. The Vision Primer requires lms to load the attachment primer with the configured identifier.";
console.error("[VisionPrimer]", error);
return {
ok: false,
infrastructureError: true,
error
};
}
const gpuArg = gpuMode === "off" ? "--gpu off" : gpuMode === "max" ? "--gpu max" : `--gpu ${gpuMode}`;
const ambiguity = await checkLmsLoadAmbiguity(lmsCli, modelKey, 5e3);
if (!ambiguity.ok) {
console.error("[VisionPrimer]", ambiguity.error);
return {
ok: false,
loadFailed: true,
userFacingError: ambiguity.userFacingError,
error: ambiguity.error
};
}
const cmd = [
`"${lmsCli}"`,
"load",
`"${modelKey}"`,
`--context-length ${contextLength}`,
gpuArg,
`--ttl ${ttlSeconds}`,
`--identifier "${identifier}"`
].join(" ");
console.debug("[VisionPrimer] Running:", cmd);
try {
const { stdout, stderr } = await execAsync(cmd, {
timeout: 12e4
});
const output = stdout + stderr;
const loadTimeSec = Math.round((Date.now() - startTs) / 1e3 * 100) / 100;
let size;
const rawSizeMatch = output.match(/\(([0-9.]+)\s*(GiB|MiB|KiB|GB|MB|KB)?\)/i);
if (rawSizeMatch) {
const numVal = parseFloat(rawSizeMatch[1]);
const unit = (rawSizeMatch[2] || "GiB").toUpperCase();
let bytes;
if (unit.startsWith("KI")) bytes = numVal * 1024;
else if (unit.startsWith("MI")) bytes = numVal * 1024 * 1024;
else if (unit.startsWith("GI")) bytes = numVal * 1024 * 1024 * 1024;
else if (unit === "KB") bytes = numVal * 1e3;
else if (unit === "MB") bytes = numVal * 1e3 * 1e3;
else if (unit === "GB") bytes = numVal * 1e3 * 1e3 * 1e3;
else bytes = numVal * 1024 * 1024 * 1024;
size = (bytes / 1e3 / 1e3 / 1e3).toFixed(2) + " GB";
}
const nowLoaded = await isModelLoaded(lmsCli, identifier, 5e3);
if (!nowLoaded) {
const error = `lms load completed, but '${identifier}' is not present in lms ps --json.`;
console.error("[VisionPrimer]", error);
return {
ok: false,
loadFailed: true,
userFacingError: `**Vision Attachment Support:**
The vision-capability-priming model \`${modelKey}\` load command completed, but readiness verification failed.
Error: ${error}`,
error
};
}
console.debug(`[VisionPrimer] \u2713 Model loaded in ${loadTimeSec}s`);
if (size) console.debug(`[VisionPrimer] Size: ${size}`);
return {
ok: true,
alreadyLoaded: false,
identifier,
size,
loadTimeSec
};
} catch (e) {
const error = e.stderr || e.message || String(e);
console.debug("[VisionPrimer] Load command failed, checking if model is now loaded anyway...");
const nowLoaded = await isModelLoaded(lmsCli, identifier, 5e3);
if (nowLoaded) {
console.debug("[VisionPrimer] Model is now loaded (concurrent load succeeded), treating as success");
return {
ok: true,
alreadyLoaded: true,
identifier
};
}
const userMsg = `**Vision Attachment Support:**
The vision-capability-priming model \`${modelKey}\` could not be loaded.
Error: ${error}
Please check LM Studio logs for details. Without this model, you can still use text prompts for image generation.`;
console.error("[VisionPrimer] Failed to load model:", error);
return {
ok: false,
loadFailed: true,
userFacingError: userMsg,
error: `Failed to load model: ${error}`
};
}
}
async function primeVisionCapability(config) {
const TOTAL_TIMEOUT_MS = 15e3;
const startTs = Date.now();
const remainingMs = () => Math.max(0, TOTAL_TIMEOUT_MS - (Date.now() - startTs));
const {
modelKey,
contextLength = 512,
gpuMode = "off",
ttlSeconds = 7200,
identifier = "vision-capability-priming"
} = config;
console.debug("[VisionPrimer] Starting vision capability priming...");
console.debug("[VisionPrimer] Config:", {
modelKey,
contextLength,
gpuMode,
ttlSeconds,
identifier
});
const lmsCli = await findLmsCli();
if (!lmsCli) {
console.warn("[VisionPrimer] lms CLI not found (infrastructure error, silent)");
return {
ok: false,
infrastructureError: true,
error: "lms CLI not found. Is LM Studio installed?"
};
}
console.debug("[VisionPrimer] Found lms CLI:", lmsCli);
if (remainingMs() < 1e3) {
console.warn("[VisionPrimer] Timeout before installation check");
return {
ok: false,
infrastructureError: true,
error: "Timeout before installation check"
};
}
const installResult = await isModelInstalled(lmsCli, modelKey, Math.min(5e3, remainingMs()));
if (installResult.error) {
console.warn("[VisionPrimer] Installation check failed:", installResult.error);
return {
ok: false,
infrastructureError: true,
error: `Installation check failed: ${installResult.error}`
};
}
if (!installResult.installed) {
const userMsg = `**Vision Attachment Support:**
The vision-capability-priming model \`${modelKey}\` is not installed.
This model enables image attachments in the chat UI. To install it:
1. Open LM Studio
2. Search for \`${modelKey}\`
3. Download the model
Without this model, you can still use text prompts for image generation.`;
console.warn(`[VisionPrimer] Model not installed: ${modelKey}`);
return {
ok: false,
notInstalled: true,
userFacingError: userMsg,
error: `Model '${modelKey}' is not installed locally.`
};
}
console.debug(`[VisionPrimer] Model installed: ${modelKey}`);
if (remainingMs() < 1e3) {
console.warn("[VisionPrimer] Timeout before loaded check");
return {
ok: false,
infrastructureError: true,
error: "Timeout before loaded check"
};
}
const loaded = await isModelLoaded(lmsCli, identifier, Math.min(5e3, remainingMs()));
if (loaded) {
console.debug(
`[VisionPrimer] Model already loaded with identifier: ${identifier}`
);
return {
ok: true,
alreadyLoaded: true,
identifier
};
}
if (remainingMs() < 2e3) {
console.warn("[VisionPrimer] Insufficient time remaining to load model");
return {
ok: false,
infrastructureError: true,
error: "Insufficient time remaining to load model"
};
}
const gpuArg = gpuMode === "off" ? "--gpu off" : gpuMode === "max" ? "--gpu max" : `--gpu ${gpuMode}`;
const ambiguity = await checkLmsLoadAmbiguity(lmsCli, modelKey, Math.min(5e3, remainingMs()));
if (!ambiguity.ok) {
console.error("[VisionPrimer]", ambiguity.error);
return {
ok: false,
loadFailed: true,
userFacingError: ambiguity.userFacingError,
error: ambiguity.error
};
}
const cmd = [
`"${lmsCli}"`,
"load",
`"${modelKey}"`,
`--context-length ${contextLength}`,
gpuArg,
`--ttl ${ttlSeconds}`,
`--identifier "${identifier}"`
].join(" ");
console.debug("[VisionPrimer] Running:", cmd);
try {
const { stdout, stderr } = await execAsync(cmd, {
timeout: remainingMs()
});
const output = stdout + stderr;
const loadTimeSec = Math.round((Date.now() - startTs) / 1e3 * 100) / 100;
let size;
const rawSizeMatch = output.match(/\(([0-9.]+)\s*(GiB|MiB|KiB|GB|MB|KB)?\)/i);
if (rawSizeMatch) {
const numVal = parseFloat(rawSizeMatch[1]);
const unit = (rawSizeMatch[2] || "GiB").toUpperCase();
let bytes;
if (unit.startsWith("KI")) bytes = numVal * 1024;
else if (unit.startsWith("MI")) bytes = numVal * 1024 * 1024;
else if (unit.startsWith("GI")) bytes = numVal * 1024 * 1024 * 1024;
else if (unit === "KB") bytes = numVal * 1e3;
else if (unit === "MB") bytes = numVal * 1e3 * 1e3;
else if (unit === "GB") bytes = numVal * 1e3 * 1e3 * 1e3;
else bytes = numVal * 1024 * 1024 * 1024;
size = (bytes / 1e3 / 1e3 / 1e3).toFixed(2) + " GB";
}
const nowLoaded = await isModelLoaded(lmsCli, identifier, Math.min(5e3, remainingMs()));
if (!nowLoaded) {
const error = `lms load completed, but '${identifier}' is not present in lms ps --json.`;
console.error("[VisionPrimer]", error);
return {
ok: false,
loadFailed: true,
userFacingError: `**Vision Attachment Support:**
The vision-capability-priming model \`${modelKey}\` load command completed, but readiness verification failed.
Error: ${error}`,
error
};
}
console.debug(`[VisionPrimer] \u2713 Model loaded in ${loadTimeSec}s`);
if (size) console.debug(`[VisionPrimer] Size: ${size}`);
return {
ok: true,
alreadyLoaded: false,
identifier,
size,
loadTimeSec
};
} catch (e) {
const error = e.stderr || e.message || String(e);
const userMsg = `**Vision Attachment Support:**
The vision-capability-priming model \`${modelKey}\` could not be loaded.
Error: ${error}
Please check LM Studio logs for details. Without this model, you can still use text prompts for image generation.`;
console.error("[VisionPrimer] Failed to load model:", error);
return {
ok: false,
loadFailed: true,
userFacingError: userMsg,
error: `Failed to load model: ${error}`
};
}
}
async function injectLastUsedModelIntoNewestChat(config) {
const startTs = Date.now();
try {
const resolved = await resolveActiveLMStudioChatId();
if (!resolved.ok) {
console.debug("[VisionPrimer] Could not resolve active chat:", resolved.reason);
return;
}
const newestFile = path23.basename(resolved.filePath);
const filePath = resolved.filePath;
const raw = await fs23.promises.readFile(filePath, "utf8");
const conversation = JSON.parse(raw);
const isActive = Array.isArray(conversation.plugins) && conversation.plugins.includes(config.pluginId);
if (!isActive) {
console.debug(`[VisionPrimer] Not active in ${newestFile}, skipping`);
return;
}
if (conversation.lastUsedModel) {
console.debug(
`[VisionPrimer] lastUsedModel already exists in ${newestFile}:`,
conversation.lastUsedModel.identifier || conversation.lastUsedModel
);
return;
}
const runtimeIdentifier = config.identifier ?? config.modelKey;
const fields = [];
if (typeof config.contextLength === "number" && config.contextLength > 0) {
fields.push({ key: "llm.load.contextLength", value: config.contextLength });
}
if (typeof config.gpuOffloadRatio === "number") {
fields.push({
key: "llm.load.llama.acceleration.offloadRatio",
value: config.gpuOffloadRatio
});
}
conversation.lastUsedModel = {
indexedModelIdentifier: config.modelKey,
identifier: runtimeIdentifier,
instanceLoadTimeConfig: { fields },
instanceOperationTimeConfig: { fields: [] }
};
await fs23.promises.writeFile(filePath, JSON.stringify(conversation, null, 2), "utf8");
const now = /* @__PURE__ */ new Date();
await fs23.promises.utimes(filePath, now, now);
console.debug(
`[VisionPrimer] \u2713 Injected lastUsedModel (model=${config.modelKey}, id=${runtimeIdentifier}) into ${newestFile} (${Date.now() - startTs}ms)`
);
setTimeout(async () => {
try {
const now2 = /* @__PURE__ */ new Date();
await fs23.promises.utimes(filePath, now2, now2);
} catch {
}
}, 2e3);
} catch (e) {
console.warn("[VisionPrimer] Failed to process newest chat:", e.message || e);
}
}
var _lastWrittenModel = null;
async function updateLastUsedModelForAgentModel(config) {
const { modelKey, instanceId, contextLength, gpuOffloadRatio, pluginId, baseUrl, chatId } = config;
const effectiveInstanceId = instanceId ?? modelKey;
if (typeof baseUrl === "string" && baseUrl.trim()) {
try {
const host = new URL(baseUrl).hostname.toLowerCase();
const isLocal = host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
if (!isLocal) {
console.debug(
`[VisionPrimer] Non-local baseUrl (${host}) \u2014 skipping lastUsedModel update`
);
return { ok: true, alreadyCorrect: true };
}
} catch {
}
}
if (_lastWrittenModel !== null && _lastWrittenModel.modelKey === modelKey && _lastWrittenModel.instanceId === effectiveInstanceId && _lastWrittenModel.contextLength === contextLength) {
console.debug(
`[VisionPrimer] lastUsedModel cache hit \u2014 skipping SSOT write (${modelKey})`
);
return { ok: true, alreadyCorrect: true };
}
const conversationsDir = path23.join(findLMStudioHome(), "conversations");
let targetFile = null;
let filePath;
let resolvedChatId = void 0;
if (chatId) {
const found = findConversationFileByChatId(chatId, conversationsDir);
if (!found) {
return { ok: false, error: `Conversation file for chatId ${chatId} not found` };
}
filePath = found;
targetFile = path23.basename(found);
resolvedChatId = chatId;
console.debug("[VisionPrimer] Using SDK chatId:", chatId);
} else {
const resolved = await resolveActiveLMStudioChatId();
if (!resolved.ok) {
return { ok: false, error: `Could not resolve active chat: ${resolved.reason}` };
}
filePath = resolved.filePath;
targetFile = path23.basename(resolved.filePath);
resolvedChatId = resolved.chatId;
}
console.debug("[VisionPrimer] Updating lastUsedModel to agent model:", {
modelKey,
instanceId: effectiveInstanceId,
contextLength,
targetFile,
chatSource: chatId ? "sdk" : "resolveActiveLMStudioChatId"
});
async function verifyWrittenValues(fp) {
try {
const raw = await fs23.promises.readFile(fp, "utf8");
const data = JSON.parse(raw);
if (data.lastUsedModel?.indexedModelIdentifier !== modelKey) {
console.debug(
`[VisionPrimer] Verify FAILED: indexedModelIdentifier is ${JSON.stringify(data.lastUsedModel?.indexedModelIdentifier)}, expected ${modelKey}`
);
return false;
}
if (data.lastUsedModel?.identifier !== effectiveInstanceId) {
console.debug(
`[VisionPrimer] Verify FAILED: identifier is ${JSON.stringify(data.lastUsedModel?.identifier)}, expected ${effectiveInstanceId}`
);
return false;
}
if (contextLength !== void 0) {
const actualCtx = data.lastUsedModel?.instanceLoadTimeConfig?.fields?.find(
(f) => f.key === "llm.load.contextLength"
)?.value;
if (actualCtx !== contextLength) {
console.debug(
`[VisionPrimer] Verify FAILED: contextLength is ${JSON.stringify(actualCtx)}, expected ${contextLength}`
);
return false;
}
}
return true;
} catch (e) {
console.debug(`[VisionPrimer] Verify read failed:`, e.message || e);
return false;
}
}
async function writeOnce() {
const raw = await fs23.promises.readFile(filePath, "utf8");
const conversation = JSON.parse(raw);
if (pluginId) {
const isActive = Array.isArray(conversation.plugins) && conversation.plugins.includes(pluginId);
if (!isActive) {
console.debug(
`[VisionPrimer] We're not active in chat (${targetFile}), skipping update`
);
throw new Error("Plugin not active in this chat");
}
}
const existingModel = conversation.lastUsedModel;
if (existingModel?.indexedModelIdentifier === modelKey && existingModel?.identifier === effectiveInstanceId) {
const existingCtx = existingModel?.instanceLoadTimeConfig?.fields?.find(
(f) => f.key === "llm.load.contextLength"
)?.value;
if (contextLength === void 0 || existingCtx === contextLength) {
_lastWrittenModel = { modelKey, instanceId: effectiveInstanceId, contextLength };
console.debug(
`[VisionPrimer] lastUsedModel already correct for ${modelKey}, skipping (cache populated)`
);
return true;
}
}
const fields = [];
if (typeof contextLength === "number" && contextLength > 0) {
fields.push({ key: "llm.load.contextLength", value: contextLength });
}
if (typeof gpuOffloadRatio !== void 0 && typeof gpuOffloadRatio === "number") {
fields.push({
key: "llm.load.llama.acceleration.offloadRatio",
value: gpuOffloadRatio
});
}
conversation.lastUsedModel = {
indexedModelIdentifier: modelKey,
identifier: effectiveInstanceId,
instanceLoadTimeConfig: { fields },
instanceOperationTimeConfig: { fields: [] }
};
await fs23.promises.writeFile(
filePath,
JSON.stringify(conversation, null, 2),
"utf8"
);
const now = /* @__PURE__ */ new Date();
await fs23.promises.utimes(filePath, now, now);
return true;
}
try {
await new Promise((resolve) => setTimeout(resolve, 400));
const maxAttempts = 3;
let verified = false;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
await writeOnce();
await new Promise((resolve) => setTimeout(resolve, 100));
const ok = await verifyWrittenValues(filePath);
if (ok) {
verified = true;
break;
}
if (attempt < maxAttempts) {
const backoffMs = 300 * attempt;
console.debug(
`[VisionPrimer] Write not persisted yet (attempt ${attempt}/${maxAttempts}), retrying in ${backoffMs}ms`
);
await new Promise((resolve) => setTimeout(resolve, backoffMs));
}
}
if (!verified) {
try {
const finalRaw = await fs23.promises.readFile(filePath, "utf8");
const finalData = JSON.parse(finalRaw);
console.warn(
`[VisionPrimer] \u2717 Could not verify write after ${maxAttempts} attempts. File has indexedModelIdentifier=${JSON.stringify(finalData.lastUsedModel?.indexedModelIdentifier)}, contextLength=${JSON.stringify(finalData.lastUsedModel?.instanceLoadTimeConfig?.fields?.find((f) => f.key === "llm.load.contextLength")?.value)}. Expected ${modelKey} / ctx=${contextLength}`
);
} catch {
console.warn(
`[VisionPrimer] \u2717 Could not verify write after ${maxAttempts} attempts and cannot read final state`
);
}
return { ok: false, error: `Write verification failed after ${maxAttempts} attempts`, chatId: resolvedChatId };
}
_lastWrittenModel = { modelKey, instanceId: effectiveInstanceId, contextLength };
console.debug(
`[VisionPrimer] \u2713 Verified lastUsedModel update to agent model: ${modelKey} (ctx=${contextLength ?? "default"}) in ${targetFile}`
);
setTimeout(async () => {
try {
const now2 = /* @__PURE__ */ new Date();
await fs23.promises.utimes(filePath, now2, now2);
console.debug(`[VisionPrimer] \u2713 Second touch for agent model update`);
} catch {
}
}, 1500);
return { ok: true, chatId: resolvedChatId };
} catch (e) {
if (e.message === "Plugin not active in this chat") {
return { ok: false, error: e.message, chatId: resolvedChatId };
}
console.warn(
"[VisionPrimer] Failed to update lastUsedModel:",
e.message || e
);
return { ok: false, error: e.message || String(e), chatId: resolvedChatId };
}
}
async function unloadVisionPrimer(identifier = "vision-capability-priming", opts) {
if (opts?.baseUrl) {
const apiRoot = normalizeLmApiRoot3(opts.baseUrl);
const unloadUrl = `${apiRoot}/api/v1/models/unload`;
try {
const axios2 = await getAxios2();
await axios2.post(
unloadUrl,
{ instance_id: identifier },
{
timeout: 3e4,
headers: {
"Content-Type": "application/json",
...buildLmApiAuthHeaders2(opts.apiKey)
}
}
);
console.debug(`[VisionPrimer] \u2713 Unloaded model via API: ${identifier}`);
return true;
} catch (e) {
const resp = e?.response;
const respText = resp?.data ? typeof resp.data === "string" ? resp.data : JSON.stringify(resp.data) : void 0;
console.warn(
"[VisionPrimer] Failed to unload via API:",
respText || e?.message || e
);
return false;
}
}
const lmsCli = await findLmsCli();
if (!lmsCli) return false;
try {
await execAsync(`"${lmsCli}" unload "${identifier}"`);
console.debug(`[VisionPrimer] \u2713 Unloaded model: ${identifier}`);
return true;
} catch (e) {
console.warn("[VisionPrimer] Failed to unload:", e.message || e);
return false;
}
}
async function ensureAgentModelLoaded(config) {
const startTs = Date.now();
const { modelKey } = config;
appendPluginLog(
`[AgentModel] ensureAgentModelLoaded start modelKey=${String(
modelKey
)} baseUrl=${String(config.baseUrl || "").trim() || "(missing)"}`
);
console.log("[AgentModel] Ensuring agent model is loaded...");
console.log("[AgentModel] Model:", modelKey);
const formatVisionModelsTable = (models) => {
const rows = models.map((m) => {
const id = String(m?.key || m?.id || "?");
const name = String(m?.display_name || id);
const params = String(m?.params_string || "?");
const size = m?.size_bytes ? (Number(m.size_bytes) / 1e3 / 1e3 / 1e3).toFixed(2) + " GB" : "?";
const caps2 = m?.capabilities;
const hasVision = caps2?.vision === true;
const hasToolUse = caps2?.trained_for_tool_use === true;
const visionMark = hasVision ? "\u2713" : "";
const toolsMark = hasToolUse ? "\u2713" : "";
const PRIMER_INSTANCE_ID = "vision-capability-priming";
const loadedAsId = Array.isArray(m?.loaded_instances) ? m.loaded_instances.some((inst) => {
const instId = typeof inst === "string" ? inst : typeof inst?.id === "string" ? inst.id : void 0;
return typeof instId === "string" && instId === id;
}) : false;
const loadedAsPrimer = Array.isArray(m?.loaded_instances) ? m.loaded_instances.some((inst) => {
const instId = typeof inst === "string" ? inst : typeof inst?.id === "string" ? inst.id : void 0;
return typeof instId === "string" && instId === PRIMER_INSTANCE_ID;
}) : false;
const status = loadedAsId ? "\u2713" : loadedAsPrimer ? "primer" : "";
return `| ${id} | ${name} | ${params} | ${size} | ${visionMark} | ${toolsMark} | ${status} |`;
});
return `
**Vision Models:**
| ID | Name | Params | Size | Vision | Tools | Loaded |
|---|---|---|---|---|---|---|
${rows.join(
"\n"
)}
`;
};
if (!config.baseUrl) {
return {
ok: false,
error: "Configuration error: Missing baseUrl for Model API check."
};
}
const requestedKeyRaw = String(modelKey || "").trim();
const requestedKey = requestedKeyRaw.toLowerCase();
if (!requestedKeyRaw) {
return { ok: false, error: "Configuration error: Empty model key." };
}
if (requestedKey === "vision-capability-priming") {
return {
ok: false,
error: "Invalid agent model: 'vision-capability-priming' is an infrastructure primer model and must not be used for chat orchestration."
};
}
const apiRoot = normalizeLmApiRoot3(config.baseUrl);
const modelsUrl = `${apiRoot}/api/v1/models`;
const loadUrl = `${apiRoot}/api/v1/models/load`;
const headers = {};
if (typeof config.apiKey === "string" && config.apiKey.trim()) {
headers.Authorization = `Bearer ${config.apiKey.trim()}`;
}
let foundModel;
let visionModels = [];
try {
console.debug(`[AgentModel] Checking status via ${modelsUrl}`);
const response = await (await getAxios2()).get(modelsUrl, {
timeout: 5e3,
headers
});
const data = response.data;
const models = Array.isArray(data) ? data : Array.isArray(data?.models) ? data.models : Array.isArray(data?.data) ? data.data : [];
if (data?.error && models.length === 0) {
throw new Error(String(data.error));
}
visionModels = models.filter((m) => m?.capabilities?.vision === true);
foundModel = models.find((m) => {
const key = String(m?.key || "").trim();
return key && key.toLowerCase() === requestedKey;
});
if (foundModel) {
const li = Array.isArray(foundModel?.loaded_instances) ? foundModel.loaded_instances : [];
const ids = li.map((inst) => {
if (typeof inst === "string") return inst;
if (inst && typeof inst.id === "string") return inst.id;
return void 0;
}).filter((v) => typeof v === "string").slice(0, 5).join(", ");
appendPluginLog(
`[AgentModel] status key=${requestedKeyRaw} found=true loaded_instances=${li.length}${ids ? ` ids=[${ids}]` : ""}`
);
} else {
appendPluginLog(`[AgentModel] status key=${requestedKeyRaw} found=false`);
}
} catch (e) {
const resp = e?.response;
const respText = resp?.data ? typeof resp.data === "string" ? resp.data : JSON.stringify(resp.data) : void 0;
const msg = respText || e?.message || String(e);
appendPluginLog(
`[AgentModel] status query failed url=${modelsUrl} error=${msg}`
);
const standardModelsUrl = `${apiRoot}/v1/models`;
appendPluginLog(
`[AgentModel] falling back to standard models endpoint: ${standardModelsUrl}`
);
try {
const fallbackResp = await (await getAxios2()).get(standardModelsUrl, {
timeout: 5e3,
headers
});
const fallbackData = fallbackResp.data;
const fallbackModels = Array.isArray(fallbackData) ? fallbackData : Array.isArray(fallbackData?.models) ? fallbackData.models : Array.isArray(fallbackData?.data) ? fallbackData.data : [];
const foundInFallback = fallbackModels.find((m) => {
const id = String(m?.id || m?.key || "").trim().toLowerCase();
if (!id) return false;
return id === requestedKey || id.endsWith("/" + requestedKey);
});
if (!foundInFallback) {
appendPluginLog(
`[AgentModel] model not found in standard endpoint: ${requestedKeyRaw}`
);
return {
ok: false,
error: `Model '${requestedKeyRaw}' not found on server (tried ${modelsUrl} and ${standardModelsUrl}).`
};
}
if (!isKnownModel(requestedKeyRaw)) {
appendPluginLog(
`[AgentModel] model not in capabilities.ts, cannot verify vision support: ${requestedKeyRaw}`
);
return {
ok: false,
error: `Model '${requestedKeyRaw}' is not listed in the plugin's capabilities registry. Add it to capabilities.ts to enable non-LM-Studio server support.`
};
}
const fallbackCaps = detectCapabilities(requestedKeyRaw);
if (!fallbackCaps.supportsVision) {
appendPluginLog(
`[AgentModel] model not vision-capable per capabilities.ts: ${requestedKeyRaw}`
);
return {
ok: false,
error: `Model '${requestedKeyRaw}' is not vision-capable (per capabilities.ts).`
};
}
appendPluginLog(
`[AgentModel] fallback ok (capabilities.ts vision=true): ${requestedKeyRaw}`
);
return {
ok: true,
alreadyLoaded: true,
identifier: requestedKeyRaw,
loadedInstanceId: requestedKeyRaw
};
} catch (fallbackErr) {
const fallbackMsg = fallbackErr?.message || String(fallbackErr);
appendPluginLog(
`[AgentModel] standard fallback also failed: ${fallbackMsg}`
);
return {
ok: false,
error: `Could not query model list via API (${modelsUrl}): ${msg}`
};
}
}
const modelTable = visionModels.length > 0 ? formatVisionModelsTable(visionModels) : "\n\n(No vision-capable models found with capabilities { vision: true }.)";
if (!foundModel) {
appendPluginLog(`[AgentModel] model not found: ${requestedKeyRaw}`);
return {
ok: false,
error: `Model '${requestedKeyRaw}' not found on server.${modelTable}`
};
}
const caps = foundModel?.capabilities;
const isSuitable = caps?.vision === true;
if (!isSuitable) {
appendPluginLog(
`[AgentModel] model not suitable (no vision): ${requestedKeyRaw}`
);
return {
ok: false,
error: `Model '${requestedKeyRaw}' is not suitable (requires vision).${modelTable}`
};
}
const loadedInstances = Array.isArray(foundModel?.loaded_instances) ? foundModel.loaded_instances : [];
const getInstanceId = (inst) => {
if (typeof inst === "string") return inst;
if (inst && typeof inst.id === "string") return inst.id;
return void 0;
};
const getInstanceContextLength = (inst) => {
if (!inst || typeof inst === "string") return void 0;
const cfg = inst?.config;
const cfgLen = typeof cfg?.context_length === "number" ? cfg.context_length : typeof cfg?.contextLength === "number" ? cfg.contextLength : void 0;
if (typeof cfgLen === "number" && Number.isFinite(cfgLen)) return cfgLen;
const v = typeof inst.context_length === "number" ? inst.context_length : typeof inst.contextLength === "number" ? inst.contextLength : void 0;
return typeof v === "number" && Number.isFinite(v) ? v : void 0;
};
const loadedInstance = loadedInstances.find((inst) => {
const instId = getInstanceId(inst);
return typeof instId === "string" && instId.toLowerCase() === requestedKey;
});
const fallbackLoadedInstance = loadedInstance ?? (loadedInstances.length > 0 ? loadedInstances[0] : void 0);
const alreadyLoaded = loadedInstances.length > 0;
if (alreadyLoaded) {
if (!loadedInstance && loadedInstances.length > 0) {
const ids = loadedInstances.map((inst) => getInstanceId(inst)).filter((v) => typeof v === "string").slice(0, 5).join(", ");
appendPluginLog(
`[AgentModel] alreadyLoaded=true via loaded_instances.length (${loadedInstances.length}) but no exact id match. requestedKey=${requestedKeyRaw} ids=[${ids}]`
);
}
console.log(
`[AgentModel] Model already loaded (via API): ${requestedKeyRaw}`
);
appendPluginLog(`[AgentModel] already loaded: ${requestedKeyRaw}`);
return {
ok: true,
alreadyLoaded: true,
identifier: requestedKeyRaw,
loadedInstanceId: getInstanceId(fallbackLoadedInstance) ?? requestedKeyRaw,
loadedInstanceContextLength: getInstanceContextLength(
fallbackLoadedInstance
),
maxContextLength: typeof foundModel?.max_context_length === "number" ? foundModel.max_context_length : typeof foundModel?.maxContextLength === "number" ? foundModel.maxContextLength : void 0,
size: foundModel?.size_bytes ? (Number(foundModel.size_bytes) / 1e3 / 1e3 / 1e3).toFixed(2) + " GB" : void 0
};
}
console.log("[AgentModel] Loading model via API:", requestedKeyRaw);
appendPluginLog(`[AgentModel] loading via API: ${requestedKeyRaw}`);
try {
const loadResp = await (await getAxios2()).post(
loadUrl,
{
model: requestedKeyRaw,
echo_load_config: true
},
{
timeout: 3e5,
headers: {
"Content-Type": "application/json",
...headers
}
}
);
const loadData = loadResp.data;
const loadTimeSecApi = typeof loadData?.load_time_seconds === "number" ? loadData.load_time_seconds : void 0;
const loadTimeSecLocal = Math.round((Date.now() - startTs) / 1e3 * 100) / 100;
const loadTimeSec = loadTimeSecApi ?? loadTimeSecLocal;
let loadedInstanceId;
let loadedInstanceContextLength;
let maxContextLength;
try {
const response2 = await (await getAxios2()).get(modelsUrl, {
timeout: 5e3,
headers
});
const data2 = response2.data;
const models2 = Array.isArray(data2) ? data2 : Array.isArray(data2?.models) ? data2.models : Array.isArray(data2?.data) ? data2.data : [];
const foundModel2 = models2.find((m) => {
const key = String(m?.key || "").trim();
return key && key.toLowerCase() === requestedKey;
});
const loadedInstances2 = Array.isArray(foundModel2?.loaded_instances) ? foundModel2.loaded_instances : [];
const loadedInstance2 = loadedInstances2.find((inst) => {
const instId = getInstanceId(inst);
return typeof instId === "string" && instId.toLowerCase() === requestedKey;
});
loadedInstanceId = getInstanceId(loadedInstance2);
loadedInstanceContextLength = getInstanceContextLength(loadedInstance2);
maxContextLength = typeof foundModel2?.max_context_length === "number" ? foundModel2.max_context_length : typeof foundModel2?.maxContextLength === "number" ? foundModel2.maxContextLength : void 0;
} catch (e) {
console.debug(
"[AgentModel] Post-load model status re-check failed (skipping context warning)."
);
}
return {
ok: true,
alreadyLoaded: false,
identifier: requestedKeyRaw,
loadedInstanceId: loadedInstanceId ?? requestedKeyRaw,
loadedInstanceContextLength,
maxContextLength,
size: foundModel?.size_bytes ? (Number(foundModel.size_bytes) / 1e3 / 1e3 / 1e3).toFixed(2) + " GB" : void 0,
loadTimeSec
};
} catch (e) {
const resp = e?.response;
const respText = resp?.data ? typeof resp.data === "string" ? resp.data : JSON.stringify(resp.data) : void 0;
const msg = respText || e?.message || String(e);
const UNSPECIFIC = "Error: Error loading model.";
const FRIENDLY = "Model load failed. Please open LM Studio Debug logs; the model configuration (e.g. context length / GPU offload) may not match your Model Loading Guardrails settings.";
const safeMsg = typeof msg === "string" && msg.includes(UNSPECIFIC) ? msg.split(UNSPECIFIC).join(FRIENDLY) : msg;
appendPluginLog(
`[AgentModel] load failed: ${requestedKeyRaw} error=${safeMsg}`
);
return {
ok: false,
error: `Failed to load model via API: ${safeMsg}`
};
}
}
// src/media-promotion-core/promotion.ts
import fs24 from "fs";
import path24 from "path";
async function pathExists3(p) {
try {
await fs24.promises.access(p, fs24.constants.F_OK);
return true;
} catch {
return false;
}
}
async function recordGeneratedVariants(chatWd, state, discoveredOriginals, previewOpts, turnIdByOriginAbs, debug = false) {
if (!discoveredOriginals.length) return { changed: false };
const prepared = [];
for (const src of discoveredOriginals) {
const abs = src.startsWith("file://") ? fileUriToPath(src) : path24.isAbsolute(src) ? src : path24.join(chatWd, src);
if (debug)
console.info(
`[recordGeneratedVariants] Processing src: ${src} \u2192 abs: ${abs}`
);
if (!await pathExists3(abs)) {
if (debug)
console.warn(
`[recordGeneratedVariants] Original not found, skipping: ${abs}`
);
continue;
}
if (!isAllowedOriginalExt(abs)) {
if (debug)
console.warn(
`[recordGeneratedVariants] Extension not allowed, skipping: ${abs}`
);
continue;
}
const base = path24.basename(abs);
if (debug) console.info(`[recordGeneratedVariants] basename: ${base}`);
const vName = base;
const vAbs = path24.join(chatWd, vName);
if (!await pathExists3(vAbs)) {
if (debug)
console.warn(
`[recordGeneratedVariants] Original missing in chatWd, skipping: ${vAbs}`
);
continue;
}
const m = /^generated-image-(.+)-v(\d+)\.\w+$/i.exec(base);
const ts = m ? m[1] : "unknown";
const vNum = parseInt(m ? m[2] : "1", 10) || 1;
if (debug)
console.info(`[recordGeneratedVariants] Parsed: ts=${ts}, vNum=${vNum}`);
const previewCandidates = [`preview-generated-image-${ts}-v${vNum}.jpg`];
let foundPreview = null;
for (const cand of previewCandidates) {
const pAbs = path24.join(chatWd, cand);
if (debug)
console.info(
`[recordGeneratedVariants] Looking for preview in chatWd: ${pAbs}`
);
if (await pathExists3(pAbs)) {
foundPreview = cand;
break;
}
}
if (foundPreview) {
const maybeTurnId = (() => {
try {
const key = path24.resolve(abs);
const tid = turnIdByOriginAbs ? turnIdByOriginAbs[key] : void 0;
return typeof tid === "number" && Number.isFinite(tid) ? tid : void 0;
} catch {
return void 0;
}
})();
prepared.push({
filename: vName,
preview: foundPreview,
v: vNum,
ts,
turnId: maybeTurnId
});
} else if (debug) {
console.warn(
`[recordGeneratedVariants] Preview not found in chatWd, skipping variant v${vNum}`
);
}
}
if (!prepared.length) return { changed: false };
const toAppend = prepared.map((r) => ({
filename: r.filename,
preview: r.preview,
turnId: r.turnId,
v: r.v
// Use the v-number parsed from filename for stable identity
}));
const result = appendVariants(state, toAppend);
if (result.changed) {
state.lastEvent = { type: "variants", at: localTimestamp() };
if (debug)
console.info(
"Recorded variants (imported from SSOT):",
result.records.map((x) => `v${x.v}: ${x.filename}`).join(", ")
);
await writeStateAtomic(chatWd, state);
}
return { changed: result.changed };
}
function buildPromotionItems(chatWd, state, {
labels = true,
onlyAttachmentNs,
onlyVariantVs,
onlyImageIs
} = {}) {
const items = [];
const maxAttachments = getAttachmentWindowSize();
const attachments = Array.isArray(state.attachments) ? state.attachments : [];
const sortedAttachments = [...attachments].sort(
(a, b) => (a.a ?? 0) - (b.a ?? 0)
);
const attachmentCap = Math.max(0, Math.floor(maxAttachments));
let cappedAttachments = attachmentCap > 0 ? sortedAttachments.slice(-attachmentCap) : [];
if (onlyAttachmentNs !== void 0) {
const allowedNs = new Set(onlyAttachmentNs);
cappedAttachments = cappedAttachments.filter((a) => allowedNs.has(a.a ?? 0));
}
for (const a of cappedAttachments) {
if (!a) continue;
const stableA = typeof a.a === "number" ? a.a : 0;
const abs = typeof a.originAbs === "string" && String(a.originAbs) ? String(a.originAbs) : "";
const pRel = typeof a.preview === "string" && String(a.preview) ? String(a.preview) : "";
const pAbs = pRel ? path24.join(chatWd, pRel) : "";
if (!abs) {
throw new Error(
`Attachment a${stableA} is missing originAbs (origin=${String(
a.origin
)})`
);
}
if (!pAbs) {
throw new Error(
`Attachment a${stableA} is missing preview (origin=${String(
a.origin
)}, originAbs=${String(a.originAbs)})`
);
}
if (labels && (!(a.originalName && typeof a.originalName === "string") || !String(a.originalName).trim())) {
throw new Error(
`Attachment a${stableA} is missing originalName (filename=${String(
a.filename
)}, origin=${String(a.origin)}, originAbs=${String(
a.originAbs
)})`
);
}
const label = labels ? `Attachment [a${stableA}] ${String(a.originalName)}` : void 0;
items.push({
abs,
previewAbs: pAbs,
label
});
}
const maxEverythingElse = getEverythingElseWindowSize();
const pool = [];
const variants = Array.isArray(state.variants) ? state.variants : [];
for (const v of variants) {
if (v.kind === "tool_result") continue;
if (!v.preview) continue;
pool.push({
kind: "variant",
key: `v${v.v}`,
index: v.v,
createdAt: v.createdAt ?? "",
filename: v.filename,
preview: v.preview
});
}
const images = Array.isArray(state.images) ? state.images : [];
for (const img of images) {
if (!img.preview) continue;
pool.push({
kind: "image",
key: `i${img.i}`,
index: img.i,
createdAt: img.createdAt ?? "",
filename: img.filename,
preview: img.preview
});
}
pool.sort((a, b) => {
const cmp = a.createdAt.localeCompare(b.createdAt);
if (cmp !== 0) return cmp;
if (a.kind !== b.kind) return a.kind === "variant" ? -1 : 1;
return a.index - b.index;
});
const everythingElseCap = Math.max(0, Math.floor(maxEverythingElse));
let windowItems = everythingElseCap > 0 ? pool.slice(-everythingElseCap) : [];
if (onlyVariantVs !== void 0 || onlyImageIs !== void 0) {
const allowedVs = new Set(onlyVariantVs ?? []);
const allowedIs = new Set(onlyImageIs ?? []);
windowItems = windowItems.filter((item) => {
if (item.kind === "variant") {
return onlyVariantVs === void 0 ? true : allowedVs.has(item.index);
}
return onlyImageIs === void 0 ? true : allowedIs.has(item.index);
});
}
for (const item of windowItems) {
const abs = path24.join(chatWd, item.filename);
const pAbs = path24.join(chatWd, item.preview);
const label = labels ? item.kind === "variant" ? `Variant [v${item.index}]` : `Image [i${item.index}]` : void 0;
items.push({
abs,
previewAbs: pAbs,
label
});
}
return items;
}
function getPromotableAttachmentNs(state) {
const maxAttachments = getAttachmentWindowSize();
const attachments = Array.isArray(state.attachments) ? state.attachments : [];
const sortedAttachments = [...attachments].sort(
(a, b) => (a.a ?? 0) - (b.a ?? 0)
);
const cap = Math.max(0, Math.floor(maxAttachments));
const cappedAttachments = cap > 0 ? sortedAttachments.slice(-cap) : [];
const ns = cappedAttachments.map((a) => typeof a.a === "number" ? a.a : 0).filter((n) => n > 0);
ns.sort((a, b) => a - b);
return ns;
}
function shouldPromoteAttachments(state) {
const currentNs = getPromotableAttachmentNs(state);
const lastNs = Array.isArray(state.lastPromotedAttachmentAs) ? [...state.lastPromotedAttachmentAs].sort((a, b) => a - b) : [];
if (currentNs.length !== lastNs.length) return true;
for (let i = 0; i < currentNs.length; i++) {
if (currentNs[i] !== lastNs[i]) return true;
}
return false;
}
function getPromotableEverythingElse(state) {
const maxEverythingElse = getEverythingElseWindowSize();
const pool = [];
const variants = Array.isArray(state.variants) ? state.variants : [];
for (const v of variants) {
if (v.kind === "tool_result") continue;
if (!v.preview) continue;
pool.push({
kind: "variant",
index: v.v,
createdAt: v.createdAt ?? ""
});
}
const images = Array.isArray(state.images) ? state.images : [];
for (const img of images) {
if (!img.preview) continue;
pool.push({
kind: "image",
index: img.i,
createdAt: img.createdAt ?? ""
});
}
pool.sort((a, b) => {
const cmp = a.createdAt.localeCompare(b.createdAt);
if (cmp !== 0) return cmp;
if (a.kind !== b.kind) return a.kind === "variant" ? -1 : 1;
return a.index - b.index;
});
const cap = Math.max(0, Math.floor(maxEverythingElse));
const windowItems = cap > 0 ? pool.slice(-cap) : [];
const variantVs = windowItems.filter((x) => x.kind === "variant").map((x) => x.index).sort((a, b) => a - b);
const imageIs = windowItems.filter((x) => x.kind === "image").map((x) => x.index).sort((a, b) => a - b);
return { variantVs, imageIs };
}
function getPromotableVariantVs(state) {
return getPromotableEverythingElse(state).variantVs;
}
function getPromotableImageIs(state) {
return getPromotableEverythingElse(state).imageIs;
}
function shouldPromoteEverythingElseIdempotent(state) {
const { variantVs, imageIs } = getPromotableEverythingElse(state);
const lastVs = Array.isArray(state.lastPromotedVariantVs) ? [...state.lastPromotedVariantVs].sort((a, b) => a - b) : [];
const lastIs = Array.isArray(state.lastPromotedImageIs) ? [...state.lastPromotedImageIs].sort((a, b) => a - b) : [];
if (variantVs.length !== lastVs.length) return true;
for (let i = 0; i < variantVs.length; i++) {
if (variantVs[i] !== lastVs[i]) return true;
}
if (imageIs.length !== lastIs.length) return true;
for (let i = 0; i < imageIs.length; i++) {
if (imageIs[i] !== lastIs[i]) return true;
}
return false;
}
function shouldPromoteVariantsIdempotent(state) {
return shouldPromoteEverythingElseIdempotent(state);
}
function fileUriToPath(uri) {
const p = decodeURIComponent(uri.replace(/^file:\/\//i, ""));
return p.startsWith("/") ? p : "/" + p;
}
// src/services/schemas.ts
import path25 from "node:path";
import { z } from "zod";
var TOOL_MIN_RENDER_DIM = drawthingsLimits.min;
var TOOL_MAX_WIDTH = drawthingsLimits.maxWidth;
var TOOL_MAX_HEIGHT = drawthingsLimits.maxHeight;
var TOOL_MAX_PREVIEW_W = drawthingsLimits.maxWidth;
var ZOOM_TOOL_MAX_DIM = 2048;
function validateImageGenerationParams(params) {
const errors = [];
if (params.prompt !== void 0 && typeof params.prompt !== "string") {
errors.push("prompt must be a string");
}
if (params.negative_prompt !== void 0 && typeof params.negative_prompt !== "string") {
errors.push("negative_prompt must be a string");
}
if (params.width !== void 0 && (!Number.isInteger(params.width) || params.width <= 0)) {
errors.push("width must be a positive integer");
}
if (params.height !== void 0 && (!Number.isInteger(params.height) || params.height <= 0)) {
errors.push("height must be a positive integer");
}
if (params.steps !== void 0 && (!Number.isInteger(params.steps) || params.steps <= 0)) {
errors.push("steps must be a positive integer");
}
if (params.seed !== void 0 && !Number.isInteger(params.seed)) {
errors.push("seed must be an integer");
}
if (params.guidance_scale !== void 0 && (typeof params.guidance_scale !== "number" || params.guidance_scale < 0)) {
errors.push("guidance_scale must be a number >= 0");
}
if (params.model !== void 0 && typeof params.model !== "string") {
errors.push("model must be a string");
}
if (params.sampler !== void 0 && typeof params.sampler !== "string" && typeof params.sampler !== "number") {
errors.push("sampler must be a string or number");
}
if (params.random_string !== void 0 && typeof params.random_string !== "string") {
errors.push("random_string must be a string");
}
return { valid: errors.length === 0, errors };
}
function normalizeQualityToInt(q, def) {
let n = typeof q === "string" ? parseFloat(q) : typeof q === "number" ? q : def;
if (!Number.isFinite(n)) n = def;
if (n > 0 && n <= 1) n = n * 100;
n = Math.round(n);
if (n < 1) n = 1;
if (n > 100) n = 100;
return n;
}
function clampNumber(n, min, max) {
return Math.min(max, Math.max(min, n));
}
function formatZodError(err) {
return err.issues.map((i) => {
const path34 = i.path && i.path.length ? i.path.join(".") : "(root)";
return `${path34}: ${i.message}`;
}).join("; ");
}
var GenerateToolParamsSchemaBase = z.object({
prompt: z.string().optional(),
negative_prompt: z.string().optional(),
width: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM, `width must be >= ${TOOL_MIN_RENDER_DIM}`).max(TOOL_MAX_WIDTH, `width must be <= ${TOOL_MAX_WIDTH}`).optional(),
height: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM, `height must be >= ${TOOL_MIN_RENDER_DIM}`).max(TOOL_MAX_HEIGHT, `height must be <= ${TOOL_MAX_HEIGHT}`).optional(),
steps: z.coerce.number().int().min(1, "steps must be >= 1").max(50, "steps must be <= 50").optional(),
seed: z.coerce.number().int().optional(),
guidance_scale: z.coerce.number().min(0, "guidance_scale must be >= 0").max(50, "guidance_scale must be <= 50").optional(),
model: z.string().optional(),
sampler: z.union([z.string(), z.number()]).optional(),
numFrames: z.coerce.number().int().min(1, "numFrames must be >= 1").max(641, "numFrames must be <= 641").optional(),
random_string: z.string().optional(),
// preview controls (validation only; defaults applied by caller)
previewFormat: z.enum(["jpeg", "webp"], {
errorMap: () => ({ message: "previewFormat must be 'jpeg' or 'webp'" })
}).optional(),
previewMaxWidth: z.coerce.number().int().min(128).max(TOOL_MAX_PREVIEW_W).optional(),
previewMinWidth: z.coerce.number().int().min(128).max(TOOL_MAX_PREVIEW_W).optional(),
previewMaxBytes: z.coerce.number().int().min(2e3).max(2e5).optional(),
previewQuality: z.union([z.coerce.number(), z.string()]).transform((v) => normalizeQualityToInt(v, NaN)).optional(),
previewMinQuality: z.union([z.coerce.number(), z.string()]).transform((v) => normalizeQualityToInt(v, NaN)).optional(),
previewQualityStep: z.coerce.number().int().min(1).max(20).optional(),
previewScaleStep: z.coerce.number().min(0.5).max(0.98).optional(),
previewInChat: z.coerce.boolean().optional(),
alt: z.string().max(120).optional(),
// saving
saveOriginal: z.coerce.boolean().optional(),
saveDir: z.string().optional()
}).passthrough();
var GenerateToolParamsSchema = GenerateToolParamsSchemaBase.superRefine((d, ctx) => {
if (d.previewMinWidth !== void 0 && d.previewMaxWidth !== void 0 && d.previewMinWidth > d.previewMaxWidth) {
ctx.addIssue({
code: "custom",
path: ["previewMinWidth"],
message: "previewMinWidth must be <= previewMaxWidth"
});
}
if (d.previewMinQuality !== void 0 && d.previewQuality !== void 0 && d.previewMinQuality > d.previewQuality) {
ctx.addIssue({
code: "custom",
path: ["previewMinQuality"],
message: "previewMinQuality must be <= previewQuality"
});
}
});
var multiIndexSchema = z.union([
z.string().transform(
(s) => s.split(/[\s,]+/).map((x) => parseInt(x.trim(), 10)).filter((n) => Number.isInteger(n) && n >= 1)
),
z.coerce.number().int().min(1).transform((n) => [n]),
z.array(z.coerce.number().int().min(1))
]).optional();
function normalizeSourceToken(raw) {
let s = String(raw ?? "").trim();
if (!s) return "";
s = s.replace(/^[\[{(]+/, "").replace(/[\]})]+$/, "");
s = s.replace(/^['"`]+|['"`]+$/g, "");
s = s.replace(/[;:.!?]+$/, "");
s = s.trim();
if (/^a$/i.test(s)) return "a1";
if (/^v$/i.test(s)) return "v1";
if (/^p$/i.test(s)) return "p1";
if (/^i$/i.test(s)) return "i1";
return s;
}
var SourceNotation = z.preprocess(
(v) => typeof v === "string" ? normalizeSourceToken(v) : v,
z.string().trim().regex(
/^([avpi]|[avpi]?[1-9]\d*)$/i,
"Source notation: 'a1', 'v2', 'p1', 'i3', or digit when unambiguous"
)
);
function isSourcePathToken(s) {
return s.length > 0 && (path25.isAbsolute(s) || s === path25.basename(s));
}
var SourcePathReference = z.string().trim().refine(isSourcePathToken, "Source path must be an absolute path or a filename without directory separators");
var SourceNotationOrPath = z.union([SourceNotation, SourcePathReference]);
var SourceNotationList = z.union([
// String form: split by comma/space and validate each part
z.string().transform(
(s) => s.split(/[\s,]+/).map((x) => normalizeSourceToken(x)).filter((x) => x.length > 0)
),
// Array form: validate each element
z.array(SourceNotationOrPath)
]).refine(
(arr) => arr.every((x) => /^([avpi]|[avpi]?[1-9]\d*)$/i.test(String(x)) || isSourcePathToken(String(x))),
"moodboard contains invalid source notation(s)"
);
var GenerateToolParamsShapeMinimal = {
prompt: z.string().optional().describe(
"Image description (mode: 'text2image') OR description of desired changes (mode: 'image2image')."
),
width: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(TOOL_MAX_WIDTH).optional().describe(`Width in pixels (max ${TOOL_MAX_WIDTH}). Has sensible default.`),
height: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(TOOL_MAX_HEIGHT).optional().describe(`Height in pixels (max ${TOOL_MAX_HEIGHT}). Has sensible default.`),
imageFormat: z.enum(["square", "landscape", "portrait", "16:9"]).optional().describe("Aspect ratio shorthand. Override if context suggests. '16:9' yields 1024\xD7576 (video-optimized)."),
// model preset selection — default 'auto' uses built-in settings
model: z.string().optional().describe("Model: 'auto' (default) picks the best model for the mode; otherwise a name from the list of installed models, a model name or a file name."),
// number of images to generate in one call
variants: z.coerce.number().int().min(1).max(4).optional().describe("Number of images (1-4). Default is 1."),
// number of video frames
numFrames: z.coerce.number().int().min(1, "numFrames must be >= 1").max(641, "numFrames must be <= 641").optional().describe("Number of video frames. Must be a multiple of 32 (or multiple of 32 + 1). Default: 1 (image). Silently ignored for non-video modes."),
// image2image controls (only allow selecting a prior variant)
mode: z.enum(["text2image", "image2image", "edit", "text2video", "image2video"]).optional().describe("Generation mode. 'text2video'/'image2video' require a video model (e.g. 'ltx2.3'). Required when sources exist."),
// Primary source for image2image/edit
canvas: z.union([
SourceNotationOrPath,
z.array(SourceNotationOrPath).min(1).max(1).transform((arr) => arr[0])
]).optional().describe(
"Primary source image. Notation: 'a1', 'v2', 'p1', 'i3'. Digit-only allowed only when unambiguous. Also accepts a filename in the scratchpad folder or an absolute path. Tolerates single-item array input."
),
// Additional style references for image2image/edit modes (gRPC only for image2image)
moodboard: SourceNotationList.optional().describe(
"Additional style references for image2image/edit modes. Array of source notations (same format as canvas)."
),
// Opt-in background execution: returns immediately with a requestId instead of waiting for rendering to finish.
runInBackground: z.boolean().optional().describe(
"If true, returns immediately with a requestId instead of waiting for the render to finish. Poll status/result with request_progress(requestId). Default false (synchronous)."
)
};
var GenerateToolParamsSchemaMinimalStrict = z.object(GenerateToolParamsShapeMinimal).strict();
var cropSideField = z.union([z.number(), z.string()]).optional();
var cropSideOrNullField = z.union([z.number(), z.string()]).nullable();
var cropSideOverrideArray = z.array(cropSideOrNullField).optional();
var cropSideOrArrayBase = z.preprocess(
(val) => {
if (typeof val === "string") {
const t = val.trim();
if (t.startsWith("[")) {
try {
const parsed = JSON.parse(t);
if (Array.isArray(parsed)) {
return parsed.map((el) => {
if (typeof el === "string") {
if (el.trim().toLowerCase() === "null") return null;
const n = Number(el.trim());
if (!isNaN(n)) return n;
}
return el;
});
}
} catch {
}
}
}
return val;
},
z.union([z.number(), z.string(), cropSideOverrideArray.unwrap()])
);
var cropSideOrArrayField = cropSideOrArrayBase.optional();
var detectLabelBase = z.preprocess(
(val) => {
if (typeof val === "string") {
const t = val.trim();
if (t.startsWith("[")) {
try {
const parsed = JSON.parse(t);
if (Array.isArray(parsed)) {
return parsed.map((el) => String(el).trim()).filter((s) => s.length > 0);
}
} catch {
}
}
}
return val;
},
z.union([
z.string().transform(
(s) => s.split(/\s*,\s*/).map((x) => x.trim()).filter((x) => x.length > 0)
),
z.array(z.string().min(1))
])
);
var RunInBackgroundField = z.boolean().optional().describe(
"If true, returns immediately with a requestId instead of waiting for the render to finish. Poll status/result with request_progress(requestId). Default false (synchronous)."
);
var ColorCalibrationField = z.boolean().optional().describe(
"Corrects a colour drift inside the mask area. Default false. Only helpful when the result shows a visible colour deviation in the masked area."
);
var CropToolParamsShape = {
canvas: z.union([
SourceNotationOrPath,
z.array(SourceNotationOrPath).min(1).max(1).transform((arr) => arr[0])
]).optional().describe(
"Source image. Notation: 'a1', 'v2', 'p1', 'i3'. Also accepts a filename in the scratchpad folder or an absolute path. Tolerates single-item array input."
),
cropLeft: z.union([z.number(), z.string(), z.array(z.union([z.number(), z.string()]).nullable())]).optional().describe(
"Amount to remove from the left side. Scalar (single-region): number or px-string, e.g. '120px'. Array (multi-region, parallel to detectLabel): one entry per label; null = keep detection value. Default unit: % (0\u201399)."
),
cropRight: z.union([z.number(), z.string(), z.array(z.union([z.number(), z.string()]).nullable())]).optional().describe(
"Amount to remove from the right side. Scalar or per-box array (null = keep detection value). Default unit: % (0\u201399)."
),
cropTop: z.union([z.number(), z.string(), z.array(z.union([z.number(), z.string()]).nullable())]).optional().describe(
"Amount to remove from the top. Scalar or per-box array (null = keep detection value). Default unit: % (0\u201399)."
),
cropBottom: z.union([z.number(), z.string(), z.array(z.union([z.number(), z.string()]).nullable())]).optional().describe(
"Amount to remove from the bottom. Scalar or per-box array (null = keep detection value). Default unit: % (0\u201399)."
),
imageFormat: z.enum(["square", "landscape", "portrait", "16:9"]).optional().describe(
"Target aspect ratio. Only active when explicitly set; omitting it crops with the given sides only (no AR enforcement). Ignored when all 4 crop sides are explicitly given. Unspecified axes are centred; single-side anchors are honoured. 'square'=1:1, 'landscape'=4:3, 'portrait'=3:4, '16:9'=16:9."
),
detectLabel: detectLabelBase.optional().describe(
`Label (or array of labels) of detected objects to mask/crop (requires a prior detect_object run). Array form enables multi-region: one bbox per entry, parallel to detectIndex and per-box crop overrides. String form: comma-separated labels, e.g. "cat, dog". Multi-word labels are supported. canvas: pass the most recent image, typically the detect_object result (e.g. 'i3'); it is traced back to its source automatically.`
),
detectIndex: z.union([
z.string().transform((s) => (s.match(/\d+/g) ?? []).map(Number)),
z.coerce.number().int().min(0).transform((n) => [n]),
z.array(z.coerce.number().int().min(0))
]).optional().describe(
"Zero-based index (or array of indices, parallel to detectLabel) to select among multiple detections with the same label. Default 0 for each entry."
),
frameAdjust: z.union([z.number(), z.string()]).optional().describe(
"Expand (positive) or shrink (negative) each detection bounding box. Applied as the final step after all overrides. Number: percent of bbox diagonal. String: value + optional 'px' suffix, e.g. '20px' or '-10%'. Applies to all regions uniformly."
)
};
var CropToolSchemaStrict = z.object(CropToolParamsShape).strict();
var ZoomInToolParamsShape = {
prompt: z.string().optional().describe("Description of desired changes to apply during re-rendering. Default: empty (preserve content)."),
width: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(ZOOM_TOOL_MAX_DIM).optional().describe(`Output width in pixels (max ${ZOOM_TOOL_MAX_DIM}). Has sensible default.`),
height: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(ZOOM_TOOL_MAX_DIM).optional().describe(`Output height in pixels (max ${ZOOM_TOOL_MAX_DIM}). Has sensible default.`),
model: z.string().optional().describe("Model: 'auto' (default), or a name from the list of installed models, a model name or a file name."),
canvas: z.union([
SourceNotationOrPath,
z.array(SourceNotationOrPath).min(1).max(1).transform((arr) => arr[0])
]).optional().describe(
"Source image. Notation: 'a1', 'v2', 'p1', 'i3'. Also accepts a filename in the scratchpad folder or an absolute path. Tolerates single-item array input."
),
detectLabel: z.string().optional().describe(
"Crop to the bounding box of a detected object by label (requires a prior detect_object run). canvas: pass the most recent image, typically the detect_object result (e.g. 'i3'); it is traced back to its source automatically."
),
detectIndex: z.coerce.number().int().min(0).optional().describe("Zero-based index to select among multiple detections with the same label. Default 0."),
frameAdjust: z.union([z.number(), z.string()]).optional().describe(
"Expand (positive) or shrink (negative) the detection bounding box before cropping. Number: percent of min(W,H). String: value + optional 'px' suffix, e.g. '20px' or '-10%'."
),
imageFormat: z.enum(["square", "landscape", "portrait", "16:9"]).optional().describe(
"Target aspect ratio for the render output. Only active when explicitly set. 'square'=1:1, 'landscape'=4:3, 'portrait'=3:4, '16:9'=16:9."
),
runInBackground: RunInBackgroundField
};
var ZoomInToolSchemaStrict = z.object(ZoomInToolParamsShape).strict();
var InpaintToolParamsShape = {
prompt: z.string().trim().min(1, "prompt is required: describe what should appear in the repainted region.").describe(`Required. What should appear in the repainted region (e.g. 'Replace the digit "2" with a "3"').`),
width: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(ZOOM_TOOL_MAX_DIM).optional().describe(`Output width in pixels (max ${ZOOM_TOOL_MAX_DIM}). Has sensible default.`),
height: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(ZOOM_TOOL_MAX_DIM).optional().describe(`Output height in pixels (max ${ZOOM_TOOL_MAX_DIM}). Has sensible default.`),
model: z.string().optional().describe("Model: 'auto' (default), or a name from the list of installed models, a model name or a file name."),
canvas: z.union([
SourceNotationOrPath,
z.array(SourceNotationOrPath).min(1).max(1).transform((arr) => arr[0])
]).optional().describe(
"Source image. Notation: 'a1', 'v2', 'p1', 'i3'. Also accepts a filename in the scratchpad folder or an absolute path. Tolerates single-item array input."
),
moodboard: SourceNotationList.optional().describe(
"Reference image(s) to guide the repainted region (e.g. a logo or object to insert). Array of source notations (same format as canvas). Passed to the model as a style/content reference only \u2014 not pixel-composited into the mask; its native aspect ratio is preserved."
),
detectLabel: detectLabelBase.optional().describe(
`Label (or array of labels) of detected objects to inpaint. Preferred: array, e.g. ["left eye", "right eye"]. Also accepts comma-separated string, e.g. "left eye, right eye". Multi-word labels are supported. Each entry selects one detection bounding box. Requires a prior detect_object run. canvas may be the source (e.g. 'a1') or the detect_object result (e.g. 'i3').`
),
detectIndex: z.union([
z.string().transform((s) => (s.match(/\d+/g) ?? []).map(Number)),
z.coerce.number().int().min(0).transform((n) => [n]),
z.array(z.coerce.number().int().min(0))
]).optional().describe(
"Zero-based index (or array of indices, parallel to detectLabel) to select among multiple detections with the same label. Default 0 for each entry."
),
frameAdjust: z.union([z.number(), z.string()]).optional().describe(
"Expand (positive) or shrink (negative) each detection bounding box. Applied as the final step after all per-box overrides. Applies uniformly to all regions. Number: percent of bbox diagonal. String: value + optional 'px' suffix, e.g. '20px' or '-10%'."
),
cropLeft: cropSideOrArrayBase.optional().describe(
"Override the left crop side for the detected region(s). Scalar = same for all; array (parallel to detectLabel, null = keep detection value) for per-box control. Default unit: % (0\u201399) or append 'px'."
),
cropRight: cropSideOrArrayBase.optional().describe(
"Override the right crop side. Scalar or per-box array (null = keep detection value). Default unit: %."
),
cropTop: cropSideOrArrayBase.optional().describe(
"Override the top crop side. Scalar or per-box array (null = keep detection value). Default unit: %."
),
cropBottom: cropSideOrArrayBase.optional().describe(
"Override the bottom crop side. Scalar or per-box array (null = keep detection value). Default unit: %."
),
colorCalibration: ColorCalibrationField,
runInBackground: RunInBackgroundField
};
var InpaintToolSchemaStrict = z.object(InpaintToolParamsShape).strict();
var OutpaintToolParamsShape = {
prompt: z.string().trim().min(1, "prompt is required: describe what should appear in the extended area.").describe("Required. What should appear in the extended area (e.g. 'Everything that is not the person becomes a green meadow')."),
width: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(ZOOM_TOOL_MAX_DIM).optional().describe(`Output width in pixels (max ${ZOOM_TOOL_MAX_DIM}). Has sensible default.`),
height: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(ZOOM_TOOL_MAX_DIM).optional().describe(`Output height in pixels (max ${ZOOM_TOOL_MAX_DIM}). Has sensible default.`),
model: z.string().optional().describe("Model: 'auto' (default), or a name from the list of installed models, a model name or a file name."),
canvas: z.union([
SourceNotationOrPath,
z.array(SourceNotationOrPath).min(1).max(1).transform((arr) => arr[0])
]).optional().describe(
"Source image. Notation: 'a1', 'v2', 'p1', 'i3'. Also accepts a filename in the scratchpad folder or an absolute path. Tolerates single-item array input."
),
moodboard: SourceNotationList.optional().describe(
"Reference image(s) to guide the extended region (e.g. a logo or object to insert). Array of source notations (same format as canvas). Passed to the model as a style/content reference only \u2014 not pixel-composited into the mask; its native aspect ratio is preserved."
),
detectLabel: detectLabelBase.optional().describe(
`Label (or array of labels) of detected objects to outpaint. Preferred: array, e.g. ["left eye", "right eye"]. Also accepts comma-separated string, e.g. "left eye, right eye". Multi-word labels are supported. Each entry selects one detection bounding box. Requires a prior detect_object run. canvas may be the source (e.g. 'a1') or the detect_object result (e.g. 'i3').`
),
detectIndex: z.union([
z.string().transform((s) => (s.match(/\d+/g) ?? []).map(Number)),
z.coerce.number().int().min(0).transform((n) => [n]),
z.array(z.coerce.number().int().min(0))
]).optional().describe(
"Zero-based index (or array of indices, parallel to detectLabel) to select among multiple detections with the same label. Default 0 for each entry."
),
frameAdjust: z.union([z.number(), z.string()]).optional().describe(
"Expand (positive) or shrink (negative) each detection bounding box. Applied as the final step after all per-box overrides. Applies uniformly to all regions. Number: percent of bbox diagonal. String: value + optional 'px' suffix, e.g. '20px' or '-10%'."
),
cropLeft: cropSideOrArrayBase.optional().describe(
"Override the left crop side for the detected region(s). Scalar = same for all; array (parallel to detectLabel, null = keep detection value) for per-box control. Default unit: % (0\u201399) or append 'px'."
),
cropRight: cropSideOrArrayBase.optional().describe(
"Override the right crop side. Scalar or per-box array (null = keep detection value). Default unit: %."
),
cropTop: cropSideOrArrayBase.optional().describe(
"Override the top crop side. Scalar or per-box array (null = keep detection value). Default unit: %."
),
cropBottom: cropSideOrArrayBase.optional().describe(
"Override the bottom crop side. Scalar or per-box array (null = keep detection value). Default unit: %."
),
colorCalibration: ColorCalibrationField,
runInBackground: RunInBackgroundField
};
var OutpaintToolSchemaStrict = z.object(OutpaintToolParamsShape).strict();
var UpscaleToolParamsShape = {
prompt: z.string().optional().describe("Description of desired changes to apply during re-rendering. Default: empty (preserve content)."),
width: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(ZOOM_TOOL_MAX_DIM).optional().describe(`Output width in pixels (max ${ZOOM_TOOL_MAX_DIM}). Has sensible default.`),
height: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(ZOOM_TOOL_MAX_DIM).optional().describe(`Output height in pixels (max ${ZOOM_TOOL_MAX_DIM}). Has sensible default.`),
scaleFactor: z.number().positive().optional().describe("Scale factor applied to the canvas dimensions. E.g. 2 doubles the resolution. Mutually exclusive with width/height."),
model: z.string().optional().describe("Model: 'auto' (default), or a name from the list of installed models, a model name or a file name."),
canvas: z.union([
SourceNotationOrPath,
z.array(SourceNotationOrPath).min(1).max(1).transform((arr) => arr[0])
]).optional().describe(
"Source image. Notation: 'a1', 'v2', 'p1', 'i3'. Also accepts a filename in the scratchpad folder or an absolute path. Tolerates single-item array input."
),
imageFormat: z.string().optional().describe("Target image format / aspect ratio preset (e.g. '16:9', 'portrait'). Resolved to concrete pixel dimensions.")
};
var UpscaleToolSchemaStrict = z.object(UpscaleToolParamsShape).strict();
// src/services/modelMappingSnapshot.ts
import path26 from "node:path";
function toUserMode(mode) {
switch (mode) {
case "txt2img":
return "text2image";
case "img2img":
return "image2image";
case "edit":
return "edit";
case "txt2vid":
return "text2video";
case "img2vid":
return "image2video";
}
}
function basenameNormalized(value) {
return path26.basename(value).trim().toLowerCase();
}
function getDefaultModelForMode(mode) {
const raw = mode === "txt2img" ? defaultParams?.model : mode === "img2img" ? defaultParamsImg2Img?.model : mode === "edit" ? defaultParamsImg2Img2?.model : mode === "txt2vid" ? defaultParamsText2Video?.model : defaultParamsImage2Video?.model;
return typeof raw === "string" ? raw : "";
}
function uniqueStrings(values) {
return [...new Set(values.filter(Boolean))];
}
function preferAutoFirst(values) {
const deduped = uniqueStrings(values);
const rest = deduped.filter((v) => v !== "auto");
return deduped.includes("auto") ? ["auto", ...rest] : rest;
}
function computeFamilyIndex(effectiveByPreset, customPresets) {
const familyByModelBasename = /* @__PURE__ */ new Map();
for (const family2 of ["z-image", "qwen-image", "flux", "ltx"]) {
for (const mode of ["txt2img", "img2img", "edit", "txt2vid", "img2vid"]) {
const file = getModelFilename(family2, mode);
if (typeof file !== "string") continue;
const base = basenameNormalized(file);
if (!base) continue;
familyByModelBasename.set(base, family2);
}
}
for (const family2 of ["z-image", "qwen-image", "flux", "ltx"]) {
const capKey = MODEL_PRESET_TO_CAPABILITY_KEY?.[family2];
if (typeof capKey !== "string") continue;
const cap = IMAGE_MODEL_CAPABILITY_MAP?.[capKey];
const filenames = cap?.modelFilenames;
if (!Array.isArray(filenames)) continue;
for (const f of filenames) {
if (typeof f !== "string") continue;
const base = basenameNormalized(f);
if (!base) continue;
if (!familyByModelBasename.has(base)) familyByModelBasename.set(base, family2);
}
}
for (const preset of customPresets.values()) {
const model = preset?.params?.model;
if (typeof model !== "string") continue;
const base = basenameNormalized(model);
if (!base) continue;
if (!familyByModelBasename.has(base)) familyByModelBasename.set(base, "custom");
}
const out = /* @__PURE__ */ new Map();
for (const info of effectiveByPreset.values()) {
out.set(info.model_filename, familyByModelBasename.get(info.model_filename) ?? "unknown");
}
return out;
}
function computeEffectiveModelForPreset(modelId, modeInternal) {
const baseModel = getDefaultModelForMode(modeInternal);
const baseBase = basenameNormalized(baseModel);
const notation = `${toUserMode(modeInternal)}.${modelId}`;
const customPreset = getCustomPreset(notation);
const hasCustomPreset = !!customPreset;
const customModelRaw = customPreset?.params?.model;
const customBase = typeof customModelRaw === "string" && customModelRaw.trim() ? basenameNormalized(customModelRaw) : void 0;
if (!hasCustomPreset && modelId !== "auto" && modelId !== "custom") {
const support = checkModeSupport(modelId, toUserMode(modeInternal));
if (!support.supported) return "";
}
if (modelId === "custom" && !customPreset) return "";
const overlay = getEffectiveOverlay(modelId, modeInternal);
const overlayModel = overlay.params?.model;
const overlayBase = typeof overlayModel === "string" && overlayModel.trim() ? basenameNormalized(overlayModel) : void 0;
return customBase ?? overlayBase ?? baseBase;
}
async function buildDtcModelMappingSnapshot() {
const customPresets = await loadCustomConfigs();
const modes = ["txt2img", "img2img", "edit", "txt2vid", "img2vid"];
const effectiveByPreset = /* @__PURE__ */ new Map();
for (const modeInternal of modes) {
const mode = toUserMode(modeInternal);
for (const modelId of MODEL_FAMILIES) {
const preset = `${mode}.${modelId}`;
effectiveByPreset.set(preset, {
mode,
model_id: modelId,
preset,
model_filename: computeEffectiveModelForPreset(modelId, modeInternal),
model_family: "unknown"
});
}
}
const familyIndex = computeFamilyIndex(effectiveByPreset, customPresets);
for (const info of effectiveByPreset.values()) {
info.model_family = familyIndex.get(info.model_filename) ?? "unknown";
}
const presetsByModel = /* @__PURE__ */ new Map();
for (const info of effectiveByPreset.values()) {
if (!info.model_filename) continue;
const set = presetsByModel.get(info.model_filename) ?? /* @__PURE__ */ new Set();
set.add(info.preset);
presetsByModel.set(info.model_filename, set);
}
const models = {};
for (const [modelFilename, presetSet] of presetsByModel.entries()) {
const model_family = familyIndex.get(modelFilename) ?? "unknown";
const model_use_by_mode = {};
for (const p of Array.from(presetSet).sort()) {
const [mode, modelId] = p.split(".");
if (!mode || !modelId) continue;
if (mode !== "text2image" && mode !== "image2image" && mode !== "edit" && mode !== "text2video" && mode !== "image2video") continue;
const existing = model_use_by_mode[mode] ?? [];
model_use_by_mode[mode] = preferAutoFirst([...existing, modelId]);
}
models[modelFilename] = {
model_family,
model_use_by_mode
};
}
return {
schema: "dtc.model-mapping-snapshot.v1",
models
};
}
// src/services/defaultParamsDrawThingsRestore.ts
var defaultParamsImg2Img3 = {
aesthetic_score: 6.5,
batch_count: 1,
batch_size: 1,
causal_inference: 0,
causal_inference_pad: 0,
cfg_zero_init_steps: 0,
cfg_zero_star: false,
clip_l_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
clip_skip: 1,
clip_weight: 1,
controls: [],
crop_left: 0,
crop_top: 0,
fps: 25,
guidance_embed: 1,
guidance_scale: 1,
guiding_frame_noise: 0.019999999552965164,
// Ensure size keys exist for filtering; service overwrites with actual PNG size
width: 576,
height: 768,
hires_fix: false,
hires_fix_height: 512,
hires_fix_strength: 0.4000000059604645,
// hires_fix_width: 384,
image_guidance: 1.5,
image_prior_steps: 5,
loras: [],
mask_blur: 2.5,
mask_blur_outset: 0,
model: "flux_2_klein_9b_kv_q6p.ckpt",
motion_scale: 127,
negative_aesthetic_score: 0,
// negative_original_height: 512, negative_original_width: 512,
negative_prompt: "",
negative_prompt_for_image_prior: true,
num_frames: 1,
open_clip_g_text: "Could this be it, or not, I am not sure really.",
// original_height: 512, original_width: 512,
preserve_original_after_inpaint: true,
prompt: "Restore the image. Maintain the identity of the subjects, objects, backgrounds, and scenes exactly as in the original image.",
refiner_model: null,
refiner_start: 0.4000000059604645,
resolution_dependent_shift: false,
sampler: "DDIM Trailing",
seed: 175308301,
seed_mode: "Scale Alike",
separate_clip_l: false,
separate_open_clip_g: false,
separate_t5: false,
sharpness: 0,
shift: 3,
speed_up_with_guidance_embed: true,
stage_2_guidance: 1,
stage_2_shift: 1,
start_frame_guidance: 1.2000000476837158,
steps: 4,
stochastic_sampling_gamma: 0.3,
strength: 1,
t5_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
t5_text_encoder_decoding: true,
// target_height: 512, target_width: 512,
tea_cache: false,
tea_cache_end: 100,
tea_cache_max_skip_steps: 3,
tea_cache_start: 5,
tea_cache_threshold: 0.20000000298023224,
tiled_decoding: false,
tiled_diffusion: false,
upscaler: null,
upscaler_scale: 0,
zero_negative_prompt: false
};
// src/services/defaultParamsZoom.ts
var defaultParamsZoom = {
aesthetic_score: 6.5,
batch_count: 1,
batch_size: 1,
causal_inference: 0,
causal_inference_pad: 0,
cfg_zero_init_steps: 0,
cfg_zero_star: false,
clip_l_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
clip_skip: 1,
clip_weight: 1,
controls: [],
crop_left: 0,
crop_top: 0,
decoding_tile_height: 1024,
decoding_tile_overlap: 128,
decoding_tile_width: 1024,
diffusion_tile_height: 1024,
diffusion_tile_overlap: 128,
diffusion_tile_width: 1024,
fps: 25,
guidance_embed: 1,
guidance_scale: 1,
guiding_frame_noise: 0.019999999552965164,
// Ensure size keys exist for filtering; service overwrites with actual PNG size
width: 768,
height: 1024,
hires_fix: false,
hires_fix_height: 512,
hires_fix_strength: 0.4000000059604645,
// hires_fix_width: 384,
image_guidance: 1.5,
image_prior_steps: 5,
loras: [],
mask_blur: 1.5,
mask_blur_outset: 0,
model: "seedvr2_7b_q6p.ckpt",
motion_scale: 127,
negative_aesthetic_score: 0,
// negative_original_height: 512, negative_original_width: 512,
negative_prompt: "",
negative_prompt_for_image_prior: true,
num_frames: 1,
open_clip_g_text: "Could this be it, or not, I am not sure really.",
// original_height: 512, original_width: 512,
preserve_original_after_inpaint: true,
prompt: "",
refiner_model: null,
refiner_start: 0.4000000059604645,
resolution_dependent_shift: false,
sampler: "DDIM Trailing",
seed: 175308301,
seed_mode: "Scale Alike",
separate_clip_l: false,
separate_open_clip_g: false,
separate_t5: false,
sharpness: 0,
shift: 3,
speed_up_with_guidance_embed: true,
stage_2_guidance: 1,
stage_2_shift: 1,
start_frame_guidance: 1.2000000476837158,
steps: 1,
stochastic_sampling_gamma: 0.3,
strength: 1,
t5_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
t5_text_encoder_decoding: true,
// target_height: 512, target_width: 512,
tea_cache: false,
tea_cache_end: 100,
tea_cache_max_skip_steps: 3,
tea_cache_start: 5,
tea_cache_threshold: 0.20000000298023224,
tiled_decoding: true,
tiled_diffusion: true,
upscaler: null,
upscaler_scale: 0,
zero_negative_prompt: false
};
// src/services/modelInventoryShadow.ts
var OVERLAY_MODES2 = ["txt2img", "img2img", "edit", "txt2vid", "img2vid"];
var CAPABILITY_MODES = ["text2image", "edit", "text2video", "image2video"];
function compareInventoryWithRegistry(inv) {
const findings = [];
let checked = 0, ok = 0, absent = 0;
const check = (subject, mode, main, required, fixed2) => {
checked++;
if (!required.every((f) => inv.files.has(f))) {
absent++;
if (fixed2) findings.push({ level: "warn", kind: "fixed-profile-missing", subject, file: main, detail: `${main} (or a required LoRA) is not installed` });
return;
}
const s = stateOfFile(inv, main);
if (s.state === "requires-missing") findings.push({ level: "warn", kind: "requires-missing", subject, file: main, detail: `required files missing: ${s.missing.join(", ")}` });
else if (s.state === "custom") findings.push({ level: "info", kind: "custom-model", subject, file: main, detail: `not in the catalog (spec family ${s.model.family})` });
else if (s.state === "not-installed") findings.push({ level: "info", kind: "unknown-file", subject, file: main, detail: "file present, but neither catalog nor server spec knows it" });
else if (mode && !supportsMode(s.model.modes, mode)) {
findings.push({ level: s.model.modesUncertain ? "info" : "warn", kind: "mode-unsupported", subject, file: main, detail: `catalog modes of ${s.model.id}: ${s.model.modes.join(", ")}${s.model.modesUncertain ? " (uncertain)" : ""}` });
} else ok++;
};
for (const id of MODEL_IDS) {
if (id === "auto" || id === "custom") continue;
for (const mode of OVERLAY_MODES2) {
const main = getModelFilename(id, mode);
if (!main) continue;
const required = getModelRequiredFiles(id, mode);
const loras = required.filter((f) => f !== main);
const missing = loras.filter((f) => !inv.files.has(f));
if (missing.length && inv.files.has(main)) {
checked++;
findings.push({ level: "warn", kind: "lora-missing", subject: `overlay ${id}/${mode}`, file: main, detail: `overlay settings assume LoRA ${missing.join(", ")}` });
continue;
}
check(`overlay ${id}/${mode}`, mode, main, required, false);
}
}
const fixed = [
["auto/text2image", defaultParams.model, "txt2img"],
["auto/image2image", defaultParamsImg2Img.model, "img2img"],
["auto/edit", defaultParamsImg2Img2.model, "edit"],
["auto/text2video", defaultParamsText2Video.model, "txt2vid"],
["auto/image2video", defaultParamsImage2Video.model, "img2vid"],
["profile restore", defaultParamsImg2Img3.model, null],
["profile zoom", defaultParamsZoom.model, null]
];
for (const [subject, file, mode] of fixed) if (file) check(subject, mode, file, [file], subject.startsWith("profile"));
for (const [key, cap] of Object.entries(IMAGE_MODEL_CAPABILITY_MAP)) {
const present = (cap.modelFilenames ?? []).filter((f) => inv.byFile.has(f));
if (!present.length) continue;
checked++;
const derived = new Set(present.flatMap((f) => inv.byFile.get(f).modes));
const uncertain = present.every((f) => inv.byFile.get(f).modesUncertain);
const hand = CAPABILITY_MODES.filter((m) => cap.modes[m]);
const diff = [...hand.filter((m) => !derived.has(m)).map((m) => `-${m}`), ...CAPABILITY_MODES.filter((m) => derived.has(m) && !hand.includes(m)).map((m) => `+${m}`)];
if (diff.length) findings.push({ level: uncertain ? "info" : "warn", kind: "capability-mode", subject: `capability ${key}`, file: present[0], detail: `registry vs catalog: ${diff.join(" ")}` });
else ok++;
}
return { checked, ok, absent, findings, hash: inv.hash };
}
var lastLoggedHash = null;
function logShadowReport(report, log2 = console) {
if (report.hash === lastLoggedHash) return;
lastLoggedHash = report.hash;
log2.info(`[inventory-shadow] checked=${report.checked} ok=${report.ok} absent=${report.absent} findings=${report.findings.length}${report.echoMs === void 0 ? "" : ` echo=${report.echoMs}ms`}`);
for (const f of report.findings) (f.level === "warn" ? log2.warn : log2.info)(`[inventory-shadow] ${f.level} ${f.kind}: ${f.subject} (${f.file}) ${f.detail}`);
}
function runInventoryShadow(echoResponse, echoMs) {
try {
logShadowReport({ ...compareInventoryWithRegistry(buildInventory(parseEchoResponse(echoResponse))), echoMs });
} catch {
}
}
// src/services/profileModels.ts
import path27 from "node:path";
var DEFAULT_MODEL = {
zoom: () => defaultParamsZoom.model,
restore: () => defaultParamsImg2Img3.model
};
var LABEL = { zoom: "the zoom pass", restore: "the restore pass" };
function substituteInstalledPrecision(file, inv) {
return installedFileOf(file, inv);
}
function substitutionNote(from, to) {
return `'${from}' is not installed; using '${to}' (another precision of the same model).`;
}
function requiredFileForProfile(profile) {
const overlay = getEffectiveOverlay(void 0, profile);
const custom = overlay.source === "custom" ? overlay.params?.model : void 0;
if (typeof custom === "string" && custom.trim()) return { file: path27.basename(custom.trim()), fromCustomConfig: true };
return { file: DEFAULT_MODEL[profile]() ?? "", fromCustomConfig: false };
}
function describeMissingProfileModel(profile, inv) {
const { file, fromCustomConfig } = requiredFileForProfile(profile);
if (!file) return null;
const effective = fromCustomConfig ? { file, substituted: false } : substituteInstalledPrecision(file, inv);
if (inv.files.has(effective.file)) {
const known = inv.byFile.get(effective.file);
return known && !known.ready ? `${LABEL[profile]} needs '${known.name}', but it is incomplete. ${explainFile(inv, effective.file)}` : null;
}
const name = catalogModelOfFile(file)?.name;
const label = name ? `${name} (${file})` : `'${file}'`;
return fromCustomConfig ? `${LABEL[profile]} needs ${label}, set in your '${profile}.auto' preset, but it is not installed. Install it in Draw Things or fix the preset.` : `${LABEL[profile]} needs ${label}, but no precision of it is installed. Install it in Draw Things (any precision works), or save a '${profile}.auto' preset with a model you have.`;
}
async function checkProfileModels(profiles) {
try {
const inv = await currentInventory();
if (!inv) return null;
const problems = profiles.map((p) => describeMissingProfileModel(p, inv)).filter((m) => !!m);
if (!problems.length) return null;
return `Cannot run: ${problems.join(" ")}`.replace(/\s+/g, " ");
} catch {
return null;
}
}
// src/services/autoFallback.ts
var MODES2 = {
text2image: { internal: "txt2img", defaultModel: () => defaultParams.model },
image2image: { internal: "img2img", defaultModel: () => defaultParamsImg2Img.model },
edit: { internal: "edit", defaultModel: () => defaultParamsImg2Img2.model },
text2video: { internal: "txt2vid", defaultModel: () => defaultParamsText2Video.model },
image2video: { internal: "img2vid", defaultModel: () => defaultParamsImage2Video.model }
};
function autoFallbackFor(mode, inv) {
const cfg = MODES2[mode];
const file = cfg?.defaultModel();
if (!cfg || !file || !inv) return null;
if (getEffectiveOverlay("auto", cfg.internal).source === "custom") return null;
const state = stateOfFile(inv, substituteInstalledPrecision(file, inv).file);
if (state.state === "ready" || state.state === "custom" && state.model.ready) return null;
const pick = pickFallbackModel(inv, mode, { accept: isImage2ImageMode(mode) ? (m) => !!image2imagePresetOf(m, inv) : void 0 });
if (!pick) return null;
const why = state.state === "requires-missing" ? `is incomplete (missing: ${state.missing.join(", ")})` : "is not installed";
const i2i = isImage2ImageMode(mode) ? image2imagePresetOf(pick.model, inv) : null;
const preset = i2i ? i2i.kind === "user" ? i2i.preset.modelId : i2i.preset : tunedPresetFor(pick.model.id, mode, inv);
return {
modelId: preset ?? pick.model.file,
note: `Default model '${file}' ${why}; using '${pick.model.name}' (${preset ? `preset ${preset}` : pick.model.file}) instead.${pick.notes.length ? ` ${pick.notes.join(" ")}` : ""}`
};
}
async function resolveAutoFallback(mode) {
try {
return autoFallbackFor(mode, await currentInventory());
} catch {
return null;
}
}
// src/services/modelListText.ts
var PRESET_MODE_ORDER = AGENT_MODE_ORDER;
var DEFAULT_MAX_CHARS = 1800;
var RECOMMENDED_EDIT = [
{ tag: "flux2_9b", hint: "our default" },
{ tag: "flux3_5b" },
{ tag: "qwen_image_2.1", hint: "Turbo" }
];
var INTRO = "auto (default) picks the best installed model for the mode. Otherwise name one of these (the best installed variant is used), or a user-defined entry from custom_configs.json.";
function tunedNames() {
const names = /* @__PURE__ */ new Set();
for (const id of MODEL_IDS) {
if (id === "auto" || id === "custom") continue;
for (const mode of ["txt2img", "edit", "txt2vid", "img2vid"]) {
const file = getModelFilename(id, mode);
const model = file ? catalogModelOfFile(file) : void 0;
const name = model && agentNameOfModel(model);
if (name) names.add(name);
}
}
return [...names].sort();
}
function userPresetLine() {
const byName = /* @__PURE__ */ new Map();
try {
for (const [mode, name] of getAvailableCustomCombinations()) {
if (name === "auto" || isPresetName(name) || runtimeCatalog.families[name]) continue;
byName.set(name, (byName.get(name) ?? /* @__PURE__ */ new Set()).add(mode));
}
} catch {
return null;
}
if (!byName.size) return null;
const names = [...byName].sort(([a], [b]) => a.localeCompare(b)).map(([name, modes]) => `${name} (${PRESET_MODE_ORDER.filter((m) => modes.has(m)).join(", ")})`);
return `- your presets (custom_configs.json): ${names.slice(0, 8).join(", ")}${names.length > 8 ? `, +${names.length - 8} more` : ""}`;
}
function buildModelListText(inv, opts = {}) {
if (opts.recommendedEdit) {
const installedFamilies = inv && new Set(inv.installed.filter((m) => m.ready).map((m) => m.family));
const shown = RECOMMENDED_EDIT.filter((r) => !installedFamilies || installedFamilies.has(r.tag));
const list = (shown.length ? shown : RECOMMENDED_EDIT).map((r) => r.hint ? `${agentNameOfFamily(r.tag)} (${r.hint})` : agentNameOfFamily(r.tag)).join(", ");
return `Default: auto, the recommended model. Omit unless the user asks. Alternatives: ${list}.`;
}
const presetLine = userPresetLine();
if (!inv) return `${INTRO} Names we tune: ${tunedNames().join(", ")} (installed models could not be checked).${presetLine ? `
${presetLine}` : ""}`;
const names = installedAgentNames(inv);
const lines = names.map((e) => `- ${e.name} (${e.modes.join(", ")})`);
const custom = inv.custom.filter((c) => c.ready).map((c) => `${c.name} [${c.family}]`).sort();
if (custom.length) lines.push(`- custom models: ${custom.slice(0, 5).join(", ")}${custom.length > 5 ? `, +${custom.length - 5} more` : ""}`);
if (presetLine) lines.push(presetLine);
if (!lines.length) return `${INTRO} No curated model is installed on this machine.`;
const full = `${INTRO} Installed on this machine:
${lines.join("\n")}`;
if (full.length <= (opts.maxChars ?? DEFAULT_MAX_CHARS)) return full;
return `${INTRO} Installed: ${names.map((e) => e.name).join(", ")}. An unknown name returns the full list.`;
}
async function getModelListText(req = {}) {
let timer;
try {
const inv = await Promise.race([
(async () => {
await req.prepare?.();
return currentInventory();
})(),
new Promise((resolve) => {
timer = setTimeout(() => resolve(null), req.timeoutMs ?? 3e3);
})
]);
return buildModelListText(inv, req);
} catch {
return buildModelListText(null, req);
} finally {
if (timer) clearTimeout(timer);
}
}
function prepareInventoryFetcher(ServiceCtor) {
if (hasInventoryFetcher()) return;
const conn = getEngineConnectionDefaults({
host: process.env.DRAW_THINGS_HOST,
httpPort: process.env.DRAW_THINGS_HTTP_PORT ? parseInt(process.env.DRAW_THINGS_HTTP_PORT, 10) : void 0,
grpcPort: process.env.DRAW_THINGS_GRPC_PORT ? parseInt(process.env.DRAW_THINGS_GRPC_PORT, 10) : void 0
});
new ServiceCtor((conn.grpc?.target || "127.0.0.1:7859").replace(/^grpc:\/\//i, ""));
}
// src/services/drawThingsConfigMapper.ts
var flatbuffers9 = __toESM(require_flatbuffers(), 1);
function buildDtGenerationConfiguration(p) {
const w = typeof p.width === "number" ? p.width : 576;
const h = typeof p.height === "number" ? p.height : 768;
const start_width = Math.max(1, Math.round(w / 64));
const start_height = Math.max(1, Math.round(h / 64));
let samplerEnum = 17 /* UniPCTrailing */;
let samplerName = "UniPCTrailing";
if (typeof p.sampler === "number") {
samplerEnum = p.sampler;
samplerName = Object.keys(SamplerType).find(
(k) => SamplerType[k] === p.sampler
) || "Unknown";
} else if (typeof p.sampler === "string") {
samplerName = p.sampler.replace(/\s+/g, "");
samplerEnum = SamplerType[samplerName] ?? 17 /* UniPCTrailing */;
}
const seedModeEnum = SeedMode[String(p.seed_mode || "Scale Alike").replace(/\s+/g, "")] ?? 2 /* ScaleAlike */;
const view = {
id: 1,
start_width,
start_height,
seed: typeof p.seed === "number" ? p.seed : void 0,
steps: typeof p.steps === "number" ? p.steps : void 0,
sampler: samplerName,
batch_count: typeof p.batch_count === "number" ? p.batch_count : void 0,
batch_size: typeof p.batch_size === "number" ? Math.max(1, Math.min(4, Math.round(p.batch_size))) : 1,
model: p.model || void 0,
seed_mode: String(p.seed_mode || "Scale Alike").replace(/\s+/g, ""),
t5_text: p.t5_text || void 0,
clip_l_text: p.clip_l_text || void 0,
image_guidance_scale: typeof p.image_guidance === "number" ? p.image_guidance : void 0,
tiled_decoding: !!p.tiled_decoding,
decoding_tile_width: typeof p.decoding_tile_width === "number" ? Math.max(1, Math.round(p.decoding_tile_width / 64)) : void 0,
decoding_tile_height: typeof p.decoding_tile_height === "number" ? Math.max(1, Math.round(p.decoding_tile_height / 64)) : void 0,
decoding_tile_overlap: typeof p.decoding_tile_overlap === "number" ? Math.max(0, Math.round(p.decoding_tile_overlap / 64)) : void 0,
compressionArtifacts: p.compressionArtifacts ?? p.compression_artifacts ?? void 0,
compressionArtifactsQuality: typeof p.compressionArtifactsQuality === "number" ? p.compressionArtifactsQuality : typeof p.compression_artifacts_quality === "number" ? p.compression_artifacts_quality : void 0,
num_frames: typeof p.num_frames === "number" ? p.num_frames : void 0
};
const builder = new flatbuffers9.Builder(2048);
const modelOffset = p.model ? builder.createString(p.model) : 0;
const upscalerOffset = typeof p.upscaler === "string" && p.upscaler ? builder.createString(p.upscaler) : 0;
const clipLTextOffset = p.clip_l_text ? builder.createString(p.clip_l_text) : 0;
const t5TextOffset = p.t5_text ? builder.createString(p.t5_text) : 0;
const openClipGTextOffset = p.open_clip_g_text ? builder.createString(p.open_clip_g_text) : 0;
let lorasVector = 0;
if (Array.isArray(p.loras) && p.loras.length) {
const loff = [];
for (const l of p.loras) {
const f = l.file ? builder.createString(l.file) : 0;
const wt = typeof l.weight === "number" ? l.weight : 1;
loff.push(LoRA.createLoRA(builder, f, wt, 0 /* All */));
}
lorasVector = GenerationConfiguration.createLorasVector(builder, loff);
}
GenerationConfiguration.startGenerationConfiguration(builder);
GenerationConfiguration.addId(builder, BigInt(1));
GenerationConfiguration.addStartWidth(builder, start_width);
GenerationConfiguration.addStartHeight(builder, start_height);
if (typeof p.seed === "number")
GenerationConfiguration.addSeed(builder, p.seed);
if (typeof p.steps === "number")
GenerationConfiguration.addSteps(builder, p.steps);
if (typeof p.guidance_scale === "number")
GenerationConfiguration.addGuidanceScale(builder, p.guidance_scale);
if (typeof p.strength === "number")
GenerationConfiguration.addStrength(builder, p.strength);
if (modelOffset) GenerationConfiguration.addModel(builder, modelOffset);
GenerationConfiguration.addSampler(builder, samplerEnum);
if (typeof p.batch_count === "number") {
GenerationConfiguration.addBatchCount(
builder,
p.batch_count
);
}
const batchSize = typeof p.batch_size === "number" ? Math.max(1, Math.min(4, Math.round(p.batch_size))) : 1;
GenerationConfiguration.addBatchSize(builder, batchSize);
if (typeof p.image_guidance === "number")
GenerationConfiguration.addImageGuidanceScale(builder, p.image_guidance);
GenerationConfiguration.addSeedMode(builder, seedModeEnum);
if (typeof p.clip_skip === "number")
GenerationConfiguration.addClipSkip(builder, p.clip_skip);
if (lorasVector) GenerationConfiguration.addLoras(builder, lorasVector);
if (typeof p.mask_blur === "number")
GenerationConfiguration.addMaskBlur(builder, p.mask_blur);
if (typeof p.mask_blur_outset === "number")
GenerationConfiguration.addMaskBlurOutset(builder, p.mask_blur_outset);
if (typeof p.preserve_original_after_inpaint === "boolean")
GenerationConfiguration.addPreserveOriginalAfterInpaint(builder, p.preserve_original_after_inpaint);
if (typeof p.clip_weight === "number")
GenerationConfiguration.addClipWeight(builder, p.clip_weight);
if (typeof p.image_prior_steps === "number")
GenerationConfiguration.addImagePriorSteps(builder, p.image_prior_steps);
if (typeof p.negative_original_height === "number")
GenerationConfiguration.addNegativeOriginalImageHeight(
builder,
p.negative_original_height
);
if (typeof p.negative_original_width === "number")
GenerationConfiguration.addNegativeOriginalImageWidth(
builder,
p.negative_original_width
);
if (typeof p.fps === "number")
GenerationConfiguration.addFpsId(builder, p.fps);
if (typeof p.motion_scale === "number")
GenerationConfiguration.addMotionBucketId(builder, p.motion_scale);
if (typeof p.start_frame_guidance === "number")
GenerationConfiguration.addStartFrameCfg(builder, p.start_frame_guidance);
if (typeof p.num_frames === "number")
GenerationConfiguration.addNumFrames(builder, p.num_frames);
if (typeof p.sharpness === "number")
GenerationConfiguration.addSharpness(builder, p.sharpness);
if (typeof p.shift === "number")
GenerationConfiguration.addShift(builder, p.shift);
if (typeof p.tiled_decoding === "boolean")
GenerationConfiguration.addTiledDecoding(builder, !!p.tiled_decoding);
if (typeof p.decoding_tile_width === "number")
GenerationConfiguration.addDecodingTileWidth(
builder,
Math.max(1, Math.round(p.decoding_tile_width / 64))
);
if (typeof p.decoding_tile_height === "number")
GenerationConfiguration.addDecodingTileHeight(
builder,
Math.max(1, Math.round(p.decoding_tile_height / 64))
);
if (typeof p.decoding_tile_overlap === "number")
GenerationConfiguration.addDecodingTileOverlap(
builder,
Math.max(0, Math.round(p.decoding_tile_overlap / 64))
);
if (typeof p.stochastic_sampling_gamma === "number")
GenerationConfiguration.addStochasticSamplingGamma(
builder,
p.stochastic_sampling_gamma
);
if (typeof p.tiled_diffusion === "boolean")
GenerationConfiguration.addTiledDiffusion(builder, !!p.tiled_diffusion);
if (clipLTextOffset)
GenerationConfiguration.addClipLText(builder, clipLTextOffset);
if (openClipGTextOffset)
GenerationConfiguration.addOpenClipGText(builder, openClipGTextOffset);
if (typeof p.speed_up_with_guidance_embed === "boolean")
GenerationConfiguration.addSpeedUpWithGuidanceEmbed(
builder,
!!p.speed_up_with_guidance_embed
);
if (typeof p.guidance_embed === "number")
GenerationConfiguration.addGuidanceEmbed(builder, p.guidance_embed);
if (typeof p.resolution_dependent_shift === "boolean")
GenerationConfiguration.addResolutionDependentShift(
builder,
!!p.resolution_dependent_shift
);
if (typeof p.tea_cache_start === "number")
GenerationConfiguration.addTeaCacheStart(builder, p.tea_cache_start);
if (typeof p.tea_cache_end === "number")
GenerationConfiguration.addTeaCacheEnd(builder, p.tea_cache_end);
if (typeof p.tea_cache_threshold === "number")
GenerationConfiguration.addTeaCacheThreshold(
builder,
p.tea_cache_threshold
);
if (typeof p.tea_cache === "boolean")
GenerationConfiguration.addTeaCache(builder, !!p.tea_cache);
if (typeof p.separate_t5 === "boolean")
GenerationConfiguration.addSeparateT5(builder, !!p.separate_t5);
if (t5TextOffset) GenerationConfiguration.addT5Text(builder, t5TextOffset);
if (typeof p.tea_cache_max_skip_steps === "number")
GenerationConfiguration.addTeaCacheMaxSkipSteps(
builder,
p.tea_cache_max_skip_steps
);
if (typeof p.causal_inference === "number")
GenerationConfiguration.addCausalInference(builder, p.causal_inference);
if (typeof p.causal_inference_pad === "number")
GenerationConfiguration.addCausalInferencePad(
builder,
p.causal_inference_pad
);
if (typeof p.cfg_zero_star === "boolean")
GenerationConfiguration.addCfgZeroStar(builder, !!p.cfg_zero_star);
if (typeof p.cfg_zero_init_steps === "number")
GenerationConfiguration.addCfgZeroInitSteps(builder, p.cfg_zero_init_steps);
const caValue = p.compressionArtifacts ?? p.compression_artifacts;
if (typeof caValue === "string") {
const ca = caValue;
const caEnum = ca === "h264" ? 1 /* H264 */ : ca === "h265" ? 2 /* H265 */ : ca === "jpeg" ? 3 /* Jpeg */ : 0 /* Disabled */;
GenerationConfiguration.addCompressionArtifacts(builder, caEnum);
}
const caQualityValue = p.compressionArtifactsQuality ?? p.compression_artifacts_quality;
if (typeof caQualityValue === "number")
GenerationConfiguration.addCompressionArtifactsQuality(builder, caQualityValue);
if (upscalerOffset) GenerationConfiguration.addUpscaler(builder, upscalerOffset);
const upscalerScale = p.upscaler_scale;
if (typeof upscalerScale === "number" && upscalerScale > 0)
GenerationConfiguration.addUpscalerScaleFactor(builder, upscalerScale);
const root = GenerationConfiguration.endGenerationConfiguration(builder);
GenerationConfiguration.finishGenerationConfigurationBuffer(builder, root);
const bytes = Buffer.from(builder.asUint8Array());
return { view, bytes };
}
// src/services/drawThingsService.ts
import axios from "axios";
import fs25 from "fs";
import path28 from "path";
var HTTP_SEED_MODE_FROM_CODE = {
0: "Legacy",
1: "Torch CPU Compatible",
2: "Scale Alike",
3: "NVIDIA GPU Compatible"
};
var HTTP_SEED_MODE_FROM_KEY = {
Legacy: "Legacy",
TorchCpuCompatible: "Torch CPU Compatible",
TorchCPUCompatible: "Torch CPU Compatible",
ScaleAlike: "Scale Alike",
NvidiaGpuCompatible: "NVIDIA GPU Compatible",
NvidiaGPUCompatible: "NVIDIA GPU Compatible"
};
var HTTP_SAMPLER_FROM_CODE = {
0: "DPM++ 2M Karras",
1: "Euler a",
2: "DDIM",
3: "PLMS",
4: "DPM++ SDE Karras",
5: "UniPC",
6: "LCM",
7: "Euler A Substep",
8: "DPM++ SDE Substep",
9: "TCD",
10: "Euler A Trailing",
11: "DPM++ SDE Trailing",
12: "DPM++ 2M AYS",
13: "Euler A AYS",
14: "DPM++ SDE AYS",
15: "DPM++ 2M Trailing",
16: "DDIM Trailing",
17: "UniPC Trailing",
18: "UniPC AYS",
19: "TCD Trailing"
};
var HTTP_SAMPLER_FROM_KEY = {
DPMPP2MKarras: "DPM++ 2M Karras",
EulerA: "Euler a",
DDIM: "DDIM",
PLMS: "PLMS",
DPMPPSDEKarras: "DPM++ SDE Karras",
UniPC: "UniPC",
LCM: "LCM",
EulerASubstep: "Euler A Substep",
DPMPPSDESubstep: "DPM++ SDE Substep",
TCD: "TCD",
EulerATrailing: "Euler A Trailing",
DPMPPSDETrailing: "DPM++ SDE Trailing",
DPMPP2MAYS: "DPM++ 2M AYS",
EulerAAYS: "Euler A AYS",
DPMPPSDEAYS: "DPM++ SDE AYS",
DPMPP2MTrailing: "DPM++ 2M Trailing",
DDIMTrailing: "DDIM Trailing",
UniPCTrailing: "UniPC Trailing",
UniPCAYS: "UniPC AYS",
TCDTrailing: "TCD Trailing"
};
function normalizeHttpSeedMode(value) {
if (typeof value === "number" && Number.isFinite(value)) {
return HTTP_SEED_MODE_FROM_CODE[value] ?? String(value);
}
if (typeof value === "string" && value.trim()) {
const raw = value.trim();
if (raw.includes(" ")) return raw;
const key = raw.replace(/\s+/g, "");
return HTTP_SEED_MODE_FROM_KEY[key] ?? raw;
}
return value;
}
function normalizeHttpSampler(value) {
if (typeof value === "number" && Number.isFinite(value)) {
return HTTP_SAMPLER_FROM_CODE[value] ?? String(value);
}
if (typeof value === "string" && value.trim()) {
const raw = value.trim();
if (raw.includes(" ") || raw.includes("+")) return raw;
const key = raw.replace(/\s+/g, "");
return HTTP_SAMPLER_FROM_KEY[key] ?? raw;
}
return value;
}
function applyHttpCustomOverlayFixups(overlay) {
const out = { ...overlay };
const rename = (from, to) => {
if (!Object.prototype.hasOwnProperty.call(out, from)) return;
if (!Object.prototype.hasOwnProperty.call(out, to)) out[to] = out[from];
delete out[from];
};
rename("stage2_guidance", "stage_2_guidance");
rename("stage2_shift", "stage_2_shift");
delete out.stage2_steps;
rename("stage2Guidance", "stage_2_guidance");
rename("stage2Shift", "stage_2_shift");
delete out.stage2Steps;
rename("t5_text_encoder", "t5_text_encoder_decoding");
rename("t5TextEncoder", "t5_text_encoder_decoding");
rename("image_guidance_scale", "image_guidance");
rename("imageGuidanceScale", "image_guidance");
delete out.target_image_height;
delete out.target_image_width;
delete out.targetImageHeight;
delete out.targetImageWidth;
delete out.original_image_height;
delete out.original_image_width;
delete out.originalImageHeight;
delete out.originalImageWidth;
delete out.negative_original_image_height;
delete out.negative_original_image_width;
delete out.negativeOriginalImageHeight;
delete out.negativeOriginalImageWidth;
delete out.face_restoration;
delete out.faceRestoration;
delete out.width;
delete out.height;
delete out.target_width;
delete out.target_height;
delete out.batch_count;
delete out.batch_size;
delete out.batchCount;
delete out.batchSize;
delete out.upscaler;
delete out.upscaler_scale;
delete out.upscalerScale;
const teaCache = typeof out.tea_cache === "boolean" ? out.tea_cache : typeof out.teaCache === "boolean" ? out.teaCache : void 0;
if (teaCache === false) {
delete out.tea_cache_start;
delete out.tea_cache_end;
delete out.teaCacheStart;
delete out.teaCacheEnd;
}
if (Object.prototype.hasOwnProperty.call(out, "upscaler_scale_factor")) {
if (!Object.prototype.hasOwnProperty.call(out, "upscaler_scale")) {
out.upscaler_scale = out.upscaler_scale_factor;
}
delete out.upscaler_scale_factor;
}
if (Object.prototype.hasOwnProperty.call(out, "upscalerScaleFactor")) {
if (!Object.prototype.hasOwnProperty.call(out, "upscaler_scale")) {
out.upscaler_scale = out.upscalerScaleFactor;
}
delete out.upscalerScaleFactor;
}
if (Object.prototype.hasOwnProperty.call(out, "upscalerScale")) {
delete out.upscalerScale;
}
if (Object.prototype.hasOwnProperty.call(out, "seed_mode")) {
out.seed_mode = normalizeHttpSeedMode(out.seed_mode);
}
if (Object.prototype.hasOwnProperty.call(out, "seedMode")) {
out.seedMode = normalizeHttpSeedMode(out.seedMode);
}
if (Object.prototype.hasOwnProperty.call(out, "sampler")) {
out.sampler = normalizeHttpSampler(out.sampler);
}
return out;
}
function buildAuditLogger2({
backend,
mode
}) {
const requestId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const entry = {
timestamp: logTimestamp(),
backend,
mode,
requestId
};
function setRequested(obj) {
entry.requested = obj;
}
function setUserInput(obj) {
entry.user_input = obj;
}
function setPrompt(p) {
if (typeof p === "string" && p.trim().length > 0) entry.prompt = p;
}
function setBackendReturned(obj) {
entry.backendReturned = obj;
}
function setPostProcessed(obj) {
entry.postProcessed = obj;
}
function setExtras(obj) {
entry.extras = { ...entry.extras || {}, ...obj };
}
function setInferenceTime(ms) {
entry.inference_time_ms = ms;
}
function setError(err) {
let message = "unknown error";
let status = void 0;
if (typeof err === "string") message = err;
else if (err && typeof err === "object") {
const anyErr = err;
message = anyErr.message || JSON.stringify(anyErr);
if (typeof anyErr.status === "number") status = anyErr.status;
}
entry.error = status ? { message, status } : { message };
}
async function write() {
try {
const logsDir2 = getLogsDir();
const filePath = path28.resolve(
logsDir2,
getPluginLogFilename().replace(/\.log$/, ".audit.jsonl")
);
await fs25.promises.mkdir(logsDir2, { recursive: true });
const block = JSON.stringify(entry, null, 2) + "\n\n";
await fs25.promises.appendFile(filePath, block, { encoding: "utf8" });
} catch (e) {
console.error(
"auditLog write failed:",
e instanceof Error ? e.message : String(e)
);
}
}
return {
requestId,
setPrompt,
setUserInput,
setRequested,
setBackendReturned,
setPostProcessed,
setExtras,
setInferenceTime,
setError,
write
};
}
var DrawThingsService = class {
name = "drawthings";
// make baseUrl public for compatibility with index.ts
baseUrl;
// change to public axios for compatibility
axios;
constructor(apiUrl = "http://127.0.0.1:7860", sharedSecretParam) {
this.baseUrl = apiUrl;
const sharedSecret = (sharedSecretParam ?? process.env.DRAWTHINGS_SHARED_SECRET) || void 0;
this.axios = axios.create({
baseURL: this.baseUrl,
timeout: 3e5,
// 5 minutes timeout (image generation may take time)
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Accept-Encoding": "gzip, deflate, br",
...sharedSecret ? { Authorization: `Bearer ${sharedSecret}` } : {}
}
});
console.info(
`DrawThingsService initialized, API location: ${this.baseUrl}`
);
}
/** Set new base URL and update axios instance */
setBaseUrl(url) {
this.baseUrl = url;
this.axios.defaults.baseURL = url;
console.info(`Updated API base URL to: ${url}`);
}
/** check API connection simplified version that just checks if API is available */
async checkApiConnection() {
try {
console.debug(`Checking API connection to: ${this.baseUrl}`);
const response = await this.axios.get("/sdapi/v1/options", {
timeout: 5e3,
validateStatus: (status) => status >= 200
});
const isConnected = response.status >= 200;
console.info(
`API connection check: ${isConnected ? "Success" : "Failed"}`
);
return isConnected;
} catch (error) {
console.error(`API connection check failed: ${error.message}`);
return false;
}
}
/** get default params */
getDefaultParams() {
return defaultParams;
}
/** generate image (text-to-image) */
async generateImage(inputParams = {}, _onProgress) {
const audit = buildAuditLogger2({ backend: this.name, mode: "txt2img" });
let overlaySource = "default";
let overlayPreset;
let overlayNote;
let effectiveModel;
let effectiveLoras;
try {
let startTime = 0;
let endTime = 0;
let params = {};
try {
const validationResult = validateImageGenerationParams(inputParams);
if (validationResult.valid) {
params = inputParams;
} else {
console.warn("parameter validation failed, use default params");
}
} catch (error) {
console.warn("parameter validation error:", error);
}
if (params.random_string && (!params.prompt || Object.keys(params).length === 1)) {
params.prompt = params.random_string;
delete params.random_string;
}
if (!params.prompt) {
params.prompt = inputParams.prompt || defaultParams.prompt;
}
let usedImageFormat = void 0;
try {
const fmt = inputParams.imageFormat;
if (params.width == null && params.height == null) {
if (fmt === "square") {
params.width = 1024;
params.height = 1024;
usedImageFormat = "square";
} else if (fmt === "landscape") {
params.width = 1024;
params.height = 768;
usedImageFormat = "landscape";
} else if (fmt === "portrait") {
params.width = 768;
params.height = 1024;
usedImageFormat = "portrait";
} else if (fmt === "16:9") {
params.width = 1024;
params.height = 576;
usedImageFormat = "16:9";
}
}
const variants = inputParams.variants;
if (typeof variants === "number") {
const v = Math.max(1, Math.min(4, Math.round(variants)));
params.batch_size = v;
params.batch_count = 1;
}
} catch {
}
const allowedKeys = new Set(Object.keys(defaultParams));
const filteredParams = {};
for (const [k, v] of Object.entries(params)) {
if (allowedKeys.has(k)) {
filteredParams[k] = v;
}
}
const modelId = inputParams.model;
const {
source,
presetName,
note,
params: overlayParams
} = getEffectiveOverlay(modelId, "txt2img");
const overlayParamsHttp = source === "custom" && overlayParams ? applyHttpCustomOverlayFixups(overlayParams) : overlayParams;
overlaySource = source;
overlayPreset = presetName;
overlayNote = note;
if (!modelId || !modelId.trim() || modelId === "auto") {
delete filteredParams.model;
}
if (overlayParamsHttp) {
console.info(
`Applying ${source} overlay for '${modelId ?? "auto"}' (txt2img)${presetName ? ` preset=${presetName}` : ""}`
);
delete filteredParams.model;
}
audit.setExtras({
overlay_source: source,
...presetName && { overlay_preset: presetName }
});
const effectiveSeed = source === "custom" && typeof overlayParamsHttp?.seed === "number" && Number.isFinite(overlayParamsHttp?.seed) ? overlayParamsHttp.seed : defaultParams.seed;
const effectiveSeedMode = source === "custom" && typeof overlayParamsHttp?.seed_mode === "string" && String(overlayParamsHttp.seed_mode).trim() ? String(overlayParamsHttp.seed_mode) : defaultParams.seed_mode;
const requestParams = {
...defaultParams,
...overlayParamsHttp || {},
...filteredParams,
seed: effectiveSeed,
seed_mode: effectiveSeedMode
};
effectiveModel = String(requestParams.model || "");
try {
const userSpecifiedLoras = Object.prototype.hasOwnProperty.call(
filteredParams,
"loras"
);
const overlaySelected = !!overlayParamsHttp;
if (userSpecifiedLoras) {
const ls = Array.isArray(filteredParams.loras) ? filteredParams.loras : [];
effectiveLoras = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else if (overlaySelected) {
const ls = Array.isArray(overlayParamsHttp?.loras) ? overlayParamsHttp.loras : [];
effectiveLoras = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else {
const ls = Array.isArray(requestParams?.loras) ? requestParams.loras : [];
effectiveLoras = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
}
} catch {
}
console.debug(`use prompt: "${requestParams.prompt}"`);
console.info("send request to Draw Things API...");
startTime = Date.now();
const response = await this.axios.post(
"/sdapi/v1/txt2img",
requestParams
);
endTime = Date.now();
if (!response.data || !response.data.images || response.data.images.length === 0) {
throw new Error("API did not return image data");
}
const imagesArr = response.data.images;
console.info(
`DrawThings: received ${imagesArr.length} image(s) from API`
);
const first = imagesArr[0];
const formattedFirst = first.startsWith("data:image/") ? first : `data:image/png;base64,${first}`;
const cleanBase64 = formattedFirst.includes(",") ? formattedFirst.split(",")[1] : formattedFirst.replace(/^data:image\/\w+;base64,/, "");
const imageBuffer = Buffer.from(cleanBase64, "base64");
console.info("image generation success");
try {
audit.setUserInput({
width: inputParams?.width,
height: inputParams?.height,
imageFormat: inputParams?.imageFormat
});
} catch {
}
try {
audit.setPrompt(String(requestParams.prompt || ""));
audit.setRequested({
source: "http.body",
model: String(requestParams.model || ""),
width: Number(requestParams.width),
height: Number(requestParams.height),
steps: Number(requestParams.steps)
});
} catch {
}
let backendW;
let backendH;
try {
const meta = await getSize(imageBuffer);
backendW = meta.width;
backendH = meta.height;
} catch {
}
audit.setBackendReturned({ width: backendW, height: backendH });
audit.setPostProcessed({ width: backendW, height: backendH });
audit.setInferenceTime(endTime - startTime);
const result = {
isError: false,
imageData: formattedFirst,
imageBuffer,
images: imagesArr.map(
(img) => img.startsWith("data:image/") ? img : `data:image/png;base64,${img}`
),
metadata: {
alt: `Image generated from prompt: ${requestParams.prompt}`,
inference_time_ms: endTime - startTime,
model: effectiveModel,
width: Number(requestParams.width),
height: Number(requestParams.height),
requested_dimensions: {
width: Number(requestParams.width),
height: Number(requestParams.height)
},
image_format: usedImageFormat,
steps: Number(requestParams.steps),
seed: typeof requestParams.seed === "number" && Number.isFinite(requestParams.seed) ? requestParams.seed : void 0,
seed_mode: (() => {
const sm = requestParams.seed_mode ?? requestParams.seedMode;
return typeof sm === "string" && sm.trim() ? sm : void 0;
})(),
seed_source: source === "custom" && typeof overlayParamsHttp?.seed === "number" && Number.isFinite(overlayParamsHttp?.seed) ? "custom" : "default",
seed_mode_source: source === "custom" && typeof overlayParamsHttp?.seed_mode === "string" && String(overlayParamsHttp.seed_mode).trim() ? "custom" : "default",
prompt_used: String(requestParams.prompt || ""),
prompt_origin: typeof inputParams.prompt === "string" && inputParams.prompt.trim() ? "user" : "default:drawthings:txt2img",
transport: "http",
drawthings_params: requestParams,
variantsReturned: imagesArr.length,
// Overlay source tracking for audit
overlay_source: overlaySource,
...overlayPreset && { overlay_preset: overlayPreset },
...overlayNote && { overlay_note: overlayNote },
defaults_used: "defaultParamsDrawThingsTxt2Img",
overlay_lookup_mode: "txt2img",
strength_used: typeof requestParams.strength === "number" && Number.isFinite(requestParams.strength) ? Number(requestParams.strength) : void 0,
steps_used: typeof requestParams.steps === "number" && Number.isFinite(requestParams.steps) ? Number(requestParams.steps) : void 0,
sampler_used: typeof requestParams.sampler === "string" && String(requestParams.sampler).trim() ? String(requestParams.sampler) : void 0,
guidance_scale_used: typeof requestParams.guidance_scale === "number" && Number.isFinite(requestParams.guidance_scale) ? Number(requestParams.guidance_scale) : void 0,
...effectiveLoras && effectiveLoras.length > 0 && { loras_used: effectiveLoras }
}
};
return result;
} catch (error) {
const errMsg = error instanceof Error ? error.message : String(error);
console.error(`image generation error: ${errMsg}`);
const axiosError = error;
let status = void 0;
let rawBody = void 0;
if (axiosError && axiosError.response) {
status = axiosError.response.status;
const data = axiosError.response.data;
if (typeof data === "string") rawBody = data;
else if (data !== void 0) {
try {
rawBody = JSON.stringify(data);
} catch {
rawBody = String(data);
}
}
}
if (!rawBody) {
if (typeof axiosError?.message === "string")
rawBody = axiosError.message;
else if (error instanceof Error && typeof error.message === "string")
rawBody = error.message;
else rawBody = "unknown error";
}
return {
isError: true,
status,
errorMessage: rawBody
};
}
}
/** generate image (image-to-image) */
async generateImageImg2Img(inputParams = {}, sourceBuffer, _onProgress, _maskBuffer) {
const audit = buildAuditLogger2({ backend: this.name, mode: "img2img" });
let overlaySource = "default";
let overlayPreset;
let overlayNote;
let effectiveModel;
let effectiveLoras;
try {
const i2iProfile = inputParams?._dt_i2i_profile;
const baseDefaults = i2iProfile === "zoom" ? defaultParamsZoom : i2iProfile === "restore" ? defaultParamsImg2Img3 : i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint" ? defaultParamsImg2Img2 : defaultParamsImg2Img;
const baseLimits = i2iProfile === "restore" || i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint" ? drawthingsLimits : drawthingsLimits;
let startTime = 0;
let endTime = 0;
let params = {};
try {
const validationResult = validateImageGenerationParams(inputParams);
if (validationResult.valid) {
params = inputParams;
}
} catch {
}
if (params.random_string && (!params.prompt || Object.keys(params).length === 1)) {
params.prompt = params.random_string;
delete params.random_string;
}
if (!params.prompt) {
params.prompt = inputParams.prompt || baseDefaults.prompt;
}
let usedImageFormat = void 0;
try {
const fmt = inputParams.imageFormat;
if (params.width == null && params.height == null) {
if (fmt === "square") {
params.width = 1024;
params.height = 1024;
usedImageFormat = "square";
} else if (fmt === "landscape") {
params.width = 1024;
params.height = 768;
usedImageFormat = "landscape";
} else if (fmt === "portrait") {
params.width = 768;
params.height = 1024;
usedImageFormat = "portrait";
} else if (fmt === "16:9") {
params.width = 1024;
params.height = 576;
usedImageFormat = "16:9";
}
}
const variants = inputParams.variants;
if (typeof variants === "number") {
const v = Math.max(1, Math.min(4, Math.round(variants)));
params.batch_size = v;
params.batch_count = 1;
}
} catch {
}
const allowedKeys = new Set(Object.keys(baseDefaults));
const filteredParams = {};
for (const [k, v] of Object.entries(params)) {
if (allowedKeys.has(k)) filteredParams[k] = v;
}
const modelId = i2iProfile === "zoom" ? void 0 : inputParams.model;
const overlayMode = i2iProfile === "zoom" ? "zoom" : i2iProfile === "restore" || i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint" ? i2iProfile : "img2img";
const {
source,
presetName,
note,
params: overlayParams
} = getEffectiveOverlay(modelId, overlayMode === "inpaint" || overlayMode === "outpaint" ? "edit" : overlayMode);
const overlayParamsHttp = source === "custom" && overlayParams ? applyHttpCustomOverlayFixups(overlayParams) : overlayParams;
overlaySource = source;
overlayPreset = presetName;
overlayNote = note;
if (!modelId || !modelId.trim() || modelId === "auto") {
delete filteredParams.model;
}
if (overlayParamsHttp) {
console.info(
`Applying ${source} overlay for '${modelId ?? "auto"}' (img2img)${presetName ? ` preset=${presetName}` : ""}`
);
delete filteredParams.model;
}
audit.setExtras({
overlay_source: source,
...presetName && { overlay_preset: presetName }
});
let initPng = sourceBuffer;
let srcW;
let srcH;
try {
initPng = await toPng(sourceBuffer);
const meta = await getSize(initPng);
srcW = meta.width;
srcH = meta.height;
} catch {
}
const initB64 = initPng.toString("base64");
const requestParams = {
...baseDefaults,
...overlayParamsHttp || {},
...filteredParams,
// Seed policy: allow Custom Configs to override (incl. -1); otherwise keep defaults.
seed: source === "custom" && typeof overlayParamsHttp?.seed === "number" && Number.isFinite(overlayParamsHttp?.seed) ? overlayParamsHttp.seed : baseDefaults.seed,
// Seed mode policy mirrors seed: allow Custom Configs to override; otherwise keep defaults.
seed_mode: source === "custom" && typeof overlayParamsHttp?.seed_mode === "string" && String(overlayParamsHttp.seed_mode).trim() ? String(overlayParamsHttp.seed_mode) : baseDefaults.seed_mode,
init_images: [initB64]
};
const defaultsUsed = i2iProfile === "restore" ? "defaultParamsDrawThingsRestore" : i2iProfile === "edit" ? "defaultParamsDrawThingsEdit" : "defaultParamsDrawThingsImg2Img";
const overlayLookupMode = overlayMode;
effectiveModel = String(requestParams.model || "");
try {
const userSpecifiedLoras = Object.prototype.hasOwnProperty.call(
filteredParams,
"loras"
);
const overlaySelected = !!overlayParamsHttp;
if (userSpecifiedLoras) {
const ls = Array.isArray(filteredParams.loras) ? filteredParams.loras : [];
effectiveLoras = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else if (overlaySelected) {
const ls = Array.isArray(overlayParamsHttp?.loras) ? overlayParamsHttp.loras : [];
effectiveLoras = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else {
const ls = Array.isArray(requestParams?.loras) ? requestParams.loras : [];
effectiveLoras = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
}
} catch {
}
const userReqW = (() => {
const v = filteredParams?.width ?? params?.width;
return typeof v === "number" && Number.isFinite(v) ? Math.round(v) : void 0;
})();
const userReqH = (() => {
const v = filteredParams?.height ?? params?.height;
return typeof v === "number" && Number.isFinite(v) ? Math.round(v) : void 0;
})();
if (srcW && srcH) {
requestParams.original_width = srcW;
requestParams.original_height = srcH;
}
{
const hasW = typeof requestParams.width === "number" && Number.isFinite(requestParams.width);
const hasH = typeof requestParams.height === "number" && Number.isFinite(requestParams.height);
if (!hasW)
requestParams.width = userReqW ?? srcW;
if (!hasH)
requestParams.height = userReqH ?? srcH;
const hasTW = typeof requestParams.target_width === "number" && Number.isFinite(requestParams.target_width);
const hasTH = typeof requestParams.target_height === "number" && Number.isFinite(requestParams.target_height);
if (!hasTW)
requestParams.target_width = requestParams.width;
if (!hasTH)
requestParams.target_height = requestParams.height;
}
{
const needs = inputParams?._dt_needs_upscaler;
if (typeof needs !== "boolean") {
throw new Error(
"Invariant failed: _dt_needs_upscaler must be provided by core for img2img"
);
}
if (needs && i2iProfile !== "zoom" && baseLimits.upscaleMethod !== "zoom-pass") {
requestParams.upscaler = baseLimits.upscaler;
requestParams.upscaler_scale = baseLimits.upscalerScaleFactor;
console.info(`DT img2img upscaler enabled (core)`);
} else {
requestParams.upscaler = null;
requestParams.upscaler_scale = 0;
console.info(`DT img2img upscaler disabled (core)`);
}
}
console.info(
`DT img2img size set: width=${requestParams.width}, height=${requestParams.height}, original_width=${requestParams.original_width}, original_height=${requestParams.original_height}, target_width=${requestParams.target_width}, target_height=${requestParams.target_height}, upscaler=${requestParams.upscaler ?? "-"}, upscaler_scale=${requestParams.upscaler_scale ?? "-"}`
);
console.info("send request to Draw Things API (img2img)...");
startTime = Date.now();
const response = await this.axios.post(
"/sdapi/v1/img2img",
requestParams
);
endTime = Date.now();
if (!response.data || !response.data.images || response.data.images.length === 0) {
throw new Error("API did not return image data");
}
const imagesArr = response.data.images;
const first = imagesArr[0];
const formattedFirst = first.startsWith("data:image/") ? first : `data:image/png;base64,${first}`;
const cleanBase64 = formattedFirst.includes(",") ? formattedFirst.split(",")[1] : formattedFirst.replace(/^data:image\/\w+;base64,/, "");
const imageBuffer = Buffer.from(cleanBase64, "base64");
try {
audit.setPrompt(String(requestParams.prompt || ""));
audit.setRequested({
source: "http.body",
model: String(requestParams.model || ""),
width: Number(requestParams.width),
height: Number(requestParams.height),
steps: Number(requestParams.steps),
original_width: Number(requestParams.original_width),
original_height: Number(requestParams.original_height),
target_width: Number(requestParams.target_width),
target_height: Number(requestParams.target_height)
});
if (srcW && srcH) {
audit.setExtras({ srcWidth: srcW, srcHeight: srcH });
}
} catch {
}
let backendW;
let backendH;
try {
const meta = await getSize(imageBuffer);
backendW = meta.width;
backendH = meta.height;
} catch {
}
audit.setBackendReturned({ width: backendW, height: backendH });
audit.setPostProcessed({ width: backendW, height: backendH });
audit.setInferenceTime(endTime - startTime);
const result = {
isError: false,
imageData: formattedFirst,
imageBuffer,
images: imagesArr.map(
(img) => img.startsWith("data:image/") ? img : `data:image/png;base64,${img}`
),
metadata: {
alt: `Image-to-image from prompt: ${requestParams.prompt}`,
inference_time_ms: endTime - startTime,
model: effectiveModel,
width: Number(requestParams.width),
height: Number(requestParams.height),
requested_dimensions: {
width: Number(requestParams.width),
height: Number(requestParams.height)
},
image_format: usedImageFormat,
steps: Number(requestParams.steps),
seed: typeof requestParams.seed === "number" && Number.isFinite(requestParams.seed) ? requestParams.seed : void 0,
seed_mode: (() => {
const sm = requestParams.seed_mode ?? requestParams.seedMode;
return typeof sm === "string" && sm.trim() ? sm : void 0;
})(),
prompt_used: String(requestParams.prompt || ""),
prompt_origin: typeof inputParams.prompt === "string" && inputParams.prompt.trim() ? "user" : "default:drawthings:img2img",
transport: "http",
// Overlay source tracking for audit
overlay_source: overlaySource,
...overlayPreset && { overlay_preset: overlayPreset },
...overlayNote && { overlay_note: overlayNote },
defaults_used: defaultsUsed,
overlay_lookup_mode: overlayLookupMode,
i2i_profile: i2iProfile,
strength_used: typeof requestParams.strength === "number" && Number.isFinite(requestParams.strength) ? requestParams.strength : void 0,
steps_used: typeof requestParams.steps === "number" && Number.isFinite(requestParams.steps) ? requestParams.steps : void 0,
sampler_used: typeof requestParams.sampler === "string" && String(requestParams.sampler).trim() ? String(requestParams.sampler) : void 0,
guidance_scale_used: typeof requestParams.guidance_scale === "number" && Number.isFinite(requestParams.guidance_scale) ? requestParams.guidance_scale : void 0,
...effectiveLoras && effectiveLoras.length > 0 && { loras_used: effectiveLoras }
}
};
return result;
} catch (error) {
const errMsg = error instanceof Error ? error.message : String(error);
console.error(`image2image generation error: ${errMsg}`);
const axiosError = error;
let status = void 0;
let rawBody = void 0;
if (axiosError && axiosError.response) {
status = axiosError.response.status;
const data = axiosError.response.data;
if (typeof data === "string") rawBody = data;
else if (data !== void 0) {
try {
rawBody = JSON.stringify(data);
} catch {
rawBody = String(data);
}
}
}
if (!rawBody) {
if (typeof axiosError?.message === "string")
rawBody = axiosError.message;
else if (error instanceof Error && typeof error.message === "string")
rawBody = error.message;
else rawBody = "unknown error";
}
return { isError: true, status, errorMessage: rawBody };
}
}
};
// src/services/drawThingsGrpcService.ts
import path29 from "path";
import fs26 from "fs";
import * as grpc2 from "@grpc/grpc-js";
import * as protoLoader from "@grpc/proto-loader";
import crypto2 from "crypto";
import { spawnSync } from "child_process";
import os8 from "os";
// src/helpers/tensorDecoderProfile.ts
function resolveTensorDecoderProfile(model) {
const modelId = String(model ?? "").trim().toLowerCase();
const capabilityKey = Object.keys(IMAGE_MODEL_CAPABILITY_MAP).find((key) => key.toLowerCase() === modelId) ?? Object.entries(IMAGE_MODEL_CAPABILITY_MAP).find(
([, capabilities]) => capabilities.modelFilenames?.some((filename) => filename.toLowerCase() === modelId)
)?.[0] ?? getCapabilityKeyForPreset(modelId);
if (capabilityKey === "flux-2-klein" || capabilityKey === "flux-3-klein") return "flux2-latent32";
if (capabilityKey === "qwen-image-1.0" || capabilityKey === "qwen-image-2.1" || capabilityKey === "qwen-image-2.1-turbo" || capabilityKey === "qwen-edit" || capabilityKey === "qwen-image-edit-2509" || capabilityKey === "qwen-image-edit-2511") {
return "qwen-argb";
}
return "direct-rgb";
}
// src/services/drawThingsGrpcService.ts
var __rootStartDir;
function setDrawThingsServiceRootStart(dir) {
__rootStartDir = dir && dir.trim() ? dir : void 0;
}
function __svcDir() {
if (__rootStartDir) return __rootStartDir;
try {
const p = process.argv && process.argv[1] ? process.argv[1] : process.cwd();
return path29.dirname(p);
} catch {
return process.cwd();
}
}
function __resolveProjectRootFrom(startDir) {
try {
let dir = startDir;
for (let i = 0; i < 50; i++) {
try {
const hasManifest = fs26.existsSync(path29.join(dir, "manifest.json"));
const hasPkg = fs26.existsSync(path29.join(dir, "package.json"));
if (hasManifest || hasPkg) return dir;
} catch {
}
const parent = path29.dirname(dir);
if (parent === dir) break;
dir = parent;
}
} catch {
}
{
let dir = startDir;
for (let i = 0; i < 20; i++) {
if (path29.basename(dir) === "dist") return path29.dirname(dir);
const parent = path29.dirname(dir);
if (parent === dir) break;
dir = parent;
}
}
{
let dir = startDir;
for (let i = 0; i < 5; i++) {
if (path29.basename(dir) === "src") return path29.dirname(dir);
const parent = path29.dirname(dir);
if (parent === dir) break;
dir = parent;
}
}
return startDir;
}
function __projectRoot() {
return __resolveProjectRootFrom(__svcDir());
}
function __logsDir() {
const dir = path29.join(__projectRoot(), "logs");
try {
if (!fs26.existsSync(dir)) fs26.mkdirSync(dir, { recursive: true });
} catch {
}
return dir;
}
function clientName() {
try {
return getPluginLogFilename().replace(/\.log$/, "");
} catch {
return "draw-things-plugin";
}
}
function logFile2(msg) {
const line = `${logTimestamp()} - ${requestLogPrefix()}${msg}
`;
try {
fs26.appendFileSync(path29.join(__logsDir(), getPluginLogFilename()), line);
} catch {
}
}
function logErr(msg) {
const line = `${logTimestamp()} - ERROR: ${msg}
`;
try {
fs26.appendFileSync(path29.join(__logsDir(), "error.log"), line);
} catch {
}
try {
console.error(`[${clientName()}] ${msg}`);
} catch {
}
}
function getTensorHelpersMode() {
const raw = String(process.env.DT_TENSOR_HELPERS_MODE || "auto").trim().toLowerCase();
if (raw === "ts" || raw === "node" || raw === "js") return "ts";
if (raw === "bin" || raw === "binary" || raw === "native") return "bin";
return "auto";
}
function buildTensorHelperCandidates(projectRoot, helperName, envCmd) {
const jsPath = path29.resolve(
projectRoot,
"dist",
"helpers",
`${helperName}.js`
);
const binDistPath = path29.resolve(projectRoot, "dist", "helpers", helperName);
const mode = getTensorHelpersMode();
const ordered = mode === "bin" ? [envCmd, binDistPath, jsPath] : [envCmd, jsPath, binDistPath];
return ordered.filter(Boolean);
}
function logToolSelection(context, tool3) {
if (!tool3) {
logFile2(`[tool] ${context} not found (no decoder/encoder available)`);
return;
}
logFile2(
`[tool] ${context} origin=${tool3.origin} impl=${tool3.impl} path=${tool3.display}`
);
}
function resolveExternalToolCandidates(projectRoot, helperName, envCmd) {
const candidates = buildTensorHelperCandidates(
projectRoot,
helperName,
envCmd
);
const tools = [];
for (const c of candidates) {
try {
const abs = path29.isAbsolute(c) ? c : path29.resolve(projectRoot, c);
if (!fs26.existsSync(abs)) continue;
const origin = c === envCmd ? "env" : "auto";
if (abs.endsWith(".js")) {
tools.push({
cmd: process.execPath,
argsPrefix: [abs],
display: abs,
impl: "ts",
origin
});
continue;
}
try {
const st = fs26.statSync(abs);
if ((st.mode & 73) === 0) {
try {
fs26.chmodSync(abs, 493);
} catch {
}
}
} catch {
}
tools.push({
cmd: abs,
argsPrefix: [],
display: abs,
impl: "mac-bin",
origin
});
} catch {
}
}
return tools;
}
function logToolCandidates(context, tools) {
if (!tools.length) {
logFile2(`[tool] ${context} not found (no decoder/encoder available)`);
return;
}
logFile2(
`[tool] ${context} candidates=${tools.length} primary=${tools[0].display}`
);
}
function logTensorSource(context, finals, preview, model) {
const describe = (b) => b.length >= 68 ? `${b.readUInt32LE(28)}x${b.readUInt32LE(24)}x${b.readUInt32LE(32)}ch bytes=${b.length}` : `bytes=${b.length}`;
const finalInfo = finals.length ? finals.map(describe).join(" | ") : "none";
const previewInfo = preview ? describe(preview) : "none";
const source = finals.length ? "final" : preview ? "PREVIEW-FALLBACK" : "empty";
logFile2(
`[result-source] ${context} model=${model ?? "?"} source=${source} final=[${finalInfo}] preview=[${previewInfo}]`
);
}
function normalizeNumFrames(n) {
if (n <= 1) return { value: 1 };
if ((n - 1) % 32 === 0) return { value: n };
if (n % 32 === 0) return { value: n + 1 };
const rounded = Math.round(n / 32) * 32 + 1;
const clamped = Math.max(33, Math.min(641, rounded));
return {
value: clamped,
hint: `numFrames adjusted to ${clamped} (must be multiple of 32 + 1).`
};
}
var DrawThingsGrpcService = class {
name = "drawthings";
baseUrl;
// target address host:port
client = null;
serviceName;
methodGenerate;
grpcCompression;
tlsMode = "auto";
currentSecurity = "unknown";
constructor(target2) {
this.baseUrl = target2 || process.env.DRAWTHINGS_GRPC_TARGET || `127.0.0.1:${process.env.DRAWTHINGS_GRPC_PORT || 7859}`;
this.serviceName = process.env.DRAWTHINGS_GRPC_SERVICE || "ImageGenerationService";
this.methodGenerate = "generateImage";
this.grpcCompression = (process.env.DRAWTHINGS_GRPC_COMPRESSION || "identity").toLowerCase();
this.loadClient();
}
registerInventoryFetcher() {
const client = this.client;
registerInventoryFetcher(echoFetcherForClient(client, clientName(), process.env.DRAWTHINGS_SHARED_SECRET));
}
setBaseUrl(url) {
this.baseUrl = url;
this.loadClient();
}
loadClient() {
try {
const projectRoot = __projectRoot();
const resolveProtoPath = () => {
const fromEnv = process.env.DRAWTHINGS_GRPC_PROTO;
if (fromEnv && fs26.existsSync(fromEnv)) return fromEnv;
const candidates = [
path29.resolve(projectRoot, "dist", "interfaces", "imageService.proto"),
path29.resolve(projectRoot, "src", "interfaces", "imageService.proto"),
path29.resolve(
projectRoot,
"dist",
"src",
"interfaces",
"imageService.proto"
),
path29.resolve(__svcDir(), "..", "interfaces", "imageService.proto")
];
for (const p of candidates) if (fs26.existsSync(p)) return p;
return candidates[0];
};
const protoPath = resolveProtoPath();
const opts = {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
};
const packageDef = protoLoader.loadSync(protoPath, opts);
const grpcObj = grpc2.loadPackageDefinition(packageDef) || {};
const SvcCtor = grpcObj[this.serviceName];
if (!SvcCtor) {
console.error(
`[DrawThingsGrpcService] Service not found: ${this.serviceName} (proto: ${protoPath})`
);
logErr(
`gRPC service not found: ${this.serviceName} (proto: ${protoPath})`
);
try {
const available = Object.keys(grpcObj || {});
console.error(
`[DrawThingsGrpcService] Available services: ${available.join(
", "
)}`
);
logFile2(`[gRPC] Available services: ${available.join(", ")}`);
} catch {
}
this.client = null;
return;
}
const channelOptions = {
"grpc.max_receive_message_length": 64 * 1024 * 1024,
"grpc.max_send_message_length": 64 * 1024 * 1024,
"grpc.ssl_target_name_override": "localhost",
"grpc.default_authority": "localhost"
};
const loadRootCAs = () => {
const tlsDirs = [
path29.resolve(projectRoot, "src", "interfaces", "tls"),
path29.resolve(projectRoot, "dist", "interfaces", "tls"),
path29.resolve(__svcDir(), "..", "interfaces", "tls")
];
const baseDir = tlsDirs.find((d) => {
try {
return fs26.existsSync(d);
} catch {
return false;
}
});
if (!baseDir) return void 0;
const serverPath = path29.join(baseDir, "server_crt.crt");
const rootPath = path29.join(baseDir, "root_ca.crt");
if (!fs26.existsSync(serverPath) || !fs26.existsSync(rootPath))
return void 0;
const serverTxt = fs26.readFileSync(serverPath, "utf8").replace(/\r\n/g, "\n").trim();
const rootTxt = fs26.readFileSync(rootPath, "utf8").replace(/\r\n/g, "\n").trim();
if (!/-----BEGIN CERTIFICATE-----/.test(serverTxt) || !/-----BEGIN CERTIFICATE-----/.test(rootTxt))
return void 0;
const bundle = `${serverTxt}
${rootTxt}
`;
try {
const out = path29.join(baseDir, "server.pem");
const prev = fs26.existsSync(out) ? fs26.readFileSync(out, "utf8").replace(/\r\n/g, "\n").trim() : "";
if (prev !== bundle.trim()) {
fs26.writeFileSync(out, bundle, "utf8");
console.log(`[TLS] Generated bundle: ${out}`);
} else {
console.log(`[TLS] Using existing bundle: ${out}`);
}
} catch {
}
return Buffer.from(bundle, "utf8");
};
const creds = grpc2.credentials.createSsl(loadRootCAs());
this.client = new SvcCtor(this.baseUrl, creds, channelOptions);
this.registerInventoryFetcher();
this.currentSecurity = "tls";
try {
globalThis.__DT_GRPC_TLS_MODE__ = this.tlsMode || "auto";
globalThis.__DT_GRPC_TLS_SELECTED__ = this.currentSecurity;
} catch {
}
try {
const proto = Object.getPrototypeOf(this.client) || {};
const methods = Object.getOwnPropertyNames(proto).filter(
(k) => typeof this.client[k] === "function" && k !== "constructor"
);
console.log(
`[DrawThingsGrpcService] client methods: ${methods.join(", ")}`
);
logFile2(`[gRPC] client methods: ${methods.join(", ")}`);
} catch {
}
} catch (e) {
console.error(
`[DrawThingsGrpcService] loadClient error: ${e instanceof Error ? e.message : String(e)}`
);
logErr(`loadClient error: ${e instanceof Error ? e.message : String(e)}`);
this.client = null;
}
}
async checkApiConnection() {
if (!this.client) return false;
try {
const echo = this.client["echo"]?.bind(this.client);
if (typeof echo === "function") {
const sharedSecret = process.env.DRAWTHINGS_SHARED_SECRET;
const req = { name: clientName() };
if (sharedSecret) req.sharedSecret = sharedSecret;
await new Promise((resolve, reject) => {
const started = Date.now();
echo(req, (err, resp) => {
if (err) return reject(err);
primeInventoryFromEcho(resp, Date.now() - started);
resolve();
});
});
return true;
}
} catch (e) {
try {
const msg = e && e.message ? String(e.message) : String(e);
const code = e?.code;
console.error(
`[gRPC check] echo failed (mode=${this.currentSecurity}) code=${code ?? "?"} msg=${msg}`
);
logErr(
`gRPC echo failed (mode=${this.currentSecurity}) code=${code ?? "?"} msg=${msg}`
);
} catch {
}
if (this.tlsMode === "auto") {
try {
const __dirname2 = __svcDir();
const projectRoot = __resolveProjectRootFrom(__dirname2);
const protoPath = (() => {
const fromEnv = process.env.DRAWTHINGS_GRPC_PROTO;
if (fromEnv && fs26.existsSync(fromEnv)) return fromEnv;
const c1 = path29.resolve(
projectRoot,
"src",
"interfaces",
"imageService.proto"
);
if (fs26.existsSync(c1)) return c1;
const c3 = path29.resolve(
projectRoot,
"dist",
"interfaces",
"imageService.proto"
);
if (fs26.existsSync(c3)) return c3;
return c1;
})();
const packageDef = protoLoader.loadSync(protoPath, {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
});
const grpcObj = grpc2.loadPackageDefinition(packageDef) || {};
const SvcCtor = grpcObj[this.serviceName];
if (SvcCtor) {
const root = (() => {
const pieces = [];
const tlsDirCandidates = [
path29.resolve(projectRoot, "src", "interfaces", "tls"),
path29.resolve(projectRoot, "dist", "interfaces", "tls")
];
const names = [
"ca.crt",
"ca.pem",
"server.crt",
"server.pem",
"rootCA.crt",
"rootCA.pem"
];
for (const d of tlsDirCandidates) {
for (const n of names) {
try {
const p = path29.join(d, n);
if (fs26.existsSync(p)) pieces.push(fs26.readFileSync(p));
} catch {
}
}
}
return pieces.length ? Buffer.concat(pieces) : void 0;
})();
const hostname = String(this.baseUrl || "").split(":")[0] || "localhost";
const candidateSet = /* @__PURE__ */ new Set([
hostname,
"localhost",
"server",
"drawthings",
"draw-things"
]);
try {
const { X509Certificate } = await import("crypto");
const protoDirs = [
path29.resolve(projectRoot, "src", "interfaces", "tls"),
path29.resolve(projectRoot, "dist", "interfaces", "tls")
];
const certFiles = [
"server_crt.crt",
"server_cert.crt",
"server.crt",
"server.pem",
"root_ca.crt",
"rootCA.crt",
"ca.crt",
"ca.pem"
];
for (const d of protoDirs) {
for (const f of certFiles) {
const p = path29.join(d, f);
try {
if (!fs26.existsSync(p)) continue;
const txt = fs26.readFileSync(p, "utf8");
const blocks = txt.split(/-----END CERTIFICATE-----/g).map(
(b) => b.includes("BEGIN CERTIFICATE") ? b + "-----END CERTIFICATE-----\n" : ""
).filter((b) => b.trim().length > 0);
for (const pem of blocks) {
try {
const x = new X509Certificate(pem);
const subj = x.subject || "";
const san = x.subjectAltName || "";
const m = subj.match(/CN=([^,\n]+)/);
if (m && m[1]) candidateSet.add(m[1].trim());
if (san) {
san.split(/[,]/).map((s) => s.trim()).filter((s) => /^DNS:/i.test(s)).map((s) => s.replace(/^DNS:\s*/i, "")).forEach(
(dname) => candidateSet.add(dname)
);
}
} catch {
}
}
} catch {
}
}
}
} catch {
}
const authCandidates = Array.from(candidateSet);
for (const auth of authCandidates) {
const channelOptions = {
"grpc.max_receive_message_length": 64 * 1024 * 1024,
"grpc.max_send_message_length": 64 * 1024 * 1024,
"grpc.ssl_target_name_override": auth,
"grpc.default_authority": auth
};
const creds = grpc2.credentials.createSsl(root);
this.client = new SvcCtor(this.baseUrl, creds, channelOptions);
this.registerInventoryFetcher();
this.currentSecurity = "tls";
try {
globalThis.__DT_GRPC_TLS_SELECTED__ = this.currentSecurity;
} catch {
}
try {
const echo2 = this.client["echo"]?.bind(this.client);
if (typeof echo2 === "function") {
const sharedSecret = process.env.DRAWTHINGS_SHARED_SECRET;
const req = { name: clientName() };
if (sharedSecret) req.sharedSecret = sharedSecret;
await new Promise((resolve2, reject2) => {
echo2(
req,
(err2) => err2 ? reject2(err2) : resolve2()
);
});
return true;
}
} catch (e2) {
try {
const msg = e2 && e2.message ? String(e2.message) : String(e2);
const code = e2?.code;
console.error(
`[gRPC check] TLS echo failed (authority=${auth}) code=${code ?? "?"} msg=${msg}`
);
} catch {
}
}
}
{
const channelOptions = {
"grpc.max_receive_message_length": 64 * 1024 * 1024,
"grpc.max_send_message_length": 64 * 1024 * 1024
};
const creds = grpc2.credentials.createInsecure();
this.client = new SvcCtor(this.baseUrl, creds, channelOptions);
this.registerInventoryFetcher();
this.currentSecurity = "insecure";
try {
globalThis.__DT_GRPC_TLS_SELECTED__ = this.currentSecurity;
} catch (e3) {
try {
const msg = e3 && e3.message ? String(e3.message) : String(e3);
const code = e3?.code;
console.error(
`[gRPC check] insecure echo retry failed code=${code ?? "?"} msg=${msg}`
);
} catch {
}
}
try {
const echo3 = this.client["echo"]?.bind(this.client);
if (typeof echo3 === "function") {
const sharedSecret = process.env.DRAWTHINGS_SHARED_SECRET;
const req = { name: clientName() };
if (sharedSecret) req.sharedSecret = sharedSecret;
await new Promise((resolve3, reject3) => {
echo3(
req,
(err3) => err3 ? reject3(err3) : resolve3()
);
});
return true;
}
} catch {
}
}
}
} catch {
}
}
}
const deadline = new Date(Date.now() + 8e3);
return new Promise((resolve) => {
try {
this.client.waitForReady(deadline, (err) => {
resolve(!err);
});
} catch {
resolve(false);
}
});
}
/** The generate RPC; every stream it returns is cancelled when the current render's cancel signal fires. */
cancellableGenerateCall() {
const rpc = this.client[this.methodGenerate]?.bind(this.client);
if (typeof rpc !== "function") return void 0;
return (...args) => {
const stream = rpc(...withProxyMarks(args, clientName()));
const signal = getCancelSignal();
if (signal) {
const cancel = () => stream.cancel?.();
if (signal.aborted) setImmediate(cancel);
else signal.addEventListener("abort", cancel, { once: true });
}
return stream;
};
}
ensureClient() {
if (!this.client)
throw new Error(
"gRPC client not configured. Set DRAWTHINGS_GRPC_* envs."
);
}
toBackendError(e) {
let status = void 0;
let msg = "unknown error";
if (e && typeof e === "object") {
if (typeof e.code === "number") status = e.code;
if (typeof e.details === "string") msg = e.details;
else if (typeof e.message === "string") msg = e.message;
}
return { isError: true, status, errorMessage: msg };
}
async generateImage(inputParams = {}, onProgress) {
try {
const __tmpDirs = [];
const __registerTmp = (d) => {
try {
__tmpDirs.push(d);
} catch {
}
};
const __cleanupTmp = () => {
for (const d of __tmpDirs) {
try {
fs26.rmSync(d, { recursive: true, force: true });
} catch {
}
}
};
const isVideoTxt2Vid = inputParams?._dt_video_mode === "txt2vid";
const baseDefaults = isVideoTxt2Vid ? defaultParamsText2Video : defaultParams;
const baseOverlayMode = isVideoTxt2Vid ? "txt2vid" : "txt2img";
const audit = buildAuditLogger({ backend: this.name, mode: baseOverlayMode });
this.ensureClient();
let configBytes = void 0;
let payloadWidth;
let payloadHeight;
let payloadSteps;
let payloadSeed;
let payloadSeedMode;
let payloadModel;
let payloadNumFrames = 1;
let payloadFps = 24;
let requiredModelFile;
let requiredLoraFiles;
let overlaySource = "default";
let overlayPreset;
let overlayNote;
let seedSource = "default";
let seedModeSource = "default";
let defaultsUsed;
let overlayLookupMode;
let strengthUsed;
let stepsUsed;
let samplerUsed;
let guidanceScaleUsed;
let shiftUsed;
let resolutionDependentShiftUsed;
let compressionArtifactsUsed;
let compressionArtifactsQualityUsed;
let params = {};
try {
const r = validateImageGenerationParams(inputParams);
if (r.valid) params = inputParams;
} catch {
}
if (params.random_string && (!params.prompt || Object.keys(params).length === 1)) {
params.prompt = params.random_string;
delete params.random_string;
}
if (!params.prompt)
params.prompt = inputParams.prompt || baseDefaults.prompt;
const promptOriginTxt = typeof inputParams?.prompt === "string" && String(inputParams.prompt).trim() ? "user" : `default:drawthings:${baseOverlayMode}`;
let usedImageFormat = void 0;
try {
const fmt = inputParams.imageFormat;
if (params.width == null && params.height == null) {
if (fmt === "square") {
params.width = 1024;
params.height = 1024;
usedImageFormat = "square";
} else if (fmt === "landscape") {
params.width = 1024;
params.height = 768;
usedImageFormat = "landscape";
} else if (fmt === "portrait") {
params.width = 768;
params.height = 1024;
usedImageFormat = "portrait";
} else if (fmt === "16:9") {
params.width = 1024;
params.height = 576;
usedImageFormat = "16:9";
}
}
const variants = inputParams.variants;
if (typeof variants === "number") {
const v = Math.max(1, Math.min(4, Math.round(variants)));
params.batch_size = v;
params.batch_count = 1;
}
if (isVideoTxt2Vid) {
const rawNumFrames = inputParams.numFrames;
if (typeof rawNumFrames === "number" && rawNumFrames > 1) {
const normalized = normalizeNumFrames(rawNumFrames);
params.num_frames = normalized.value;
if (normalized.hint) console.info(`[txt2vid] ${normalized.hint}`);
}
}
} catch {
}
try {
const allowedKeys = new Set(Object.keys(baseDefaults));
const filtered = {};
for (const [k, v] of Object.entries(params)) {
if (allowedKeys.has(k)) filtered[k] = v;
}
const modelId = params.model;
const {
source,
presetName,
note,
params: overlayParams
} = getEffectiveOverlay(modelId, baseOverlayMode);
const overlayParamsNoSize = (() => {
if (!overlayParams) return overlayParams;
const o = { ...overlayParams };
delete o.batch_count;
delete o.batch_size;
delete o.batchCount;
delete o.batchSize;
delete o.upscaler;
delete o.upscaler_scale;
delete o.upscalerScale;
delete o.fps;
return o;
})();
overlaySource = source;
overlayPreset = presetName;
overlayNote = note;
if (!modelId || !modelId.trim() || modelId === "auto") {
delete filtered.model;
}
if (overlayParams) {
const msg = `Applying ${source} overlay for '${modelId ?? "auto"}' (${baseOverlayMode}, gRPC)${presetName ? ` preset=${presetName}` : ""}`;
logFile2(msg);
console.info(msg);
delete filtered.model;
}
audit.setOutput({
overlay_source: source,
...presetName && { overlay_preset: presetName },
...note && { overlay_note: note }
});
const effectiveSeed = source === "custom" && typeof overlayParamsNoSize?.seed === "number" && Number.isFinite(overlayParamsNoSize?.seed) ? overlayParamsNoSize.seed : baseDefaults.seed;
const effectiveSeedMode = source === "custom" && typeof overlayParamsNoSize?.seed_mode === "string" && String(overlayParamsNoSize.seed_mode).trim() ? String(overlayParamsNoSize.seed_mode) : baseDefaults.seed_mode;
seedSource = source === "custom" && typeof overlayParamsNoSize?.seed === "number" && Number.isFinite(overlayParamsNoSize?.seed) ? "custom" : "default";
seedModeSource = source === "custom" && typeof overlayParamsNoSize?.seed_mode === "string" && String(overlayParamsNoSize.seed_mode).trim() ? "custom" : "default";
const effective = {
...baseDefaults,
...overlayParamsNoSize || {},
...filtered,
seed: effectiveSeed,
seed_mode: effectiveSeedMode
};
{
const sub = overlaySource === "custom" ? { file: "", substituted: false } : substituteInstalledPrecision(String(effective.model ?? ""), await currentInventory());
if (sub.substituted) {
const note2 = substitutionNote(String(effective.model), sub.file);
effective.model = sub.file;
overlayNote = overlayNote ? `${overlayNote} ${note2}` : note2;
logFile2(note2);
}
}
defaultsUsed = isVideoTxt2Vid ? "defaultParamsDrawThingsText2Video" : "defaultParamsDrawThingsTxt2Img";
overlayLookupMode = baseOverlayMode;
strengthUsed = typeof effective.strength === "number" && Number.isFinite(effective.strength) ? effective.strength : void 0;
stepsUsed = typeof effective.steps === "number" && Number.isFinite(effective.steps) ? effective.steps : void 0;
samplerUsed = typeof effective.sampler === "string" && String(effective.sampler).trim() ? String(effective.sampler) : void 0;
guidanceScaleUsed = typeof effective.guidance_scale === "number" && Number.isFinite(effective.guidance_scale) ? effective.guidance_scale : void 0;
shiftUsed = typeof effective.shift === "number" && Number.isFinite(effective.shift) ? effective.shift : void 0;
resolutionDependentShiftUsed = typeof effective.resolution_dependent_shift === "boolean" ? effective.resolution_dependent_shift : void 0;
compressionArtifactsUsed = typeof effective.compressionArtifacts === "string" ? effective.compressionArtifacts : typeof effective.compression_artifacts === "string" ? effective.compression_artifacts : null;
compressionArtifactsQualityUsed = typeof effective.compressionArtifactsQuality === "number" ? effective.compressionArtifactsQuality : typeof effective.compression_artifacts_quality === "number" ? effective.compression_artifacts_quality : null;
audit.setOutput({
overlay_lookup_mode: baseOverlayMode,
defaults_used: isVideoTxt2Vid ? "defaultParamsDrawThingsText2Video" : "defaultParamsDrawThingsTxt2Img",
strength_used: typeof effective.strength === "number" && Number.isFinite(effective.strength) ? effective.strength : void 0,
steps_used: typeof effective.steps === "number" && Number.isFinite(effective.steps) ? effective.steps : void 0,
sampler_used: typeof effective.sampler === "string" && String(effective.sampler).trim() ? String(effective.sampler) : void 0,
guidance_scale_used: typeof effective.guidance_scale === "number" && Number.isFinite(effective.guidance_scale) ? effective.guidance_scale : void 0,
shift_used: typeof effective.shift === "number" && Number.isFinite(effective.shift) ? effective.shift : void 0,
resolution_dependent_shift_used: typeof effective.resolution_dependent_shift === "boolean" ? effective.resolution_dependent_shift : void 0,
num_frames_used: typeof effective.num_frames === "number" ? effective.num_frames : null,
compression_artifacts_used: typeof effective.compressionArtifacts === "string" ? effective.compressionArtifacts : typeof effective.compression_artifacts === "string" ? effective.compression_artifacts : null,
compression_artifacts_quality_used: typeof effective.compressionArtifactsQuality === "number" ? effective.compressionArtifactsQuality : typeof effective.compression_artifacts_quality === "number" ? effective.compression_artifacts_quality : null
});
try {
if (typeof effective.model === "string" && effective.model.trim()) {
requiredModelFile = String(effective.model).trim();
}
const userSpecifiedLoras = Object.prototype.hasOwnProperty.call(
filtered,
"loras"
);
const overlaySelected = !!overlayParams;
if (userSpecifiedLoras) {
const ls = Array.isArray(filtered.loras) ? filtered.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else if (overlaySelected) {
const ls = Array.isArray(overlayParams?.loras) ? overlayParams.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else {
const ls = Array.isArray(effective?.loras) ? effective.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
}
} catch {
}
const cfg = buildDtGenerationConfiguration(effective);
configBytes = cfg.bytes && cfg.bytes.length ? cfg.bytes : void 0;
try {
payloadWidth = cfg?.view?.width;
payloadHeight = cfg?.view?.height;
payloadSteps = cfg?.view?.steps;
payloadSeed = cfg?.view?.seed;
payloadSeedMode = cfg?.view?.seed_mode;
payloadModel = String(effective.model || "");
payloadNumFrames = typeof effective.num_frames === "number" ? effective.num_frames : 1;
payloadFps = (typeof filtered.fps === "number" ? filtered.fps : void 0) ?? getDefaultFpsForModel(payloadModel) ?? (typeof effective.fps === "number" ? effective.fps : 24);
} catch {
}
try {
const view = cfg.view || {};
audit.setOutput({
flatbuf_num_frames: typeof view.num_frames === "number" ? view.num_frames : null
});
console.info(
`[grpc-config] fields=${Object.keys(view).join(",")}`
);
} catch {
}
} catch {
}
try {
const echo = this.client["echo"]?.bind(this.client);
if (typeof echo === "function") {
const sharedSecret2 = process.env.DRAWTHINGS_SHARED_SECRET;
const req = { name: clientName() };
if (sharedSecret2) req.sharedSecret = sharedSecret2;
const echoStarted = Date.now();
await new Promise((resolve, reject) => {
echo(req, (err, resp) => {
if (err) return reject(err);
if (resp?.sharedSecretMissing && !sharedSecret2)
return reject(
new Error(
"gRPC requires sharedSecret. Set DRAWTHINGS_SHARED_SECRET."
)
);
const echoMs = Date.now() - echoStarted;
primeInventoryFromEcho(resp, echoMs);
runInventoryShadow(resp, echoMs);
resolve();
});
});
}
} catch (e) {
throw e;
}
try {
const sharedSecret2 = process.env.DRAWTHINGS_SHARED_SECRET;
const chk = await checkDrawThingsGrpcAssets({
client: this.client,
sharedSecret: sharedSecret2 || void 0,
modelFile: requiredModelFile,
loraFiles: requiredLoraFiles
});
if (!chk.ok) {
const overlayCtx = overlaySource && overlaySource !== "default" ? `overlay=${overlaySource}${overlayPreset ? ` preset=${overlayPreset}` : ""}` : "";
logErr(
`[asset-check] ${chk.details.split("\n")[0]}${overlayCtx ? ` (${overlayCtx})` : ""}`
);
const why = chk.missingModel && requiredModelFile ? await explainRequiredFile(requiredModelFile) : null;
const details = why ? `${chk.details}
${why}` : chk.details;
return {
isError: true,
status: 400,
errorMessage: overlayCtx ? `${overlayCtx}
${details}` : details
};
}
} catch (e) {
try {
logErr(
`[asset-check] warning: ${e instanceof Error ? e.message : String(e)}`
);
} catch {
}
}
const sharedSecret = process.env.DRAWTHINGS_SHARED_SECRET;
const request = {
prompt: String(params.prompt || baseDefaults.prompt),
negativePrompt: String(params.negative_prompt || ""),
scaleFactor: 1,
keywords: [],
user: clientName(),
device: "LAPTOP",
chunked: true,
...sharedSecret ? { sharedSecret } : {}
};
if (configBytes) request.configuration = configBytes;
const cfgB64 = process.env.DRAWTHINGS_CONFIG_B64;
if (cfgB64 && typeof cfgB64 === "string" && cfgB64.trim()) {
try {
request.configuration = Buffer.from(cfgB64.trim(), "base64");
} catch {
}
}
const call = this.cancellableGenerateCall();
if (typeof call !== "function")
throw new Error(`gRPC method not found: ${this.methodGenerate}`);
const startTime = Date.now();
const imagesBuffers = [];
const audioBuffers = [];
let chunkAccum = null;
let previewBuf = null;
let lastSeenStep = 0;
const handleData = (resp) => {
try {
if (resp?.currentSignpost?.sampling?.step) {
const currentStep = resp.currentSignpost.sampling.step;
lastSeenStep = currentStep;
console.info(
`gRPC progress: sampling step=${currentStep}`
);
logFile2(
`t2i progress: sampling step=${currentStep}`
);
if (onProgress) {
try {
onProgress(
currentStep,
payloadSteps,
`Sampling step ${currentStep}${payloadSteps ? `/${payloadSteps}` : ""}`
);
} catch {
}
}
} else if (resp?.currentSignpost != null && onProgress) {
const sp = resp.currentSignpost;
let label;
if (lastSeenStep === 0) {
if (sp.textEncoded != null) label = "Loading...";
else if (sp.imageEncoded != null) label = "Processing...";
} else {
label = "Finishing...";
}
if (label) {
try {
onProgress(-1, payloadSteps, label);
} catch {
}
}
}
if (resp?.generatedImages && Array.isArray(resp.generatedImages)) {
const list = resp.generatedImages.map(
(b) => Buffer.isBuffer(b) ? b : Buffer.from(b)
);
const cs = resp?.chunkState;
const isMore = cs === 1 || cs === "MORE_CHUNKS";
const isLast = cs === 0 || cs === "LAST_CHUNK";
if (isMore) {
if (list.length > 0) {
chunkAccum = chunkAccum ? Buffer.concat([chunkAccum, list[0]]) : Buffer.from(list[0]);
}
} else if (isLast && list.length > 0) {
if (chunkAccum) {
const full = Buffer.concat([chunkAccum, list[0]]);
imagesBuffers.push(full);
chunkAccum = null;
} else {
for (const buf of list) imagesBuffers.push(buf);
}
} else {
for (const buf of list) imagesBuffers.push(buf);
}
}
if (resp?.previewImage) {
const b = resp.previewImage;
previewBuf = Buffer.isBuffer(b) ? b : Buffer.from(b);
}
if (resp?.generatedAudio && Array.isArray(resp.generatedAudio)) {
for (const a of resp.generatedAudio) {
const ab = Buffer.isBuffer(a) ? a : Buffer.from(a);
if (ab.length > 0) audioBuffers.push(ab);
}
}
} catch {
}
};
await new Promise((resolve, reject) => {
try {
const accept = process.env.DRAWTHINGS_GRPC_ACCEPT_ENCODING;
const md = new grpc2.Metadata();
if (accept && accept.trim()) {
md.add("grpc-accept-encoding", accept.trim());
}
const stream = md.get("grpc-accept-encoding").length > 0 ? call(request, md) : call(request);
stream.on("data", handleData);
stream.on("error", (err) => reject(err));
stream.on("end", () => resolve());
} catch (e) {
reject(e);
}
});
const endTime = Date.now();
let primaryBuf;
logTensorSource("t2i", imagesBuffers, previewBuf, payloadModel);
if (imagesBuffers.length > 0) primaryBuf = imagesBuffers[0];
else if (previewBuf) primaryBuf = previewBuf;
if (!primaryBuf) throw new Error("gRPC stream yielded no image data");
const decoderTools = resolveExternalToolCandidates(
__projectRoot(),
"GRPCBin2PNG",
process.env.DT_DECODER_CMD
);
logToolCandidates("t2i decode", decoderTools);
const decoderProfile = resolveTensorDecoderProfile(payloadModel);
const decodedBuffers = [];
if (decoderTools.length) {
const finalW = Number(params.width || baseDefaults.width || 1024);
const finalH = Number(params.height || baseDefaults.height || 1024);
for (let i = 0; i < imagesBuffers.length; i++) {
try {
const tmpDir = fs26.mkdtempSync(
path29.join(os8.tmpdir(), `${clientName()}-dt-`)
);
__registerTmp(tmpDir);
const inPath = path29.join(tmpDir, `img-${i + 1}.bin`);
const outPath = path29.join(tmpDir, `img-${i + 1}.png`);
fs26.writeFileSync(inPath, imagesBuffers[i]);
const args = [
"--in",
inPath,
"--out",
outPath,
"--profile",
decoderProfile
];
let decoded = null;
for (const tool3 of decoderTools) {
const proc = spawnSync(tool3.cmd, [...tool3.argsPrefix, ...args], {
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env }
});
if (proc.error) {
logErr(
`[decoder] exception via ${tool3.display}: ${proc.error.message}`
);
continue;
}
if (proc.status !== 0) {
logErr(
`[decoder] exit=${proc.status} via ${tool3.display} stderr=${proc.stderr?.toString?.() || ""}`
);
continue;
}
if (fs26.existsSync(outPath) && fs26.statSync(outPath).size > 0) {
decoded = fs26.readFileSync(outPath);
break;
}
logErr(
`[decoder] no output via ${tool3.display}; outPath missing/empty`
);
}
if (decoded) decodedBuffers.push(decoded);
else decodedBuffers.push(imagesBuffers[i]);
} catch {
decodedBuffers.push(imagesBuffers[i]);
logErr(
`[decoder] exception decoding t2i img-${i + 1}.bin; kept raw`
);
}
}
if (decodedBuffers.length > 0) {
logFile2(
`[decoder] t2i: decoded ${decodedBuffers.length} frame(s) \u2192 PNG via ${decoderTools[0].display}`
);
}
}
let finalBuffers = decoderTools.length ? decodedBuffers : imagesBuffers;
if ((!finalBuffers || finalBuffers.length === 0) && previewBuf) {
if (decoderTools.length) {
try {
const tmpDir = fs26.mkdtempSync(
path29.join(os8.tmpdir(), `${clientName()}-dt-`)
);
__registerTmp(tmpDir);
const inPath = path29.join(tmpDir, `preview.bin`);
const outPath = path29.join(tmpDir, `preview.png`);
fs26.writeFileSync(inPath, previewBuf);
const finalW = Number(params.width || baseDefaults.width || 1024);
const finalH = Number(
params.height || baseDefaults.height || 1024
);
const args = [
"--in",
inPath,
"--out",
outPath,
"--profile",
decoderProfile
];
let decodedPrev = null;
for (const tool3 of decoderTools) {
const proc = spawnSync(tool3.cmd, [...tool3.argsPrefix, ...args], {
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env }
});
if (proc.error) continue;
if (proc.status !== 0) continue;
if (fs26.existsSync(outPath) && fs26.statSync(outPath).size > 0) {
decodedPrev = fs26.readFileSync(outPath);
logFile2(
`[decoder] decoded preview.bin \u2192 PNG (${decodedPrev.length} bytes) via ${tool3.display}`
);
break;
}
}
finalBuffers = decodedPrev ? [decodedPrev] : [previewBuf];
} catch {
finalBuffers = [previewBuf];
}
} else {
finalBuffers = [previewBuf];
}
}
const pngCandidate = finalBuffers[0];
const effW = Number(
payloadWidth ?? params.width ?? baseDefaults.width ?? 1024
);
const effH = Number(
payloadHeight ?? params.height ?? baseDefaults.height ?? 1024
);
const dataUrl = `data:image/png;base64,${pngCandidate.toString(
"base64"
)}`;
logFile2(
`t2i completed: variants=${finalBuffers.length}, chunks=${imagesBuffers.length}, bytes=${pngCandidate.length}`
);
const result = {
isError: false,
imageBuffer: pngCandidate,
imageData: dataUrl,
images: finalBuffers.length ? finalBuffers.map(
(b) => `data:image/png;base64,${b.toString("base64")}`
) : void 0,
metadata: {
alt: `Image generated from prompt: ${request.prompt}`,
inference_time_ms: endTime - startTime,
model: payloadModel,
width: effW,
height: effH,
requested_dimensions: {
width: effW,
height: effH
},
steps: Number.isFinite(Number(payloadSteps)) ? Number(payloadSteps) : void 0,
seed: typeof payloadSeed === "number" && Number.isFinite(payloadSeed) ? payloadSeed : void 0,
seed_mode: typeof payloadSeedMode === "string" && payloadSeedMode.trim() ? payloadSeedMode : void 0,
seed_source: seedSource,
seed_mode_source: seedModeSource,
prompt_used: String(request.prompt || ""),
prompt_origin: promptOriginTxt,
...configBytes && { config_v2: generationConfigBytesToV2(configBytes) },
transport: "grpc",
stream_chunks: imagesBuffers.length,
num_frames: payloadNumFrames,
fps: payloadFps,
// Overlay source tracking for audit
overlay_source: overlaySource,
...overlayPreset && { overlay_preset: overlayPreset },
...overlayNote && { overlay_note: overlayNote },
...defaultsUsed && { defaults_used: defaultsUsed },
...overlayLookupMode && { overlay_lookup_mode: overlayLookupMode },
...typeof strengthUsed === "number" && { strength_used: strengthUsed },
...typeof stepsUsed === "number" && { steps_used: stepsUsed },
...samplerUsed && { sampler_used: samplerUsed },
...typeof guidanceScaleUsed === "number" && {
guidance_scale_used: guidanceScaleUsed
},
...typeof shiftUsed === "number" && { shift_used: shiftUsed },
...typeof resolutionDependentShiftUsed === "boolean" && {
resolution_dependent_shift_used: resolutionDependentShiftUsed
},
...compressionArtifactsUsed != null && {
compression_artifacts_used: compressionArtifactsUsed
},
...compressionArtifactsQualityUsed != null && {
compression_artifacts_quality_used: compressionArtifactsQualityUsed
},
...requiredLoraFiles && requiredLoraFiles.length > 0 && { loras_used: requiredLoraFiles }
},
audioBuffers: audioBuffers.length > 0 ? audioBuffers : void 0
};
__cleanupTmp();
return result;
} catch (e) {
try {
} catch {
}
return this.toBackendError(e);
}
}
async generateImageImg2Img(inputParams = {}, sourceBuffer, onProgress, maskBuffer) {
try {
const __tmpDirs = [];
const __registerTmp = (d) => {
try {
__tmpDirs.push(d);
} catch {
}
};
const __cleanupTmp = () => {
for (const d of __tmpDirs) {
try {
fs26.rmSync(d, { recursive: true, force: true });
} catch {
}
}
};
const isVideoImg2Vid = inputParams?._dt_video_mode === "img2vid";
const i2iProfile = isVideoImg2Vid ? void 0 : inputParams?._dt_i2i_profile;
const auditMode = isVideoImg2Vid ? "img2vid" : i2iProfile === "zoom" ? "zoom" : i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint" || i2iProfile === "restore" ? "edit" : "img2img";
const audit = buildAuditLogger({ backend: this.name, mode: auditMode });
this.ensureClient();
const baseDefaults = isVideoImg2Vid ? defaultParamsImage2Video : i2iProfile === "zoom" ? defaultParamsZoom : i2iProfile === "restore" ? defaultParamsImg2Img3 : i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint" ? defaultParamsImg2Img2 : defaultParamsImg2Img;
const baseLimits = isVideoImg2Vid ? drawthingsLimits : i2iProfile === "restore" || i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint" ? drawthingsLimits : drawthingsLimits;
let params = {};
try {
const r = validateImageGenerationParams(inputParams);
if (r.valid) params = inputParams;
} catch {
}
if (params.random_string && (!params.prompt || Object.keys(params).length === 1)) {
params.prompt = params.random_string;
delete params.random_string;
}
if (!params.prompt)
params.prompt = inputParams.prompt || baseDefaults.prompt;
const promptOriginI2I = typeof inputParams?.prompt === "string" && String(inputParams.prompt).trim() ? "user" : `default:drawthings:${isVideoImg2Vid ? "img2vid" : "img2img"}`;
let usedImageFormat = void 0;
try {
const fmt = inputParams.imageFormat;
if (fmt === "square") {
params.width = 1024;
params.height = 1024;
usedImageFormat = "square";
} else if (fmt === "landscape") {
params.width = 1024;
params.height = 768;
usedImageFormat = "landscape";
} else if (fmt === "portrait") {
params.width = 768;
params.height = 1024;
usedImageFormat = "portrait";
} else if (fmt === "16:9") {
params.width = 1024;
params.height = 576;
usedImageFormat = "16:9";
}
const variants = inputParams.variants;
if (typeof variants === "number") {
const v = Math.max(1, Math.min(4, Math.round(variants)));
params.batch_size = v;
params.batch_count = 1;
}
if (isVideoImg2Vid) {
const rawNumFrames = inputParams.numFrames;
if (typeof rawNumFrames === "number" && rawNumFrames > 1) {
const normalized = normalizeNumFrames(rawNumFrames);
params.num_frames = normalized.value;
if (normalized.hint) console.info(`[img2vid] ${normalized.hint}`);
}
}
} catch {
}
let initPng = sourceBuffer;
let srcW;
let srcH;
try {
const meta = await getSize(sourceBuffer);
srcW = meta.width;
srcH = meta.height;
initPng = await toPng(sourceBuffer);
} catch {
}
const userReqW = (() => {
const v = inputParams?.width;
return typeof v === "number" && Number.isFinite(v) ? Math.round(v) : void 0;
})();
const userReqH = (() => {
const v = inputParams?.height;
return typeof v === "number" && Number.isFinite(v) ? Math.round(v) : void 0;
})();
if (srcW && srcH) {
params.original_width = srcW;
params.original_height = srcH;
const hasW = typeof params.width === "number" && Number.isFinite(params.width);
const hasH = typeof params.height === "number" && Number.isFinite(params.height);
if (!hasW) params.width = userReqW ?? srcW;
if (!hasH) params.height = userReqH ?? srcH;
const hasTW = typeof params.target_width === "number" && Number.isFinite(params.target_width);
const hasTH = typeof params.target_height === "number" && Number.isFinite(params.target_height);
if (!hasTW) params.target_width = params.width;
if (!hasTH) params.target_height = params.height;
}
let configBytes = void 0;
let payloadWidth;
let payloadHeight;
let payloadSteps;
let payloadSeed;
let payloadSeedMode;
let payloadModel;
let payloadNumFrames = 1;
let payloadFps = 24;
let requiredModelFile;
let requiredLoraFiles;
let overlaySource = "default";
let overlayPreset;
let overlayNote;
let defaultsUsed;
let overlayLookupMode;
let i2iProfileUsed;
let strengthUsed;
let stepsUsed;
let samplerUsed;
let guidanceScaleUsed;
let shiftUsed;
let resolutionDependentShiftUsed;
let compressionArtifactsUsed;
let compressionArtifactsQualityUsed;
try {
const allowedKeys = new Set(Object.keys(baseDefaults));
const filtered = {};
for (const [k, v] of Object.entries(params)) {
if (allowedKeys.has(k)) filtered[k] = v;
}
const modelId = i2iProfile === "zoom" ? void 0 : params.model;
const overlayMode = isVideoImg2Vid ? "img2vid" : i2iProfile === "zoom" ? "zoom" : i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint" || i2iProfile === "restore" ? i2iProfile : "img2img";
const {
source,
presetName,
note,
params: overlayParams
} = getEffectiveOverlay(modelId, overlayMode === "inpaint" || overlayMode === "outpaint" ? "edit" : overlayMode);
const overlayParamsNoSize = (() => {
if (!overlayParams) return overlayParams;
const o = { ...overlayParams };
delete o.width;
delete o.height;
delete o.batch_count;
delete o.batch_size;
delete o.batchCount;
delete o.batchSize;
delete o.upscaler;
delete o.upscaler_scale;
delete o.upscalerScale;
delete o.fps;
return o;
})();
overlaySource = source;
overlayPreset = presetName;
overlayNote = note;
if (!modelId || !modelId.trim() || modelId === "auto") {
delete filtered.model;
}
if (overlayParams) {
const msg = `Applying ${source} overlay for '${modelId ?? "auto"}' (${overlayMode}, gRPC)${presetName ? ` preset=${presetName}` : ""}`;
logFile2(msg);
console.info(msg);
delete filtered.model;
}
if (i2iProfile === "zoom") {
delete filtered.model;
delete filtered.strength;
if (overlayParamsNoSize) delete overlayParamsNoSize.strength;
}
audit.setOutput({
overlay_source: source,
...presetName && { overlay_preset: presetName },
...note && { overlay_note: note }
});
const effectiveSeed = source === "custom" && typeof overlayParamsNoSize?.seed === "number" && Number.isFinite(overlayParamsNoSize?.seed) ? overlayParamsNoSize.seed : baseDefaults.seed;
const effective = {
...baseDefaults,
...overlayParamsNoSize || {},
...filtered,
seed: effectiveSeed
};
{
const sub = overlaySource === "custom" ? { file: "", substituted: false } : substituteInstalledPrecision(String(effective.model ?? ""), await currentInventory());
if (sub.substituted) {
const note2 = substitutionNote(String(effective.model), sub.file);
effective.model = sub.file;
overlayNote = overlayNote ? `${overlayNote} ${note2}` : note2;
logFile2(note2);
}
}
if ((i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint") && (typeof effective.model !== "string" || !effective.model.trim())) {
throw new Error(
`No usable edit model found. Requested model: '${modelId ?? "auto"}'. Check that a custom config or model overlay is registered for mode='edit'.`
);
}
defaultsUsed = isVideoImg2Vid ? "defaultParamsDrawThingsImage2Video" : i2iProfile === "zoom" ? "defaultParamsZoom" : i2iProfile === "restore" ? "defaultParamsDrawThingsRestore" : i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint" ? "defaultParamsDrawThingsEdit" : "defaultParamsDrawThingsImg2Img";
overlayLookupMode = overlayMode;
i2iProfileUsed = isVideoImg2Vid ? void 0 : i2iProfile;
strengthUsed = typeof effective.strength === "number" && Number.isFinite(effective.strength) ? effective.strength : void 0;
stepsUsed = typeof effective.steps === "number" && Number.isFinite(effective.steps) ? effective.steps : void 0;
samplerUsed = typeof effective.sampler === "string" && String(effective.sampler).trim() ? String(effective.sampler) : void 0;
guidanceScaleUsed = typeof effective.guidance_scale === "number" && Number.isFinite(effective.guidance_scale) ? effective.guidance_scale : void 0;
shiftUsed = typeof effective.shift === "number" && Number.isFinite(effective.shift) ? effective.shift : void 0;
resolutionDependentShiftUsed = typeof effective.resolution_dependent_shift === "boolean" ? effective.resolution_dependent_shift : void 0;
compressionArtifactsUsed = typeof effective.compressionArtifacts === "string" ? effective.compressionArtifacts : typeof effective.compression_artifacts === "string" ? effective.compression_artifacts : null;
compressionArtifactsQualityUsed = typeof effective.compressionArtifactsQuality === "number" ? effective.compressionArtifactsQuality : typeof effective.compression_artifacts_quality === "number" ? effective.compression_artifacts_quality : null;
{
const defaultsUsed2 = isVideoImg2Vid ? "defaultParamsDrawThingsImage2Video" : i2iProfile === "zoom" ? "defaultParamsZoom" : i2iProfile === "restore" ? "defaultParamsDrawThingsRestore" : i2iProfile === "edit" ? "defaultParamsDrawThingsEdit" : "defaultParamsDrawThingsImg2Img";
audit.setOutput({
overlay_lookup_mode: overlayMode === "inpaint" || overlayMode === "outpaint" ? "edit" : overlayMode,
defaults_used: defaultsUsed2,
i2i_profile: i2iProfile,
strength_used: typeof effective.strength === "number" && Number.isFinite(effective.strength) ? effective.strength : void 0,
steps_used: typeof effective.steps === "number" && Number.isFinite(effective.steps) ? effective.steps : void 0,
sampler_used: typeof effective.sampler === "string" && String(effective.sampler).trim() ? String(effective.sampler) : void 0,
guidance_scale_used: typeof effective.guidance_scale === "number" && Number.isFinite(effective.guidance_scale) ? effective.guidance_scale : void 0,
shift_used: typeof effective.shift === "number" && Number.isFinite(effective.shift) ? effective.shift : void 0,
resolution_dependent_shift_used: typeof effective.resolution_dependent_shift === "boolean" ? effective.resolution_dependent_shift : void 0,
num_frames_used: typeof effective.num_frames === "number" ? effective.num_frames : null,
compression_artifacts_used: typeof effective.compressionArtifacts === "string" ? effective.compressionArtifacts : typeof effective.compression_artifacts === "string" ? effective.compression_artifacts : null,
compression_artifacts_quality_used: typeof effective.compressionArtifactsQuality === "number" ? effective.compressionArtifactsQuality : typeof effective.compression_artifacts_quality === "number" ? effective.compression_artifacts_quality : null
});
}
try {
if (typeof effective.model === "string" && effective.model.trim()) {
requiredModelFile = String(effective.model).trim();
}
const userSpecifiedLoras = Object.prototype.hasOwnProperty.call(
filtered,
"loras"
);
const overlaySelected = !!overlayParams;
if (userSpecifiedLoras) {
const ls = Array.isArray(filtered.loras) ? filtered.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else if (overlaySelected) {
const ls = Array.isArray(overlayParams?.loras) ? overlayParams.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else {
const ls = Array.isArray(effective?.loras) ? effective.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
}
} catch {
}
{
const needs = inputParams?._dt_needs_upscaler;
if (typeof needs !== "boolean") {
throw new Error(
`Invariant failed: _dt_needs_upscaler must be provided by core for ${i2iProfile}`
);
}
if (needs && i2iProfile !== "zoom" && baseLimits.upscaleMethod !== "zoom-pass") {
effective.upscaler = baseLimits.upscaler;
effective.upscaler_scale = baseLimits.upscalerScaleFactor;
console.info(`DT gRPC ${i2iProfile} upscaler enabled (core)`);
} else {
effective.upscaler = null;
effective.upscaler_scale = 0;
console.info(`DT gRPC ${i2iProfile} upscaler disabled (core)`);
}
}
const cfg = buildDtGenerationConfiguration(effective);
configBytes = cfg.bytes && cfg.bytes.length ? cfg.bytes : void 0;
try {
const view = cfg?.view || {};
payloadWidth = view.width;
payloadHeight = view.height;
payloadSteps = view.steps;
payloadSeed = view.seed;
payloadSeedMode = view.seed_mode;
payloadModel = String(effective.model || "");
payloadNumFrames = typeof effective.num_frames === "number" ? effective.num_frames : 1;
payloadFps = (typeof filtered.fps === "number" ? filtered.fps : void 0) ?? getDefaultFpsForModel(payloadModel) ?? (typeof effective.fps === "number" ? effective.fps : 24);
} catch {
}
try {
const view = cfg.view || {};
audit.setOutput({
flatbuf_num_frames: typeof view.num_frames === "number" ? view.num_frames : null
});
console.info(
`[grpc-config] fields=${Object.keys(view).join(",")}`
);
} catch {
}
} catch {
}
try {
const sharedSecret = process.env.DRAWTHINGS_SHARED_SECRET;
const chk = await checkDrawThingsGrpcAssets({
client: this.client,
sharedSecret: sharedSecret || void 0,
modelFile: requiredModelFile,
loraFiles: requiredLoraFiles
});
if (!chk.ok) {
logErr(`[asset-check] ${chk.details.split("\n")[0]}`);
__cleanupTmp();
const why = chk.missingModel && requiredModelFile ? await explainRequiredFile(requiredModelFile) : null;
const details = why ? `${chk.details}
${why}` : chk.details;
return {
isError: true,
status: 400,
errorMessage: overlaySource && overlaySource !== "default" ? `overlay=${overlaySource}${overlayPreset ? ` preset=${overlayPreset}` : ""}
${details}` : details
};
}
} catch (e) {
try {
logErr(
`[asset-check] warning: ${e instanceof Error ? e.message : String(e)}`
);
} catch {
}
}
try {
const sharedSecret = process.env.DRAWTHINGS_SHARED_SECRET;
const chk = await checkDrawThingsGrpcAssets({
client: this.client,
sharedSecret: sharedSecret || void 0,
modelFile: requiredModelFile,
loraFiles: requiredLoraFiles
});
if (!chk.ok) {
logErr(`[asset-check] ${chk.details.split("\n")[0]}`);
const why = chk.missingModel && requiredModelFile ? await explainRequiredFile(requiredModelFile) : null;
const details = why ? `${chk.details}
${why}` : chk.details;
return {
isError: true,
status: 400,
errorMessage: overlaySource && overlaySource !== "default" ? `overlay=${overlaySource}${overlayPreset ? ` preset=${overlayPreset}` : ""}
${details}` : details
};
}
} catch (e) {
try {
logErr(
`[asset-check] warning: ${e instanceof Error ? e.message : String(e)}`
);
} catch {
}
}
const sharedSecret2 = process.env.DRAWTHINGS_SHARED_SECRET;
const request = {
prompt: String(params.prompt || defaultParamsImg2Img.prompt),
negativePrompt: String(params.negative_prompt || ""),
scaleFactor: 1,
keywords: [],
user: clientName(),
device: "LAPTOP",
chunked: true,
...sharedSecret2 ? { sharedSecret: sharedSecret2 } : {}
};
if (configBytes) request.configuration = configBytes;
const projectRoot2 = __resolveProjectRootFrom(__svcDir());
const encoderTools = resolveExternalToolCandidates(
projectRoot2,
"PNG2GRPCBin",
process.env.DT_ENCODER_CMD
);
logToolCandidates("i2i encode", encoderTools);
if (encoderTools.length) {
try {
const tmpDir = fs26.mkdtempSync(
path29.join(os8.tmpdir(), `${clientName()}-enc-`)
);
__registerTmp(tmpDir);
const pngPath = path29.join(tmpDir, "input.png");
const imgBinPath = path29.join(tmpDir, "image.bin");
fs26.writeFileSync(pngPath, initPng);
const args = ["--in", pngPath, "--out", imgBinPath];
let lastStdout = "";
let lastStderr = "";
let blob = null;
let toolUsed = null;
for (const tool3 of encoderTools) {
try {
try {
if (fs26.existsSync(imgBinPath)) fs26.unlinkSync(imgBinPath);
} catch {
}
const proc = spawnSync(tool3.cmd, [...tool3.argsPrefix, ...args], {
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env }
});
if (proc.error) {
lastStderr = proc.error.message;
logErr(
`[i2i-encode] exception via ${tool3.display}: ${lastStderr}`
);
continue;
}
lastStdout = (proc.stdout || Buffer.alloc(0)).toString("utf8").trim();
lastStderr = (proc.stderr || Buffer.alloc(0)).toString("utf8").trim();
if (typeof proc.status === "number" && proc.status !== 0) {
logErr(
`[i2i-encode] exit=${proc.status} via ${tool3.display} stderr=${lastStderr}`
);
continue;
}
if (fs26.existsSync(imgBinPath) && fs26.statSync(imgBinPath).size > 0) {
blob = fs26.readFileSync(imgBinPath);
toolUsed = tool3;
break;
}
logErr(
`[i2i-encode] no output via ${tool3.display}; image.bin missing/empty stdout=${lastStdout}`
);
} catch (e) {
logErr(
`[i2i-encode] exception via ${tool3.display}: ${e instanceof Error ? e.message : String(e)}`
);
continue;
}
}
if (blob && toolUsed) {
let imgHashBuf = null;
if (/^[0-9a-fA-F]{64}$/.test(lastStdout)) {
imgHashBuf = Buffer.from(lastStdout, "hex");
} else {
const h = crypto2.createHash("sha256").update(blob).digest();
imgHashBuf = h;
}
const hashHex = imgHashBuf.toString("hex");
logFile2(
`[encoder] encoded input.png \u2192 image.bin (${blob.length} bytes) via ${toolUsed.display}`
);
try {
const filesExist2 = this.client["filesExist"]?.bind(
this.client
);
if (typeof filesExist2 === "function") {
await new Promise((resolve) => {
filesExist2(
{
files: [],
filesWithHash: [hashHex],
...sharedSecret2 ? { sharedSecret: sharedSecret2 } : {}
},
(err, resp) => {
if (err) {
logErr(
`FilesExist error: ${err?.message || String(err)}`
);
return resolve();
}
try {
const existArr = Array.isArray(
resp?.existences
) ? resp.existences : [];
const exists = existArr[0] === true;
logFile2(
`[CAS] FilesExist hash=${hashHex} exists=${exists}`
);
if (!exists) {
try {
const upload = this.client["uploadFile"]?.call(this.client);
if (upload && typeof upload.write === "function") {
const fname = `image-${hashHex}.bin`;
upload.write({
initRequest: {
filename: fname,
sha256: imgHashBuf,
totalSize: blob.length
},
...sharedSecret2 ? { sharedSecret: sharedSecret2 } : {}
});
upload.write({
chunk: {
content: blob,
filename: fname,
offset: 0
},
...sharedSecret2 ? { sharedSecret: sharedSecret2 } : {}
});
upload.end();
upload.on(
"end",
() => logFile2(
`[CAS] UploadFile completed hash=${hashHex} size=${blob.length}`
)
);
upload.on(
"error",
(ue) => logErr(
`[CAS] UploadFile error: ${ue?.message || String(ue)}`
)
);
}
} catch (ue) {
logErr(
`[CAS] UploadFile exception: ${ue?.message || String(ue)}`
);
}
}
} catch {
}
resolve();
}
);
});
}
} catch {
}
request.image = imgHashBuf;
request.contents = [blob];
logFile2(
`[i2i-encode] built image.bin (${blob.length} bytes) hash=${imgHashBuf.toString("hex")}`
);
if (maskBuffer) {
try {
const maskPngPath = path29.join(tmpDir, "mask.png");
const maskBinPath = path29.join(tmpDir, "mask.bin");
fs26.writeFileSync(maskPngPath, maskBuffer);
const maskArgs = ["--in", maskPngPath, "--out", maskBinPath, "--mode", "mask"];
let maskStdout = "";
const maskProc = spawnSync(toolUsed.cmd, [...toolUsed.argsPrefix, ...maskArgs], {
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env }
});
maskStdout = (maskProc.stdout || Buffer.alloc(0)).toString("utf8").trim();
if (!maskProc.error && (typeof maskProc.status !== "number" || maskProc.status === 0) && fs26.existsSync(maskBinPath) && fs26.statSync(maskBinPath).size > 0) {
const maskBlob = fs26.readFileSync(maskBinPath);
let maskHashBuf;
if (/^[0-9a-fA-F]{64}$/.test(maskStdout)) {
maskHashBuf = Buffer.from(maskStdout, "hex");
} else {
maskHashBuf = crypto2.createHash("sha256").update(maskBlob).digest();
}
const maskHashHex = maskHashBuf.toString("hex");
try {
const filesExist2 = this.client["filesExist"]?.bind(this.client);
if (typeof filesExist2 === "function") {
await new Promise((resolve) => {
filesExist2(
{
files: [],
filesWithHash: [maskHashHex],
...sharedSecret2 ? { sharedSecret: sharedSecret2 } : {}
},
(err, resp) => {
if (err) {
logErr(`[CAS] FilesExist mask error: ${err?.message || String(err)}`);
return resolve();
}
try {
const existArr = Array.isArray(resp?.existences) ? resp.existences : [];
const exists = existArr[0] === true;
logFile2(`[CAS] FilesExist mask hash=${maskHashHex} exists=${exists}`);
if (!exists) {
try {
const upload = this.client["uploadFile"]?.call(this.client);
if (upload && typeof upload.write === "function") {
const fname = `mask-${maskHashHex}.bin`;
upload.write({
initRequest: {
filename: fname,
sha256: maskHashBuf,
totalSize: maskBlob.length
},
...sharedSecret2 ? { sharedSecret: sharedSecret2 } : {}
});
upload.write({
chunk: {
content: maskBlob,
filename: fname,
offset: 0
},
...sharedSecret2 ? { sharedSecret: sharedSecret2 } : {}
});
upload.end();
upload.on(
"end",
() => logFile2(`[CAS] UploadFile mask completed hash=${maskHashHex} size=${maskBlob.length}`)
);
upload.on(
"error",
(ue) => logErr(`[CAS] UploadFile mask error: ${ue?.message || String(ue)}`)
);
}
} catch (ue) {
logErr(`[CAS] UploadFile mask exception: ${ue?.message || String(ue)}`);
}
}
} catch {
}
resolve();
}
);
});
}
} catch {
}
request.mask = maskHashBuf;
request.contents = [blob, maskBlob];
logFile2(`[i2i-encode] built mask.bin (${maskBlob.length} bytes) hash=${maskHashHex}`);
} else {
logErr(`[i2i-encode] mask encoding failed via ${toolUsed.display}`);
}
try {
fs26.unlinkSync(maskPngPath);
} catch {
}
try {
fs26.unlinkSync(maskBinPath);
} catch {
}
} catch (e) {
logErr(`[i2i-encode] mask encode exception: ${e instanceof Error ? e.message : String(e)}`);
}
}
try {
fs26.unlinkSync(pngPath);
} catch {
}
try {
fs26.unlinkSync(imgBinPath);
} catch {
}
} else {
console.error(
`[i2i-encode] encoder did not produce image.bin; stdout=${lastStdout}`
);
logErr(
`[i2i-encode] encoder did not produce image.bin; stdout=${lastStdout} stderr=${lastStderr}`
);
}
} catch (e) {
console.error(
`[i2i-encode] encoder failed: ${e instanceof Error ? e.message : String(e)}`
);
logErr(
`[i2i-encode] encoder failed: ${e instanceof Error ? e.message : String(e)}`
);
}
}
if (!request.image || !request.contents || !Array.isArray(request.contents) || request.contents.length === 0) {
request.contents = [Buffer.from(initPng)];
}
const call = this.cancellableGenerateCall();
if (typeof call !== "function")
throw new Error(`gRPC method not found: ${this.methodGenerate}`);
const startTime = Date.now();
const imagesBuffers = [];
const audioBuffers = [];
let chunkAccum = null;
let previewBuf = null;
let lastSeenStep = 0;
const handleData = (resp) => {
try {
if (resp?.currentSignpost?.sampling?.step) {
const currentStep = resp.currentSignpost.sampling.step;
lastSeenStep = currentStep;
console.info(
`gRPC progress: sampling step=${currentStep}`
);
logFile2(
`i2i progress: sampling step=${currentStep}`
);
if (onProgress) {
try {
onProgress(
currentStep,
payloadSteps,
`Sampling step ${currentStep}${payloadSteps ? `/${payloadSteps}` : ""}`
);
} catch {
}
}
} else if (resp?.currentSignpost != null && onProgress) {
const sp = resp.currentSignpost;
let label;
if (lastSeenStep === 0) {
if (sp.textEncoded != null) label = "Loading...";
else if (sp.imageEncoded != null) label = "Processing...";
} else {
label = "Finishing...";
}
if (label) {
try {
onProgress(-1, payloadSteps, label);
} catch {
}
}
}
if (resp?.generatedImages && Array.isArray(resp.generatedImages)) {
const list = resp.generatedImages.map(
(b) => Buffer.isBuffer(b) ? b : Buffer.from(b)
);
const cs = resp?.chunkState;
const isMore = cs === 1 || cs === "MORE_CHUNKS";
const isLast = cs === 0 || cs === "LAST_CHUNK";
if (isMore) {
if (list.length > 0) {
chunkAccum = chunkAccum ? Buffer.concat([chunkAccum, list[0]]) : Buffer.from(list[0]);
}
} else if (isLast && list.length > 0) {
if (chunkAccum) {
const full = Buffer.concat([chunkAccum, list[0]]);
imagesBuffers.push(full);
chunkAccum = null;
} else {
for (const buf of list) imagesBuffers.push(buf);
}
} else {
for (const buf of list) imagesBuffers.push(buf);
}
}
if (resp?.previewImage) {
const b = resp.previewImage;
previewBuf = Buffer.isBuffer(b) ? b : Buffer.from(b);
}
if (resp?.generatedAudio && Array.isArray(resp.generatedAudio)) {
for (const a of resp.generatedAudio) {
const ab = Buffer.isBuffer(a) ? a : Buffer.from(a);
if (ab.length > 0) audioBuffers.push(ab);
}
}
} catch {
}
};
await new Promise((resolve, reject) => {
try {
const stream = call(request);
stream.on("data", handleData);
stream.on("error", (err) => reject(err));
stream.on("end", () => resolve());
} catch (e) {
reject(e);
}
});
const endTime = Date.now();
const decoderTools2 = resolveExternalToolCandidates(
__projectRoot(),
"GRPCBin2PNG",
process.env.DT_DECODER_CMD
);
logToolCandidates("i2i decode", decoderTools2);
const decoderProfile = resolveTensorDecoderProfile(payloadModel);
logTensorSource("i2i", imagesBuffers, previewBuf, payloadModel);
if (decoderTools2.length && imagesBuffers.length > 0) {
const finalW = Number(
params.width || defaultParamsImg2Img.width || 1024
);
const finalH = Number(
params.height || defaultParamsImg2Img.height || 1024
);
const decoded = [];
for (let i = 0; i < imagesBuffers.length; i++) {
try {
const tmpDir = fs26.mkdtempSync(
path29.join(os8.tmpdir(), `${clientName()}-dt-`)
);
__registerTmp(tmpDir);
const inPath = path29.join(tmpDir, `img2img-${i + 1}.bin`);
const outPath = path29.join(tmpDir, `img2img-${i + 1}.png`);
fs26.writeFileSync(inPath, imagesBuffers[i]);
const args = [
"--in",
inPath,
"--out",
outPath,
"--profile",
decoderProfile
];
let decodedOne = null;
for (const tool3 of decoderTools2) {
const proc = spawnSync(tool3.cmd, [...tool3.argsPrefix, ...args], {
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env }
});
if (proc.error) {
logErr(
`[decoder] exception via ${tool3.display}: ${proc.error.message}`
);
continue;
}
if (proc.status !== 0) {
logErr(
`[decoder] exit=${proc.status} via ${tool3.display} stderr=${proc.stderr?.toString?.() || ""}`
);
continue;
}
if (fs26.existsSync(outPath) && fs26.statSync(outPath).size > 0) {
decodedOne = fs26.readFileSync(outPath);
break;
}
}
if (decodedOne) {
decoded.push(decodedOne);
try {
fs26.unlinkSync(inPath);
} catch {
}
} else {
decoded.push(imagesBuffers[i]);
}
} catch {
decoded.push(imagesBuffers[i]);
}
}
if (decoded.length > 0) {
imagesBuffers.length = 0;
imagesBuffers.push(...decoded);
logFile2(
`[decoder] i2i: decoded ${decoded.length} frame(s) \u2192 PNG via ${decoderTools2[0].display}`
);
}
}
let primaryBuf;
if (imagesBuffers.length > 0) primaryBuf = imagesBuffers[0];
else if (previewBuf) {
if (decoderTools2.length && previewBuf) {
try {
const tmpDir = fs26.mkdtempSync(
path29.join(os8.tmpdir(), `${clientName()}-dt-`)
);
__registerTmp(tmpDir);
const inPath = path29.join(tmpDir, `preview-i2i.bin`);
const outPath = path29.join(tmpDir, `preview-i2i.png`);
fs26.writeFileSync(inPath, previewBuf);
const finalW = Number(
params.width || defaultParamsImg2Img.width || 1024
);
const finalH = Number(
params.height || defaultParamsImg2Img.height || 1024
);
const args = [
"--in",
inPath,
"--out",
outPath,
"--profile",
decoderProfile
];
let decodedPrev = null;
for (const tool3 of decoderTools2) {
const proc = spawnSync(tool3.cmd, [...tool3.argsPrefix, ...args], {
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env }
});
if (proc.error) continue;
if (proc.status !== 0) continue;
if (fs26.existsSync(outPath) && fs26.statSync(outPath).size > 0) {
decodedPrev = fs26.readFileSync(outPath);
logFile2(
`[decoder] decoded preview-i2i.bin \u2192 PNG (${decodedPrev.length} bytes) via ${tool3.display}`
);
break;
}
}
primaryBuf = decodedPrev ? decodedPrev : previewBuf;
try {
fs26.unlinkSync(inPath);
} catch {
}
} catch {
primaryBuf = previewBuf;
}
} else {
primaryBuf = previewBuf;
}
}
if (!primaryBuf) throw new Error("gRPC stream yielded no image data");
const dataUrl = `data:image/png;base64,${primaryBuf.toString("base64")}`;
logFile2(
`i2i completed: images=${imagesBuffers.length}, bytes=${primaryBuf.length}`
);
const effW = Number(
payloadWidth ?? params.width ?? defaultParamsImg2Img.width ?? 1024
);
const effH = Number(
payloadHeight ?? params.height ?? defaultParamsImg2Img.height ?? 1024
);
const result = {
isError: false,
imageBuffer: primaryBuf,
imageData: dataUrl,
images: imagesBuffers.length ? imagesBuffers.map(
(b) => `data:image/png;base64,${b.toString("base64")}`
) : void 0,
metadata: {
alt: `Image-to-image from prompt: ${request.prompt}`,
inference_time_ms: endTime - startTime,
model: payloadModel,
width: effW,
height: effH,
requested_dimensions: {
width: effW,
height: effH
},
steps: Number.isFinite(Number(payloadSteps)) ? Number(payloadSteps) : void 0,
seed: typeof payloadSeed === "number" && Number.isFinite(payloadSeed) ? payloadSeed : void 0,
seed_mode: typeof payloadSeedMode === "string" && payloadSeedMode.trim() ? payloadSeedMode : void 0,
prompt_used: String(request.prompt || ""),
prompt_origin: promptOriginI2I,
...configBytes && { config_v2: generationConfigBytesToV2(configBytes) },
transport: "grpc",
stream_chunks: imagesBuffers.length,
num_frames: payloadNumFrames,
fps: payloadFps,
// Overlay source tracking for audit
overlay_source: overlaySource,
...overlayPreset && { overlay_preset: overlayPreset },
...overlayNote && { overlay_note: overlayNote },
...defaultsUsed && { defaults_used: defaultsUsed },
...overlayLookupMode && { overlay_lookup_mode: overlayLookupMode },
...i2iProfileUsed && { i2i_profile: i2iProfileUsed },
...typeof strengthUsed === "number" && { strength_used: strengthUsed },
...typeof stepsUsed === "number" && { steps_used: stepsUsed },
...samplerUsed && { sampler_used: samplerUsed },
...typeof guidanceScaleUsed === "number" && {
guidance_scale_used: guidanceScaleUsed
},
...typeof shiftUsed === "number" && { shift_used: shiftUsed },
...typeof resolutionDependentShiftUsed === "boolean" && {
resolution_dependent_shift_used: resolutionDependentShiftUsed
},
...compressionArtifactsUsed != null && {
compression_artifacts_used: compressionArtifactsUsed
},
...compressionArtifactsQualityUsed != null && {
compression_artifacts_quality_used: compressionArtifactsQualityUsed
},
...requiredLoraFiles && requiredLoraFiles.length > 0 && { loras_used: requiredLoraFiles }
},
audioBuffers: audioBuffers.length > 0 ? audioBuffers : void 0
};
__cleanupTmp();
return result;
} catch (e) {
try {
} catch {
}
return this.toBackendError(e);
}
}
/** Edit mode generation with multiple reference images. */
async generateImageEdit(inputParams = {}, referenceBuffers, onProgress, maskBuffer) {
const isVideoEdit = inputParams?._dt_video_mode === "img2vid";
const rawProfile = inputParams?._dt_i2i_profile;
const i2iProfileUsed = rawProfile === "img2img" ? "img2img" : rawProfile === "inpaint" || rawProfile === "outpaint" ? rawProfile : "edit";
const overlayMode = isVideoEdit ? "img2vid" : i2iProfileUsed;
const modeLabel = overlayMode === "img2img" ? "image2image" : overlayMode === "img2vid" ? "image2video" : "edit";
if (!referenceBuffers || referenceBuffers.length === 0) {
return {
isError: true,
errorMessage: "Edit mode requires at least one reference image"
};
}
if (referenceBuffers.length > 1 && !isVideoEdit && rawProfile !== "img2img" && rawProfile !== "edit" && rawProfile !== "inpaint" && rawProfile !== "outpaint") {
try {
logFile2(
"[multi-ref] WARNING: _dt_i2i_profile missing; defaulting to edit profile. This indicates a core/service interface regression."
);
} catch {
}
}
if (referenceBuffers.length === 1) {
const effectiveProfile = rawProfile === "restore" || rawProfile === "img2img" || rawProfile === "inpaint" || rawProfile === "outpaint" ? rawProfile : "edit";
const editParams = { ...inputParams, _dt_i2i_profile: effectiveProfile };
return this.generateImageImg2Img(editParams, referenceBuffers[0], onProgress, maskBuffer);
}
try {
const __tmpDirs = [];
const __registerTmp = (d) => {
try {
__tmpDirs.push(d);
} catch {
}
};
const __cleanupTmp = () => {
for (const d of __tmpDirs) {
try {
fs26.rmSync(d, { recursive: true, force: true });
} catch {
}
}
};
const audit = buildAuditLogger({
backend: this.name,
mode: overlayMode === "inpaint" || overlayMode === "outpaint" ? "edit" : overlayMode
});
this.ensureClient();
let overlaySource = "default";
let overlayPreset;
let overlayNote;
let defaultsUsed;
let overlayLookupMode;
let strengthUsed;
let stepsUsed;
let samplerUsed;
let guidanceScaleUsed;
let shiftUsed;
let resolutionDependentShiftUsed;
let requiredLoraFiles;
const baseDefaults = isVideoEdit ? defaultParamsImage2Video : overlayMode === "edit" || overlayMode === "inpaint" || overlayMode === "outpaint" ? defaultParamsImg2Img2 : defaultParamsImg2Img;
const baseLimits = isVideoEdit ? drawthingsLimits : overlayMode === "edit" || overlayMode === "inpaint" || overlayMode === "outpaint" ? drawthingsLimits : drawthingsLimits;
let params = {};
try {
const r = validateImageGenerationParams(inputParams);
if (r.valid) params = inputParams;
} catch {
}
if (!params.prompt)
params.prompt = inputParams.prompt || baseDefaults.prompt;
try {
const variants = inputParams.variants;
if (typeof variants === "number") {
const v = Math.max(1, Math.min(4, Math.round(variants)));
params.batch_size = v;
params.batch_count = 1;
}
} catch {
}
if (isVideoEdit) {
const rawNumFrames = inputParams.numFrames;
if (typeof rawNumFrames === "number" && rawNumFrames > 1) {
const normalized = normalizeNumFrames(rawNumFrames);
params.num_frames = normalized.value;
if (normalized.hint) console.info(`[img2vid] ${normalized.hint}`);
}
}
const resolveEncoderCmd = () => {
const envCmd = process.env.DT_ENCODER_CMD;
const projectRoot2 = __resolveProjectRootFrom(__svcDir());
const candidates = buildTensorHelperCandidates(
projectRoot2,
"PNG2GRPCBin",
envCmd
);
for (const c of candidates) {
try {
const abs = path29.isAbsolute(c) ? c : path29.resolve(projectRoot2, c);
if (!fs26.existsSync(abs)) continue;
const origin = c === envCmd ? "env" : "auto";
if (abs.endsWith(".js")) {
return {
cmd: process.execPath,
argsPrefix: [abs],
display: abs,
impl: "ts",
origin
};
}
try {
const st = fs26.statSync(abs);
if ((st.mode & 73) === 0) {
try {
fs26.chmodSync(abs, 493);
} catch {
}
}
} catch {
}
return {
cmd: abs,
argsPrefix: [],
display: abs,
impl: "mac-bin",
origin
};
} catch {
}
}
return null;
};
const encoderCmd = resolveEncoderCmd();
logToolSelection("edit encode", encoderCmd);
if (!encoderCmd) {
return {
isError: true,
errorMessage: "PNG2GRPCBin encoder not found for multi-reference edit"
};
}
const contentsTensors = [];
let primaryHash = null;
const moodboardHashes = [];
let canvasW;
let canvasH;
for (let i = 0; i < referenceBuffers.length; i++) {
const refBuf = referenceBuffers[i];
const pngBuf = await toPng(refBuf);
if (i === 0) {
try {
const meta = await getSize(pngBuf);
canvasW = meta.width;
canvasH = meta.height;
} catch {
}
}
const tmpDir = fs26.mkdtempSync(
path29.join(os8.tmpdir(), `${clientName()}-edit-${i}-`)
);
__registerTmp(tmpDir);
const pngPath = path29.join(tmpDir, "input.png");
const imgBinPath = path29.join(tmpDir, "image.bin");
fs26.writeFileSync(pngPath, pngBuf);
const args = ["--in", pngPath, "--out", imgBinPath];
const proc = spawnSync(
encoderCmd.cmd,
[...encoderCmd.argsPrefix, ...args],
{
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env }
}
);
if (proc.error) {
__cleanupTmp();
return {
isError: true,
errorMessage: `Encoder failed for reference ${i + 1}: ${proc.error.message}`
};
}
if (typeof proc.status === "number" && proc.status !== 0) {
const stdout = proc.stdout ? proc.stdout.toString("utf8") : "";
const stderr = proc.stderr ? proc.stderr.toString("utf8") : "";
logErr(
`[edit] encoder exit=${proc.status} ref=${i + 1} cmd=${encoderCmd.cmd} ${[...encoderCmd.argsPrefix, ...args].join(" ")}`
);
if (stdout.trim())
logFile2(`[edit] encoder stdout ref=${i + 1}: ${stdout.trim()}`);
if (stderr.trim())
logErr(`[edit] encoder stderr ref=${i + 1}: ${stderr.trim()}`);
__cleanupTmp();
return {
isError: true,
errorMessage: `Encoder failed for reference ${i + 1} (exit ${proc.status})${stderr.trim() ? `: ${stderr.trim()}` : ""}`
};
}
if (!fs26.existsSync(imgBinPath) || fs26.statSync(imgBinPath).size === 0) {
const stdout = proc.stdout ? proc.stdout.toString("utf8") : "";
const stderr = proc.stderr ? proc.stderr.toString("utf8") : "";
if (stdout.trim())
logFile2(`[edit] encoder stdout ref=${i + 1}: ${stdout.trim()}`);
if (stderr.trim())
logErr(`[edit] encoder stderr ref=${i + 1}: ${stderr.trim()}`);
__cleanupTmp();
return {
isError: true,
errorMessage: `Encoder produced no output for reference ${i + 1}`
};
}
const blob = fs26.readFileSync(imgBinPath);
contentsTensors.push(blob);
const tensorHash = crypto2.createHash("sha256").update(blob).digest();
if (i === 0) {
primaryHash = tensorHash;
} else {
moodboardHashes.push(tensorHash);
}
try {
fs26.unlinkSync(pngPath);
} catch {
}
try {
fs26.unlinkSync(imgBinPath);
} catch {
}
}
logFile2(
`[${modeLabel}] encoded ${contentsTensors.length} reference images for multi-ref`
);
if (canvasW && canvasH) {
params.original_width = canvasW;
params.original_height = canvasH;
const hasW = typeof params.width === "number" && Number.isFinite(params.width);
const hasH = typeof params.height === "number" && Number.isFinite(params.height);
if (!hasW) params.width = canvasW;
if (!hasH) params.height = canvasH;
const hasTW = typeof params.target_width === "number" && Number.isFinite(params.target_width);
const hasTH = typeof params.target_height === "number" && Number.isFinite(params.target_height);
if (!hasTW) params.target_width = params.width;
if (!hasTH) params.target_height = params.height;
}
let configBytes = void 0;
let payloadWidth;
let payloadHeight;
let payloadSteps;
let payloadSeed;
let payloadSeedMode;
let payloadModel;
let payloadNumFrames = 1;
let payloadFps = 24;
try {
const allowedKeys = new Set(Object.keys(baseDefaults));
const filtered = {};
for (const [k, v] of Object.entries(params)) {
if (allowedKeys.has(k)) filtered[k] = v;
}
const modelId = params.model;
const {
source,
presetName,
note,
params: overlayParams
} = getEffectiveOverlay(modelId, overlayMode === "inpaint" || overlayMode === "outpaint" ? "edit" : overlayMode);
const overlayParamsNoSize = (() => {
if (!overlayParams) return overlayParams;
const o = { ...overlayParams };
delete o.width;
delete o.height;
delete o.batch_count;
delete o.batch_size;
delete o.batchCount;
delete o.batchSize;
delete o.upscaler;
delete o.upscaler_scale;
delete o.upscalerScale;
delete o.fps;
return o;
})();
overlaySource = source;
overlayPreset = presetName;
overlayNote = note;
if (modelId === "auto") {
delete filtered.model;
}
if (overlayParams) {
logFile2(
`Applying ${source} overlay for '${modelId ?? "auto"}' (${modeLabel}, gRPC)${presetName ? ` preset=${presetName}` : ""}`
);
delete filtered.model;
}
audit.setOutput({
overlay_source: source,
...presetName && { overlay_preset: presetName },
...note && { overlay_note: note }
});
const effective = {
...baseDefaults,
...overlayParamsNoSize || {},
...filtered,
seed: baseDefaults.seed
};
{
const sub = overlaySource === "custom" ? { file: "", substituted: false } : substituteInstalledPrecision(String(effective.model ?? ""), await currentInventory());
if (sub.substituted) {
const note2 = substitutionNote(String(effective.model), sub.file);
effective.model = sub.file;
overlayNote = overlayNote ? `${overlayNote} ${note2}` : note2;
logFile2(note2);
}
}
defaultsUsed = isVideoEdit ? "defaultParamsDrawThingsImage2Video" : overlayMode === "edit" || overlayMode === "inpaint" || overlayMode === "outpaint" ? "defaultParamsDrawThingsEdit" : "defaultParamsDrawThingsImg2Img";
overlayLookupMode = overlayMode;
strengthUsed = typeof effective.strength === "number" && Number.isFinite(effective.strength) ? effective.strength : void 0;
stepsUsed = typeof effective.steps === "number" && Number.isFinite(effective.steps) ? effective.steps : void 0;
samplerUsed = typeof effective.sampler === "string" && String(effective.sampler).trim() ? String(effective.sampler) : void 0;
guidanceScaleUsed = typeof effective.guidance_scale === "number" && Number.isFinite(effective.guidance_scale) ? effective.guidance_scale : void 0;
shiftUsed = typeof effective.shift === "number" && Number.isFinite(effective.shift) ? effective.shift : void 0;
resolutionDependentShiftUsed = typeof effective.resolution_dependent_shift === "boolean" ? effective.resolution_dependent_shift : void 0;
audit.setOutput({
overlay_lookup_mode: overlayMode === "inpaint" || overlayMode === "outpaint" ? "edit" : overlayMode,
defaults_used: defaultsUsed,
strength_used: typeof effective.strength === "number" && Number.isFinite(effective.strength) ? effective.strength : void 0,
steps_used: typeof effective.steps === "number" && Number.isFinite(effective.steps) ? effective.steps : void 0,
sampler_used: typeof effective.sampler === "string" && String(effective.sampler).trim() ? String(effective.sampler) : void 0,
guidance_scale_used: typeof effective.guidance_scale === "number" && Number.isFinite(effective.guidance_scale) ? effective.guidance_scale : void 0,
shift_used: typeof effective.shift === "number" && Number.isFinite(effective.shift) ? effective.shift : void 0,
resolution_dependent_shift_used: typeof effective.resolution_dependent_shift === "boolean" ? effective.resolution_dependent_shift : void 0
});
try {
const userSpecifiedLoras = Object.prototype.hasOwnProperty.call(
filtered,
"loras"
);
const overlaySelected = !!overlayParams;
if (userSpecifiedLoras) {
const ls = Array.isArray(filtered.loras) ? filtered.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else if (overlaySelected) {
const ls = Array.isArray(overlayParams?.loras) ? overlayParams.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else {
const ls = Array.isArray(effective?.loras) ? effective.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
}
} catch {
}
const cfg = buildDtGenerationConfiguration(effective);
configBytes = cfg.bytes && cfg.bytes.length ? cfg.bytes : void 0;
try {
const view = cfg?.view || {};
payloadWidth = view.width;
payloadHeight = view.height;
payloadSteps = view.steps;
payloadSeed = view.seed;
payloadSeedMode = view.seed_mode;
payloadModel = String(effective.model || "");
payloadNumFrames = typeof effective.num_frames === "number" ? effective.num_frames : 1;
payloadFps = (typeof filtered.fps === "number" ? filtered.fps : void 0) ?? getDefaultFpsForModel(payloadModel) ?? (typeof effective.fps === "number" ? effective.fps : 24);
} catch {
}
} catch {
}
const sharedSecret = process.env.DRAWTHINGS_SHARED_SECRET;
const moodboardWeight = moodboardHashes.length > 0 ? 1 / moodboardHashes.length : 1;
const shuffleHints = moodboardHashes.map((hash) => ({
tensor: hash,
// SHA256 hash (32 bytes) referencing tensor in contents[]
weight: moodboardWeight
}));
const request = {
prompt: String(params.prompt || baseDefaults.prompt),
negativePrompt: String(params.negative_prompt || ""),
scaleFactor: 1,
keywords: [],
user: clientName(),
device: "LAPTOP",
chunked: true,
...sharedSecret ? { sharedSecret } : {},
image: primaryHash,
// Hash of first (canvas) image
contents: contentsTensors,
// All reference tensors (Content-Addressable Storage)
// Moodboard images as shuffle hints
...shuffleHints.length > 0 ? {
hints: [
{
hintType: "shuffle",
// MUST be "shuffle" for moodboard/reference images
tensors: shuffleHints
}
]
} : {}
};
if (configBytes) request.configuration = configBytes;
logFile2(
`[${modeLabel}] request built: canvas=1, moodboard=${shuffleHints.length}, total_contents=${contentsTensors.length}`
);
const call = this.cancellableGenerateCall();
if (typeof call !== "function")
throw new Error(`gRPC method not found: ${this.methodGenerate}`);
const startTime = Date.now();
const imagesBuffers = [];
const audioBuffers = [];
let chunkAccum = null;
let previewBuf = null;
let lastSeenStep = 0;
const handleData = (resp) => {
try {
if (resp?.currentSignpost?.sampling?.step) {
const currentStep = resp.currentSignpost.sampling.step;
lastSeenStep = currentStep;
console.info(
`gRPC progress: sampling step=${currentStep}`
);
logFile2(
`edit progress: sampling step=${currentStep}`
);
if (onProgress) {
try {
onProgress(
currentStep,
payloadSteps,
`Sampling step ${currentStep}${payloadSteps ? `/${payloadSteps}` : ""}`
);
} catch {
}
}
} else if (resp?.currentSignpost != null && onProgress) {
const sp = resp.currentSignpost;
let label;
if (lastSeenStep === 0) {
if (sp.textEncoded != null) label = "Loading...";
else if (sp.imageEncoded != null) label = "Processing...";
} else {
label = "Finishing...";
}
if (label) {
try {
onProgress(-1, payloadSteps, label);
} catch {
}
}
}
if (resp?.generatedImages && Array.isArray(resp.generatedImages)) {
const list = resp.generatedImages.map(
(b) => Buffer.isBuffer(b) ? b : Buffer.from(b)
);
const cs = resp?.chunkState;
const isMore = cs === 1 || cs === "MORE_CHUNKS";
const isLast = cs === 0 || cs === "LAST_CHUNK";
if (isMore) {
if (list.length > 0) {
chunkAccum = chunkAccum ? Buffer.concat([chunkAccum, list[0]]) : Buffer.from(list[0]);
}
} else if (isLast && list.length > 0) {
if (chunkAccum) {
const full = Buffer.concat([chunkAccum, list[0]]);
imagesBuffers.push(full);
chunkAccum = null;
} else {
for (const buf of list) imagesBuffers.push(buf);
}
} else {
for (const buf of list) imagesBuffers.push(buf);
}
}
if (resp?.previewImage) {
const b = resp.previewImage;
previewBuf = Buffer.isBuffer(b) ? b : Buffer.from(b);
}
if (resp?.generatedAudio && Array.isArray(resp.generatedAudio)) {
for (const a of resp.generatedAudio) {
const ab = Buffer.isBuffer(a) ? a : Buffer.from(a);
if (ab.length > 0) audioBuffers.push(ab);
}
}
} catch {
}
};
await new Promise((resolve, reject) => {
try {
const stream = call(request);
stream.on("data", handleData);
stream.on("error", (err) => reject(err));
stream.on("end", () => resolve());
} catch (e) {
reject(e);
}
});
const endTime = Date.now();
const resolveDecoderCmd = () => {
const envCmd = process.env.DT_DECODER_CMD;
const projectRoot2 = __projectRoot();
const candidates = buildTensorHelperCandidates(
projectRoot2,
"GRPCBin2PNG",
envCmd
);
for (const c of candidates) {
try {
const abs = path29.isAbsolute(c) ? c : path29.resolve(projectRoot2, c);
if (!fs26.existsSync(abs)) continue;
const origin = c === envCmd ? "env" : "auto";
if (abs.endsWith(".js")) {
return {
cmd: process.execPath,
argsPrefix: [abs],
display: abs,
impl: "ts",
origin
};
}
try {
const st = fs26.statSync(abs);
if ((st.mode & 73) === 0) {
try {
fs26.chmodSync(abs, 493);
} catch {
}
}
} catch {
}
return {
cmd: abs,
argsPrefix: [],
display: abs,
impl: "mac-bin",
origin
};
} catch {
}
}
return null;
};
const decoderCmd = resolveDecoderCmd();
const decoderProfile = resolveTensorDecoderProfile(payloadModel);
logToolSelection("edit decode", decoderCmd);
let primaryBuf = null;
logTensorSource("edit-multiref", imagesBuffers, previewBuf, payloadModel);
if (decoderCmd && imagesBuffers.length > 0) {
const pngBuffers = [];
for (let i = 0; i < imagesBuffers.length; i++) {
const rawBuf = imagesBuffers[i];
try {
const tmpDir = fs26.mkdtempSync(
path29.join(os8.tmpdir(), `${clientName()}-dec-${i}-`)
);
__registerTmp(tmpDir);
const inPath = path29.join(tmpDir, "input.bin");
const outPath = path29.join(tmpDir, "output.png");
fs26.writeFileSync(inPath, rawBuf);
const proc = spawnSync(
decoderCmd.cmd,
[
...decoderCmd.argsPrefix,
"--in",
inPath,
"--out",
outPath,
"--profile",
decoderProfile
],
{
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env }
}
);
if (!proc.error && fs26.existsSync(outPath) && fs26.statSync(outPath).size > 0) {
pngBuffers.push(fs26.readFileSync(outPath));
}
} catch {
}
}
if (pngBuffers.length > 0) {
primaryBuf = pngBuffers[0];
imagesBuffers.length = 0;
for (const b of pngBuffers) imagesBuffers.push(b);
}
}
if (!primaryBuf && previewBuf) {
primaryBuf = previewBuf;
}
if (!primaryBuf)
throw new Error("gRPC edit stream yielded no image data");
const dataUrl = `data:image/png;base64,${primaryBuf.toString("base64")}`;
logFile2(
`edit completed: refs=${referenceBuffers.length}, images=${imagesBuffers.length}, bytes=${primaryBuf.length}`
);
const effW = Number(payloadWidth ?? params.width ?? 1024);
const effH = Number(payloadHeight ?? params.height ?? 1024);
const result = {
isError: false,
imageBuffer: primaryBuf,
imageData: dataUrl,
images: imagesBuffers.length ? imagesBuffers.map(
(b) => `data:image/png;base64,${b.toString("base64")}`
) : void 0,
metadata: {
alt: overlayMode === "img2img" ? `Image-to-image from prompt: ${request.prompt}` : `Edit from prompt: ${request.prompt}`,
inference_time_ms: endTime - startTime,
model: payloadModel,
width: effW,
height: effH,
requested_dimensions: {
width: effW,
height: effH
},
steps: Number.isFinite(Number(payloadSteps)) ? Number(payloadSteps) : void 0,
seed: typeof payloadSeed === "number" && Number.isFinite(payloadSeed) ? payloadSeed : void 0,
seed_mode: typeof payloadSeedMode === "string" && payloadSeedMode.trim() ? payloadSeedMode : void 0,
prompt_used: String(request.prompt || ""),
reference_count: referenceBuffers.length,
...configBytes && { config_v2: generationConfigBytesToV2(configBytes) },
transport: "grpc",
stream_chunks: imagesBuffers.length,
num_frames: payloadNumFrames,
fps: payloadFps,
// Overlay source tracking for audit
overlay_source: overlaySource,
...overlayPreset && { overlay_preset: overlayPreset },
...overlayNote && { overlay_note: overlayNote },
...defaultsUsed && { defaults_used: defaultsUsed },
...overlayLookupMode && { overlay_lookup_mode: overlayLookupMode },
i2i_profile: i2iProfileUsed,
...typeof strengthUsed === "number" && { strength_used: strengthUsed },
...typeof stepsUsed === "number" && { steps_used: stepsUsed },
...samplerUsed && { sampler_used: samplerUsed },
...typeof guidanceScaleUsed === "number" && {
guidance_scale_used: guidanceScaleUsed
},
...typeof shiftUsed === "number" && { shift_used: shiftUsed },
...typeof resolutionDependentShiftUsed === "boolean" && {
resolution_dependent_shift_used: resolutionDependentShiftUsed
},
...requiredLoraFiles && requiredLoraFiles.length > 0 && { loras_used: requiredLoraFiles }
},
audioBuffers: audioBuffers.length > 0 ? audioBuffers : void 0
};
__cleanupTmp();
return result;
} catch (e) {
return this.toBackendError(e);
}
}
};
// src/helpers/imageModelMeta.ts
import path30 from "node:path";
function normalizeModelFilenameForLookup(value) {
return path30.basename(value).trim().toLowerCase();
}
function resolveModelFamilyFromModelBasename(modelBasename2) {
const normalized = normalizeModelFilenameForLookup(modelBasename2);
if (!normalized) return "unknown";
for (const family2 of ["z-image", "qwen-image", "flux", "ltx"]) {
for (const mode of ["txt2img", "img2img", "edit", "txt2vid", "img2vid"]) {
const m = getModelFilename(family2, mode);
if (typeof m !== "string") continue;
if (normalizeModelFilenameForLookup(m) === normalized) return family2;
}
}
for (const family2 of ["z-image", "qwen-image", "flux", "ltx"]) {
const key = MODEL_PRESET_TO_CAPABILITY_KEY?.[family2];
if (typeof key !== "string") continue;
const cap = IMAGE_MODEL_CAPABILITY_MAP?.[key];
const filenames = cap?.modelFilenames;
if (!Array.isArray(filenames)) continue;
for (const f of filenames) {
if (typeof f !== "string") continue;
if (normalizeModelFilenameForLookup(f) === normalized) return family2;
}
}
const customLabels = getCustomPresetLabelsUsingModelFilename(normalized);
if (customLabels.length > 0) return "custom";
return "unknown";
}
function modeToUserMode(mode) {
switch (mode) {
case "txt2img":
return "text2image";
case "img2img":
return "image2image";
case "txt2vid":
return "text2video";
case "img2vid":
return "image2video";
case "edit":
return "edit";
}
}
function userModeToMode(mode) {
switch (mode) {
case "text2image":
return "txt2img";
case "image2image":
return "img2img";
case "text2video":
return "txt2vid";
case "image2video":
return "img2vid";
case "edit":
return "edit";
}
}
function getDefaultModelForMode2(mode) {
const raw = mode === "txt2img" ? defaultParams?.model : mode === "img2img" ? defaultParamsImg2Img?.model : mode === "txt2vid" ? defaultParamsText2Video?.model : mode === "img2vid" ? defaultParamsImage2Video?.model : defaultParamsImg2Img2?.model;
return typeof raw === "string" ? raw : "";
}
function computeEffectiveModelFilename(modelId, mode) {
const base = getDefaultModelForMode2(mode);
const baseBase = normalizeModelFilenameForLookup(base);
const overlay = getEffectiveOverlay(modelId, mode);
const overlayModel = overlay.params?.model;
const chosen = typeof overlayModel === "string" && overlayModel.trim() ? overlayModel : base;
const chosenBase = normalizeModelFilenameForLookup(chosen);
return {
modelBasename: chosenBase || baseBase,
overlaySource: overlay.source,
presetName: overlay.presetName
};
}
function scorePresetForDisplay(p) {
const isAuto = p.modelId === "auto";
const isCustomConfig = p.overlaySource === "custom";
const isOverlay = p.overlaySource === "modelOverlay";
return (isCustomConfig ? 100 : isOverlay ? 50 : 0) + (isAuto ? 10 : 0);
}
function pickDisplayPreset(presets) {
if (!presets.length) return void 0;
return [...presets].sort((a, b) => scorePresetForDisplay(b) - scorePresetForDisplay(a))[0];
}
function resolveImageModelInfoFromModelUsed(modelFilenameOrPath, opts) {
if (typeof modelFilenameOrPath !== "string") return null;
const base = path30.basename(modelFilenameOrPath).trim();
if (!base) return null;
const normalized = normalizeModelFilenameForLookup(base);
const modes = opts?.mode ? [userModeToMode(opts.mode)] : ["txt2img", "img2img", "edit", "txt2vid", "img2vid"];
const presets = [];
for (const mode of modes) {
for (const modelId of MODEL_IDS) {
const eff = computeEffectiveModelFilename(modelId, mode);
if (!eff.modelBasename) continue;
if (eff.modelBasename !== normalized) continue;
if (eff.overlaySource === "default" && modelId !== "auto") continue;
const userMode = modeToUserMode(mode);
const preset = `${userMode}.${modelId}`;
presets.push({
mode: userMode,
modelId,
preset,
overlaySource: eff.overlaySource,
...eff.presetName ? { customConfig: eff.presetName } : {}
});
}
}
const customConfigLabels = getCustomPresetLabelsUsingModelFilename(base);
const chosen = pickDisplayPreset(presets);
const modelFamily = resolveModelFamilyFromModelBasename(base);
const display = modelFamily && modelFamily !== "unknown" ? `${modelFamily} (${base})` : base;
return {
modelUsedBasename: base,
display,
...chosen ? { chosen_model_id: chosen.modelId } : {},
...modelFamily ? { model_family: modelFamily } : {},
presets,
...customConfigLabels.length ? { custom_config_labels: customConfigLabels } : {}
};
}
function formatImageModelForToolDisplay(modelFilenameOrPath) {
const info = resolveImageModelInfoFromModelUsed(modelFilenameOrPath);
return info?.display ?? "";
}
// src/services/defaultParamsPreviewAnalyse.ts
var previewDefaults = {
previewFormat: "jpeg",
previewMaxWidth: 1024,
previewQuality: 85
};
// src/services/mediaReconcile/reconcile.ts
import path31 from "path";
// src/services/mediaReconcile/types.ts
var DEFAULT_RECONCILE_OPTIONS = {
attachment: {
strategy: "replace",
generatePreviews: true,
maxPreviews: 5
// Only top 5 attachments get previews (for Vision)
},
variant: {
strategy: "merge",
generatePreviews: false
// Previews created by generate_image tool
},
picture: {
strategy: "merge",
generatePreviews: true
// Download and create preview from URL
},
image: {
strategy: "merge",
generatePreviews: false
// Previews created by generating tool
}
};
// src/services/mediaReconcile/reconcile.ts
function getIdentifierKey(mediaType) {
switch (mediaType) {
case "attachment":
return "originAbs";
// Absolute path to original file
case "variant":
return "filename";
// Filename in chatWd
case "picture":
return "sourceUrl";
// Original URL
case "image":
return "filename";
// Filename in chatWd
default:
return "filename";
}
}
function getIndexKey(mediaType) {
const config = MEDIA_SOURCE_REGISTRY[mediaType];
return config?.indexPrefix ?? "n";
}
function normalizeIdentifier(id, mediaType) {
if (mediaType === "attachment") {
try {
return path31.resolve(id);
} catch {
return id;
}
}
return id;
}
function candidateToRecord(candidate, index2, mediaType) {
const indexKey = getIndexKey(mediaType);
const base = {
[indexKey]: index2,
turnId: candidate.turnId
};
switch (mediaType) {
case "attachment":
return {
...base,
originAbs: candidate.identifier
// filename and preview will be set during import
};
case "variant":
return {
...base,
filename: candidate.identifier,
// preview expected to exist alongside original
preview: `preview-${path31.basename(candidate.identifier, ".png")}.jpg`,
// Persist provenance (mirrors "picture"/"image" cases below).
sourceTool: candidate.sourceTool,
pluginId: candidate.pluginId
};
case "picture":
return {
sourceUrl: candidate.identifier,
title: candidate.title,
sourceTool: candidate.sourceTool,
pluginId: candidate.pluginId,
turnId: candidate.turnId,
[indexKey]: index2
};
case "image": {
const sourceTool = candidate.pluginId && candidate.sourceTool ? `${candidate.pluginId}, ${candidate.sourceTool}` : candidate.sourceTool;
return {
filename: candidate.identifier,
preview: `preview-${path31.basename(
candidate.identifier,
path31.extname(candidate.identifier)
)}.jpg`,
sourceTool,
// kind: undefined - set by caller if needed
turnId: candidate.turnId,
// createdAt: undefined - set by appendImages if missing
[indexKey]: index2
};
}
default:
return base;
}
}
async function reconcileMedia(chatWd, stateArray, mediaType, candidates, options) {
const { strategy, debug } = options;
const identifierKey = getIdentifierKey(mediaType);
const indexKey = getIndexKey(mediaType);
if (debug) {
console.info(
`[reconcileMedia] ${mediaType}: ${candidates.length} candidates, strategy=${strategy}`
);
}
if (strategy === "replace") {
return reconcileReplace(
chatWd,
stateArray,
mediaType,
candidates,
identifierKey,
indexKey,
options
);
} else {
return reconcileMerge(
chatWd,
stateArray,
mediaType,
candidates,
identifierKey,
indexKey,
options
);
}
}
async function reconcileReplace(chatWd, stateArray, mediaType, candidates, identifierKey, indexKey, options) {
const { debug } = options;
if (candidates.length === 0) {
if (debug) {
console.info(
`[reconcileMedia] ${mediaType}: No candidates, keeping existing state`
);
}
return {
result: {
added: 0,
removed: 0,
unchanged: stateArray.length,
stateChanged: false
},
newArray: stateArray
};
}
const existingByIdentifier = /* @__PURE__ */ new Map();
for (const record of stateArray) {
const id = record[identifierKey];
if (typeof id === "string") {
existingByIdentifier.set(normalizeIdentifier(id, mediaType), record);
}
}
const newArray = [];
let added = 0;
let unchanged = 0;
for (let i = 0; i < candidates.length; i++) {
const candidate = candidates[i];
const normalizedId = normalizeIdentifier(candidate.identifier, mediaType);
const existing = existingByIdentifier.get(normalizedId);
if (existing) {
const updated = { ...existing };
updated[indexKey] = i + 1;
if (candidate.turnId !== void 0) {
updated.turnId = candidate.turnId;
}
newArray.push(updated);
unchanged++;
} else {
const record = candidateToRecord(candidate, i + 1, mediaType);
newArray.push(record);
added++;
}
}
const removed = stateArray.length - unchanged;
const stateChanged = added > 0 || removed > 0;
if (debug) {
console.info(
`[reconcileMedia] ${mediaType}: added=${added}, removed=${removed}, unchanged=${unchanged}`
);
}
return {
result: { added, removed, unchanged, stateChanged },
newArray
};
}
async function reconcileMerge(chatWd, stateArray, mediaType, candidates, identifierKey, indexKey, options) {
const { debug } = options;
if (candidates.length === 0) {
if (debug) {
console.info(
`[reconcileMedia] ${mediaType}: No candidates, keeping existing state (merge)`
);
}
return {
result: {
added: 0,
removed: 0,
unchanged: stateArray.length,
stateChanged: false
},
newArray: stateArray
};
}
const candidateIds = /* @__PURE__ */ new Set();
for (const c of candidates) {
candidateIds.add(normalizeIdentifier(c.identifier, mediaType));
}
const existingByIdentifier = /* @__PURE__ */ new Map();
for (const record of stateArray) {
const id = record[identifierKey];
if (typeof id === "string") {
existingByIdentifier.set(normalizeIdentifier(id, mediaType), record);
}
}
const newArray = [];
let removed = 0;
let unchanged = 0;
for (const record of stateArray) {
const id = record[identifierKey];
if (typeof id !== "string") {
removed++;
continue;
}
const normalizedId = normalizeIdentifier(id, mediaType);
if (candidateIds.has(normalizedId)) {
newArray.push(record);
unchanged++;
} else {
if (debug) {
console.info(
`[reconcileMedia] ${mediaType}: Removing deleted item: ${id}`
);
}
removed++;
}
}
let added = 0;
let nextIndex = Math.max(
0,
...newArray.map((r) => {
const idx = r[indexKey];
return typeof idx === "number" ? idx : 0;
})
) + 1;
for (const candidate of candidates) {
const normalizedId = normalizeIdentifier(candidate.identifier, mediaType);
if (!existingByIdentifier.has(normalizedId)) {
const record = candidateToRecord(candidate, nextIndex, mediaType);
newArray.push(record);
added++;
nextIndex++;
}
}
const stateChanged = added > 0 || removed > 0;
if (debug) {
console.info(
`[reconcileMedia] ${mediaType}: added=${added}, removed=${removed}, unchanged=${unchanged}`
);
}
return {
result: { added, removed, unchanged, stateChanged },
newArray
};
}
function getStateArrayKey(mediaType) {
switch (mediaType) {
case "attachment":
return "attachments";
case "variant":
return "variants";
case "picture":
return "pictures";
case "image":
return "images";
default:
return `${mediaType}s`;
}
}
// src/tools/review_image.ts
import { tool } from "@lmstudio/sdk";
import { z as z2 } from "zod";
import path32 from "path";
import fs27 from "fs";
var FlexibleTargetsList = z2.union([
// String form: split by comma/space
z2.string().transform(
(s) => s.split(/[\s,]+/).map((x) => x.trim()).filter((x) => x.length > 0)
),
// Array form: pass through
z2.array(z2.string())
]).refine((arr) => arr.length >= 1, "targets must contain at least one notation").refine((arr) => arr.length <= 32, "targets must contain at most 32 notations");
var ReviewImageParamsShape = {
targets: FlexibleTargetsList
};
function normalizeTargetNotationToken(raw) {
let s = String(raw ?? "").trim();
if (!s) return "";
s = s.replace(/^[\[{(]+/, "").replace(/[\]})]+$/, "");
s = s.replace(/^['"`]+|['"`]+$/g, "");
s = s.replace(/[;:.!?]+$/, "");
s = s.trim().toLowerCase();
if (/^[avip]$/i.test(s)) return `${s}1`;
return s;
}
function normalizeTargetsArg(rawTargets) {
const fromArray = (arr) => arr.map((x) => typeof x === "string" ? x : String(x ?? "")).map((x) => x.trim()).filter((x) => x.length > 0);
if (Array.isArray(rawTargets)) {
return fromArray(rawTargets);
}
if (typeof rawTargets === "string") {
const t = rawTargets.trim();
if (!t) return [];
if (t.startsWith("[") && t.endsWith("]")) {
try {
const parsed = JSON.parse(t);
if (Array.isArray(parsed)) {
return fromArray(parsed);
}
} catch {
}
}
return t.split(/[\s,]+/).map((x) => x.trim()).filter((x) => x.length > 0);
}
if (rawTargets == null) return [];
return [String(rawTargets)];
}
function parseTargets(targets) {
const parsed = { a: [], v: [], i: [], p: [] };
const invalid = [];
for (const raw of targets) {
const s = normalizeTargetNotationToken(raw);
const m = /^([avip])(\d+)$/i.exec(s);
if (!m) {
invalid.push(String(raw));
continue;
}
const kind = m[1].toLowerCase();
const n = parseInt(m[2], 10);
if (!Number.isFinite(n) || n <= 0) {
invalid.push(String(raw));
continue;
}
parsed[kind].push(n);
}
Object.keys(parsed).forEach((k) => {
parsed[k] = Array.from(new Set(parsed[k])).sort((a, b) => a - b);
});
return { parsed, invalid };
}
function normalizeAliasRef(input) {
const raw = String(input ?? "");
let s = raw.trim();
s = s.replace(/[)\],.;]+$/g, "");
s = s.replace(/^"(.+)"$/g, "$1");
s = s.replace(/^'(.+)'$/g, "$1");
let url;
try {
if (/^https?:\/\//i.test(s)) url = new URL(s);
} catch {
url = void 0;
}
const basename5 = (() => {
try {
if (url) return path32.posix.basename(url.pathname || "") || void 0;
return path32.basename(s) || void 0;
} catch {
return void 0;
}
})();
return { raw, trimmed: s, basename: basename5, url };
}
function resolveAliasTargets(state, refs) {
const resolved = [];
const unresolved = [];
const pushUnique = (arr, v) => {
const s = String(v || "").trim();
if (!s) return;
if (!arr.includes(s)) arr.push(s);
};
const matchByExactOrBasename = (candidate, basename5, field) => {
const v = typeof field === "string" ? field.trim() : "";
if (!v) return false;
if (v === candidate) return true;
if (!basename5) return false;
try {
return path32.basename(v) === basename5;
} catch {
return false;
}
};
for (const r of refs) {
const n = normalizeAliasRef(r);
const s = n.trimmed;
if (!s) {
unresolved.push(String(r));
continue;
}
const candidates = /* @__PURE__ */ new Set();
for (const rec of state.pictures || []) {
if (!rec || typeof rec.p !== "number") continue;
const pVal = rec.p;
if (!Number.isFinite(pVal) || pVal <= 0) continue;
if (matchByExactOrBasename(s, n.basename, rec.sourceUrl))
candidates.add(`p${pVal}`);
else if (matchByExactOrBasename(s, n.basename, rec.preview))
candidates.add(`p${pVal}`);
else if (matchByExactOrBasename(s, n.basename, rec.filename))
candidates.add(`p${pVal}`);
}
for (const rec of state.images || []) {
if (!rec || typeof rec.i !== "number") continue;
const iVal = rec.i;
if (!Number.isFinite(iVal) || iVal <= 0) continue;
if (matchByExactOrBasename(s, n.basename, rec.preview))
candidates.add(`i${iVal}`);
else if (matchByExactOrBasename(s, n.basename, rec.filename))
candidates.add(`i${iVal}`);
}
for (const rec of state.variants || []) {
if (!rec || typeof rec.v !== "number") continue;
const vVal = rec.v;
if (!Number.isFinite(vVal) || vVal <= 0) continue;
if (matchByExactOrBasename(s, n.basename, rec.preview))
candidates.add(`v${vVal}`);
else if (matchByExactOrBasename(s, n.basename, rec.filename))
candidates.add(`v${vVal}`);
else if (matchByExactOrBasename(s, n.basename, rec.sourceUrl))
candidates.add(`v${vVal}`);
}
for (const rec of state.attachments || []) {
if (!rec || typeof rec.a !== "number") continue;
const aVal = rec.a;
if (!Number.isFinite(aVal) || aVal <= 0) continue;
if (matchByExactOrBasename(s, n.basename, rec.originAbs))
candidates.add(`a${aVal}`);
else if (matchByExactOrBasename(s, n.basename, rec.preview))
candidates.add(`a${aVal}`);
else if (matchByExactOrBasename(s, n.basename, rec.filename))
candidates.add(`a${aVal}`);
}
if (candidates.size === 1) {
pushUnique(resolved, Array.from(candidates)[0]);
continue;
}
unresolved.push(String(r));
}
return { resolved, unresolved };
}
function getAvailable(state) {
const availableA = (state.attachments || []).map((x) => typeof x?.a === "number" ? x.a : void 0).filter((x) => typeof x === "number" && x > 0).sort((a, b) => a - b);
const availableV = (state.variants || []).map((x) => typeof x?.v === "number" ? x.v : void 0).filter((x) => typeof x === "number" && x > 0).sort((a, b) => a - b);
const availableI = (state.images || []).map((x) => typeof x?.i === "number" ? x.i : void 0).filter((x) => typeof x === "number" && x > 0).sort((a, b) => a - b);
const availableP = (state.pictures || []).map((x) => typeof x?.p === "number" ? x.p : void 0).filter((x) => typeof x === "number" && x > 0).sort((a, b) => a - b);
return { availableA, availableV, availableI, availableP };
}
async function ensurePreviewExists(chatWd, previewRel) {
const pAbs = path32.join(chatWd, previewRel);
await fs27.promises.access(pAbs, fs27.constants.F_OK);
}
function appendReviewToPluginLog(line) {
try {
const logsDir2 = getLogsDir();
if (!fs27.existsSync(logsDir2)) fs27.mkdirSync(logsDir2, { recursive: true });
fs27.appendFileSync(
path32.join(logsDir2, getPluginLogFilename()),
`${localTimestamp()} - ${line}
`
);
} catch {
}
}
function createReviewImageTool(ctl) {
return tool({
name: "review_image",
description: `Request visual inspection of one or more media items for the agent's analysis.
Visibility rules: This tool shows images to the agent only (for internal review/analysis). The user doesn't see anything from this call.
There are three distinct media classes, each with different visibility behaviour:
- Attachments (aN): Images provided by the user. Displayed automatically on first appearance. Use review_image to re-examine them \u2014 for a closer look, re-evaluation, or comparison.
- Variants (vN): Images or video previews produced by generate_image. Also displayed automatically once. Use review_image to return them to the agent's view for inspection or side-by-side comparison.
- Pictures (pN): A separate class \u2014 typically search results returned by image-index tools such as find_image or index_image, often in larger quantities. Pictures are NEVER shown automatically and are only made visible on explicit request via this tool.
Since each attachment and variant renders only once automatically, review_image is also the reliable way to place any selection of results side-by-side for direct visual comparison.
Parameters:
- targets: Field in the JSON argument object. Pass a JSON array of media notations, e.g. {"targets":["v1", "v2"]}.
- aN \u2014 Attachment N (e.g. a1, a2)
- vN \u2014 Generated variant N (e.g. v1, v3)
- pN \u2014 Picture / index result N (e.g. p1, p2)
Examples:
- {"targets":["v1", "v2", "v3"]} \u2014 Compare three generated variants side-by-side
- {"targets":["p1", "p2", "p3"]} \u2014 Inspect the top results from a find_image or index_image search
- {"targets":["a1", "v1"]} \u2014 Compare the original attachment with a generated result
- {"targets":["v1"]} \u2014 Re-examine a single variant for closer review
${formatToolMetaBlock()}`,
parameters: ReviewImageParamsShape,
implementation: async (args, ctx) => {
try {
try {
const workingDir2 = ctl.getWorkingDirectory();
if (typeof workingDir2 === "string" && workingDir2.trim().length > 0) {
const chatId2 = path32.basename(workingDir2);
if (/^\d+$/.test(chatId2)) {
setActiveChatContext({
chatId: chatId2,
workingDir: workingDir2,
requestId: `tool-${Date.now()}`
});
}
}
} catch {
}
const previewInChat = String(process.env.PREVIEW_IN_CHAT || "").toLowerCase() === "true";
if (previewInChat) {
const msg = 'review_image can\u2019t be used while "Simple Previews in Chat" is enabled. In that mode the plugin does not keep the local preview/index files required for re-view. Turn OFF "Simple Previews in Chat" in Global Plugin Settings, then call review_image again.';
try {
ctx.status(
"review_image unavailable: Simple Previews in Chat is enabled"
);
} catch {
}
return msg;
}
const strict = args?.strict !== void 0 ? !!args.strict : true;
const targets = normalizeTargetsArg(args?.targets);
const { parsed, invalid: invalidRaw } = parseTargets(targets);
const workingDir = ctl.getWorkingDirectory();
if (typeof workingDir !== "string" || !workingDir.trim()) {
return "review_image failed: working directory not available.";
}
const chatWd = workingDir;
const chatId = (() => {
try {
return path32.basename(chatWd);
} catch {
return "(unknown)";
}
})();
const state = await readState(chatWd);
const { resolved: resolvedAliases, unresolved: unresolvedAliases } = invalidRaw.length > 0 ? resolveAliasTargets(state, invalidRaw) : { resolved: [], unresolved: [] };
if (resolvedAliases.length > 0) {
const { parsed: parsed2, invalid: stillInvalid } = parseTargets(
resolvedAliases
);
parsed.a.push(...parsed2.a);
parsed.v.push(...parsed2.v);
parsed.i.push(...parsed2.i);
parsed.p.push(...parsed2.p);
unresolvedAliases.push(...stillInvalid);
}
Object.keys(parsed).forEach((k) => {
parsed[k] = Array.from(new Set(parsed[k])).sort((a, b) => a - b);
});
if (unresolvedAliases.length > 0 && strict) {
return `review_image failed: invalid targets: ${unresolvedAliases.map((s) => JSON.stringify(s)).join(", ")}`;
}
const { availableA, availableV, availableI, availableP } = getAvailable(state);
const missingNotations = /* @__PURE__ */ new Set();
const missingDetails = [];
for (const n of parsed.a) {
const rec = (state.attachments || []).find((x) => x?.a === n);
if (!rec) {
missingNotations.add(`a${n}`);
missingDetails.push(`a${n}`);
continue;
}
const previewRel = typeof rec.preview === "string" ? String(rec.preview) : "";
if (!previewRel.trim()) {
missingNotations.add(`a${n}`);
missingDetails.push(`a${n} (missing preview)`);
continue;
}
try {
await ensurePreviewExists(chatWd, previewRel);
} catch {
missingNotations.add(`a${n}`);
missingDetails.push(`a${n} (preview file missing)`);
}
}
for (const n of parsed.v) {
const rec = (state.variants || []).find((x) => x?.v === n);
if (!rec) {
missingNotations.add(`v${n}`);
missingDetails.push(`v${n}`);
continue;
}
const previewRel = typeof rec.preview === "string" ? String(rec.preview) : "";
if (!previewRel.trim()) {
missingNotations.add(`v${n}`);
missingDetails.push(`v${n} (missing preview)`);
continue;
}
try {
await ensurePreviewExists(chatWd, previewRel);
} catch {
missingNotations.add(`v${n}`);
missingDetails.push(`v${n} (preview file missing)`);
}
}
for (const n of parsed.i) {
const rec = (state.images || []).find((x) => x?.i === n);
if (!rec) {
missingNotations.add(`i${n}`);
missingDetails.push(`i${n}`);
continue;
}
const previewRel = typeof rec.preview === "string" ? String(rec.preview) : "";
if (!previewRel.trim()) {
missingNotations.add(`i${n}`);
missingDetails.push(`i${n} (missing preview)`);
continue;
}
try {
await ensurePreviewExists(chatWd, previewRel);
} catch {
missingNotations.add(`i${n}`);
missingDetails.push(`i${n} (preview file missing)`);
}
}
for (const n of parsed.p) {
const rec = (state.pictures || []).find((x) => x?.p === n);
if (!rec) {
missingNotations.add(`p${n}`);
missingDetails.push(`p${n}`);
continue;
}
const previewRel = typeof rec.preview === "string" ? String(rec.preview) : "";
if (!previewRel.trim()) {
missingNotations.add(`p${n}`);
missingDetails.push(`p${n} (missing preview)`);
continue;
}
try {
await ensurePreviewExists(chatWd, previewRel);
} catch {
missingNotations.add(`p${n}`);
missingDetails.push(`p${n} (preview file missing)`);
}
}
if (missingDetails.length > 0 && strict) {
const hint = `Available: a=[${availableA.map((x) => `a${x}`).join(", ") || "(none)"}] v=[${availableV.map((x) => `v${x}`).join(", ") || "(none)"}] i=[${availableI.map((x) => `i${x}`).join(", ") || "(none)"}] p=[${availableP.map((x) => `p${x}`).join(", ") || "(none)"}]`;
return `review_image failed: unknown/invalid targets: ${missingDetails.join(", ")}. ${hint}`;
}
if (!strict && missingNotations.size > 0) {
parsed.a = parsed.a.filter((n) => !missingNotations.has(`a${n}`));
parsed.v = parsed.v.filter((n) => !missingNotations.has(`v${n}`));
parsed.i = parsed.i.filter((n) => !missingNotations.has(`i${n}`));
parsed.p = parsed.p.filter((n) => !missingNotations.has(`p${n}`));
}
const requestedByToolCallId = (() => {
try {
const anyCtx = ctx;
const v = anyCtx?.toolCallId ?? anyCtx?.tool_call_id ?? anyCtx?.id ?? anyCtx?.callId;
return typeof v === "string" && v.trim() ? v.trim() : void 0;
} catch {
return void 0;
}
})();
state.pendingReviewPromotion = {
requestedAt: localTimestamp(),
requestedByToolCallId,
ttlMs: 5 * 60 * 1e3,
targets: {
a: parsed.a.length ? parsed.a : void 0,
v: parsed.v.length ? parsed.v : void 0,
i: parsed.i.length ? parsed.i : void 0,
p: parsed.p.length ? parsed.p : void 0
}
};
await writeStateAtomic(chatWd, state);
const scheduled = [];
scheduled.push(...parsed.a.map((n) => `a${n}`));
scheduled.push(...parsed.v.map((n) => `v${n}`));
scheduled.push(...parsed.i.map((n) => `i${n}`));
scheduled.push(...parsed.p.map((n) => `p${n}`));
try {
appendReviewToPluginLog(
`VIP review scheduled: chatId=${chatId} targets=[${scheduled.join(",")}]` + (requestedByToolCallId ? ` toolCallId=${requestedByToolCallId}` : "")
);
} catch {
}
try {
ctx.status(`Scheduled re-view for: ${scheduled.join(", ")}`);
} catch {
}
return `Scheduled re-view for: ${scheduled.join(", ")}`;
} catch (e) {
return `review_image failed: ${String(e?.message || e)}`;
}
}
});
}
// src/tools/review_sequence.ts
import { tool as tool2 } from "@lmstudio/sdk";
import { z as z3 } from "zod";
import path33 from "path";
import fs28 from "fs";
var ReviewSequenceParamsShape = {
variant: z3.coerce.string().describe(
"Reference to the video to review. Use standard media notation: vN for variants, iN for images, pN for pictures (e.g. v1, i3). A bare integer N is also accepted and treated as vN. Must correspond to a generated video."
),
fps: z3.coerce.number().min(0.1).max(30).optional().default(2).describe(
"Frame sampling rate in fps. Default: 2. Higher values send more frames to the model."
)
};
function appendReviewSequenceToPluginLog(line) {
try {
const logsDir2 = getLogsDir();
if (!fs28.existsSync(logsDir2)) fs28.mkdirSync(logsDir2, { recursive: true });
fs28.appendFileSync(
path33.join(logsDir2, getPluginLogFilename()),
`${localTimestamp()} - ${line}
`
);
} catch {
}
}
function createReviewSequenceTool(ctl) {
return tool2({
name: "review_sequence",
description: `Send a frame sequence of a generated video to the model for visual review.
Use this when the user asks you to watch, review or analyse the content of a generated video.
LM Studio does not support native video objects; this tool compensates by sampling frames at a configurable fps and transmitting them as a labelled image sequence.
Parameters:
- variant: Media reference for the video \u2014 vN, iN, or pN notation (e.g. v1, i3).
- fps: Frame sampling rate (default: 2). Higher \u2192 more frames \u2192 larger context.
${formatToolMetaBlock()}`,
parameters: ReviewSequenceParamsShape,
implementation: async (args, ctx) => {
try {
try {
const workingDir2 = ctl.getWorkingDirectory();
if (typeof workingDir2 === "string" && workingDir2.trim().length > 0) {
const chatId2 = path33.basename(workingDir2);
if (/^\d+$/.test(chatId2)) {
setActiveChatContext({
chatId: chatId2,
workingDir: workingDir2,
requestId: `tool-${Date.now()}`
});
}
}
} catch {
}
const workingDir = ctl.getWorkingDirectory();
if (typeof workingDir !== "string" || !workingDir.trim()) {
return "review_sequence failed: working directory not available.";
}
const chatWd = workingDir;
const rawRef = typeof args?.variant === "string" ? args.variant.trim() : String(args?.variant ?? "").trim();
let refType = "v";
let refNum = 0;
const refMatch = /^([vip])(\d+)$/i.exec(rawRef);
if (refMatch) {
refType = refMatch[1].toLowerCase();
refNum = parseInt(refMatch[2], 10);
} else if (/^\d+$/.test(rawRef)) {
refType = "v";
refNum = parseInt(rawRef, 10);
}
if (refNum <= 0) {
return "review_sequence failed: variant must be a media reference like 'v1', 'i3', 'p2', or a positive integer.";
}
const displayRef = `${refType}${refNum}`;
const fps = typeof args?.fps === "number" && args.fps > 0 ? args.fps : 2;
const state = await readState(chatWd);
let movAbs;
if (refType === "v") {
const rec = (state.variants || []).find(
(x) => typeof x?.v === "number" && x.v === refNum
);
if (!rec) {
const available = [
...(state.variants || []).map((x) => typeof x?.v === "number" ? `v${x.v}` : null),
...(state.images || []).map((x) => typeof x?.i === "number" ? `i${x.i}` : null)
].filter(Boolean).join(", ");
return `review_sequence failed: ${displayRef} not found in state.` + (available ? ` Available: ${available}.` : " No variants or images recorded yet.");
}
const fn = typeof rec.filename === "string" ? String(rec.filename) : "";
if (!fn) return `review_sequence failed: ${displayRef} has no filename recorded.`;
movAbs = path33.join(chatWd, fn.replace(/\.png$/i, ".mov"));
} else if (refType === "i") {
const rec = (state.images || []).find(
(x) => typeof x?.i === "number" && x.i === refNum
);
if (!rec) {
const available = [
...(state.variants || []).map((x) => typeof x?.v === "number" ? `v${x.v}` : null),
...(state.images || []).map((x) => typeof x?.i === "number" ? `i${x.i}` : null)
].filter(Boolean).join(", ");
return `review_sequence failed: ${displayRef} not found in state.` + (available ? ` Available: ${available}.` : " No variants or images recorded yet.");
}
const fn = typeof rec.filename === "string" ? String(rec.filename) : "";
if (!fn) return `review_sequence failed: ${displayRef} has no filename recorded.`;
movAbs = path33.join(chatWd, fn.replace(/\.png$/i, ".mov"));
} else {
const rec = (state.pictures || []).find(
(x) => typeof x?.p === "number" && x.p === refNum
);
if (!rec) {
const available = (state.pictures || []).map((x) => typeof x?.p === "number" ? `p${x.p}` : null).filter(Boolean).join(", ");
return `review_sequence failed: ${displayRef} not found in state.` + (available ? ` Available: ${available}.` : " No pictures recorded yet.");
}
const src = typeof rec.sourceUrl === "string" ? String(rec.sourceUrl) : "";
if (!src) return `review_sequence failed: ${displayRef} has no sourceUrl recorded.`;
movAbs = src;
}
let movExists = false;
try {
await fs28.promises.access(movAbs, fs28.constants.F_OK);
movExists = true;
} catch {
movExists = false;
}
if (!movExists) {
return `review_sequence failed: no video file found for ${displayRef}. Expected: ${movAbs}. ${displayRef} may be a still image, not a video.`;
}
state.pendingSequenceReview = {
requestedAt: localTimestamp(),
movAbs,
variant: refNum,
variantLabel: displayRef,
fps,
ttlMs: 5 * 60 * 1e3
};
await writeStateAtomic(chatWd, state);
const chatId = (() => {
try {
return path33.basename(chatWd);
} catch {
return "(unknown)";
}
})();
try {
appendReviewSequenceToPluginLog(
`Sequence review scheduled: chatId=${chatId} ref=${displayRef} fps=${fps}`
);
} catch {
}
try {
ctx.status(`Extracting frames for ${displayRef} at ${fps} fps\u2026`);
} catch {
}
return `Scheduled sequence review for ${displayRef} at ${fps} fps.`;
} catch (e) {
return `review_sequence failed: ${String(e?.message || e)}`;
}
}
});
}
export {
AGENT_MODE_ORDER,
AGENT_NAMES,
ALLOWED_GEN_INPUT_KEYS,
ATTACHMENT_CONFIG,
ATTACHMENT_FULL_CONFIG,
BOX_MATCH_IOU,
ColorCalibration,
CompressionMethod,
Control,
ControlInputType,
ControlMode,
CropToolParamsShape,
CropToolSchemaStrict,
DEFAULT_MAX_REFERENCE_IMAGES,
DEFAULT_RECONCILE_OPTIONS,
DrawThingsGrpcService,
DrawThingsService,
FASTVLM_DEFAULT_ENDPOINT,
GenerateToolParamsSchema,
GenerateToolParamsSchemaBase,
GenerateToolParamsSchemaMinimalStrict,
GenerateToolParamsShapeMinimal,
GenerationConfiguration,
IMAGE_CONFIG,
IMAGE_FULL_CONFIG,
IMAGE_MODEL_CAPABILITY_MAP,
INJECTION_END,
INJECTION_START,
InpaintToolParamsShape,
InpaintToolSchemaStrict,
LoRA,
LoRAMode,
MEDIA_HARVESTING_CONFIG,
MEDIA_SOURCE_REGISTRY,
MLX_VISION_ANALYZE_IMAGE_PROMPT,
MLX_VISION_INDEX_IMAGE_PROMPT,
MODEL_FAMILIES,
MODEL_IDS,
MODEL_PRESET_TO_CAPABILITY_KEY,
OVERLAY_REGISTRY,
OutpaintToolParamsShape,
OutpaintToolSchemaStrict,
PICTURE_CONFIG,
PICTURE_FULL_CONFIG,
PROMPT_UPSAMPLER_APIS,
PROMPT_UPSAMPLER_FAMILY_SPECS,
PROMPT_UPSAMPLING_MODEL_FAMILIES,
Reason,
SamplerType,
SeedMode,
TensorHistoryNode,
TextHistoryNode,
TextModification,
TextRange,
TextType,
ThumbnailHistoryNode,
UpscaleToolParamsShape,
UpscaleToolSchemaStrict,
VARIANT_CONFIG,
VARIANT_FULL_CONFIG,
VISION_WINDOW_SIZES,
ZoomInToolParamsShape,
ZoomInToolSchemaStrict,
agentNameOfFamily,
agentNameOfModel,
appendErrorRaw,
appendImages,
appendMediaItems,
appendModelHint,
appendPictures,
appendPluginLog,
appendVariants,
appendVisionPromotionJsonl,
applyPromptUpsampling,
autoFallbackFor,
bitmapToLab,
boxesFromMask,
buildAuditLogger,
buildDtGenerationConfiguration,
buildDtcModelMappingSnapshot,
buildInventory,
buildLockedInstruction,
buildModelListText,
buildPlainRows,
buildPromotionItems,
buildPromptUpsamplingAudit,
cancelBackgroundRequest,
catalogModeFor,
catalogModelById,
catalogModelOfFile,
catalogOverlayFor,
checkCustomConfigs,
checkDrawThingsGrpcAssets,
checkDrawThingsGrpcFilesExist,
checkFreshness,
checkModeSupport,
checkModeSupportWithCustom,
checkProfileModels,
checkVisionPrimerStatus,
chooseAlignedCanvas,
clampNumber,
clearCustomConfigsCache,
clearInjections,
compareInventoryWithRegistry,
configSchematics,
correctMaskColorDrift,
correctMaskColorDriftPng,
createBackgroundRequestId,
createInventoryProvider,
createMcpProgressSender,
createProgressReporter,
createReviewImageTool,
createReviewSequenceTool,
createSaveOriginalPng,
createStatusProgressCallback,
cropToPng,
currentInventory,
currentRequestLogId,
currentToolName,
decodeToRgba,
deepParseMaybeJson,
defaultParams,
defaultParamsImg2Img2 as defaultParamsEdit,
defaultParamsImage2Video,
defaultParamsImg2Img,
defaultParamsImg2Img3 as defaultParamsRestore,
defaultParamsText2Video,
defaultParamsZoom,
derivativeSourceRef,
describeMissingProfileModel,
detectCapabilities,
detectImageMimeType,
detectImageModelCapabilities,
detectProjectImageType,
diffProjectGenerationSnapshots,
drawthingsLimits as drawthingsEditLimits,
drawthingsLimits,
drawthingsLimits as drawthingsRestoreLimits,
drawthingsLimits as drawthingsZoomLimits,
echoFetcherForClient,
encodeFileUrl,
encodeJpegPreview,
encodeJpegPreviewFromBuffer,
encodeRgbaToPng,
engineConnectionDefaults,
ensureAgentModelLoaded,
ensureLlamaServerRouterRunning,
ensureLogsDir,
explainFile,
explainRequiredFile,
extractPendingAttachments,
extractSequenceFrames,
extractToolCalls,
extractToolResultImageCandidates,
extractUserAttachments,
fileInWd,
findAllAttachmentsLegacy,
findAllImages,
findAllMedia,
findAllMediaAllTypes,
findAllPictures,
findAllVariantsLegacy,
findConversationPath,
findCustomPresetsByModelFile,
findImageModelCapabilitiesByFilename,
findLMStudioHome,
findLastAttachmentLegacy,
findLastImages,
findLastMedia,
findLastPictures,
findLmsCli,
findMessagesArray,
findStateRecord,
formatEta,
formatImageModelForToolDisplay,
formatModelHint,
formatToolMetaBlock,
formatZodError,
generatePreview,
generatePreviewFromBuffer,
generateRuntimeDefaults,
generationConfigBytesToV2,
getActiveChatContext,
getAllMediaTypeConfigs,
getAllMediaTypeFullConfigs,
getAllowlistedPictureTools,
getAttachmentWindowSize,
getAudioSampleRateForModel,
getAvailableCustomCombinations,
getBackgroundRequest,
getCancelSignal,
getCapabilityKeyForPreset,
getConfiguredCustomConfigsPath,
getCurrentConnectionSettings,
getCustomPreset,
getCustomPresetLabelsUsingModelFilename,
getDefaultFpsForModel,
getDefaultPreviewOptions,
getDrawThingsGenerationMetadata,
getEffectiveOverlay,
getEngineConnectionDefaults,
getEverythingElseWindowSize,
getHealthyServerBaseUrl,
getInjectionCount,
getLMConversationFilePath,
getLMStudioFileMetadata,
getLMStudioUserFilePath,
getLMStudioWorkingDir,
getLogsDir,
getMaxReferenceImages,
getMediaTypeConfig,
getMediaTypeForTool,
getMediaTypeForToolCall,
getMediaTypeFullConfig,
getMessageRole,
getModelFilename,
getModelListText,
getModelOverlay,
getModelRequiredFiles,
getOriginalFileName,
getPluginLogFilename,
getPluginMeta,
getProjectRoot,
getPromotableAttachmentNs,
getPromotableEverythingElse,
getPromotableImageIs,
getPromotableVariantVs,
getSelfPluginIdentifier,
getSize,
getStateArrayKey,
getThumbnailFromProject,
getThumbnailsFromProject,
getToolExtractor,
getUndeliveredCompletedBackgroundRequests,
getWindowSizeForKind,
globalConfigSchematics,
gridBoxIoU,
guessExtForOriginal,
harvestToolResultImages,
hasInjections,
hasInventoryFetcher,
hasTrackedInjections,
image2imageAlternatives,
image2imagePresetOf,
image2imageUnavailable,
importAttachmentBatch,
injectLastUsedModelIntoNewestChat,
injectXmpIntoBuffer,
installedAgentNames,
installedFileOf,
isAllowedOriginalExt,
isAllowlistedSsotToolCall,
isBackgroundCall,
isDerivativeToolRecord,
isHttpServerHealthy,
isImage2ImageMode,
isKnownModel,
isLegacyPresetName,
isLocalLmApiBaseUrl,
isModelInstalled,
isModelLoaded,
isPictureToolAllowlisted,
isPng,
isPresetName,
isProjectUri,
isSupportedImageBuffer,
isToolAllowlistedForMediaType,
isValidModelId,
isoStamp,
legacyNamesOf,
listAvailable,
listBackgroundRequests,
listImage2ImageModels,
listUsablePresets,
loadCustomConfigs,
loadVisionPrimerModel,
localTimestamp,
log,
logError,
logShadowReport,
logTimestamp,
loraFallbackOverlay,
markBackgroundRequestDelivered,
markBackgroundRequestFailed,
markBackgroundRequestQueued,
materializeToolResultImageToFiles,
modelLine,
modelOverlays,
normalizeInputBuffer,
normalizeModelId,
normalizeModelName,
normalizeQualityToInt,
normalizeSourceNotation,
normalizeToolPluginId,
officialNameFor,
parseDigitOnlyNotation,
parseEchoResponse,
parseMessages,
parsePrefixedNotation,
parseProjectUri,
parseThinkingToolCalls,
parseToolResultPayload,
parseVisionPromotionJsonlText,
peekInventory,
pickFallbackModel,
prepareInventoryFetcher,
preprocess,
presetAvailability,
previewDefaults,
previewFilenameFrom,
primeInventoryFromEcho,
primeVisionCapability,
projectGenerationFingerprint,
projectGenerationIdentity,
proxyMarks,
pyJson,
readBackgroundRequests,
readCameraImageMetadata,
readConversation,
readLastAttachmentRef,
readPromptUpsamplerConfigFromEnv,
readState,
readVisionPromotionJsonlEntries,
recommendedParamsFor,
reconcileMedia,
recordGeneratedVariants,
rectMask,
referencedFiles,
registerInventoryFetcher,
rehydrateLastAttachment,
reimposeBoxes,
renderPictureMarkdown,
requestBelongsToScope,
requestLogPrefix,
requiredFileForProfile,
resizeAndEncode,
resizeAndEncodeByHeight,
resizeAndEncodeBySum,
resizeCanvasAndMask,
resizeCoverToPng,
resizeFillToPng,
resizeInsideToPng,
resolveActions,
resolveActiveLMStudioChatId,
resolveAutoFallback,
resolveEffectiveSourceToken,
resolveImageModelInfoFromModelUsed,
resolveImg2ImgSourceLMStudio,
resolveInjection,
resolveLatestLmStudioLlamaServer,
resolveMessageVersion,
resolveModelArgument,
resolveOriginalReference,
resolveProjectGenerationMetadata,
resolveProjectUri,
resolveRequestedModel,
resolveRequestedOutputDims,
resolveTensorDecoderProfile,
runAsBackgroundCall,
runBackgroundJobAwaited,
runInBackgroundJob,
runInventoryShadow,
runWithCancelSignal,
runWithRequestLogId,
runWithToolName,
runWithToolPass,
runtimeCatalog,
scanMedia,
selectAutoModel,
setActiveChatContext,
setDrawThingsServiceRootStart,
shouldPromoteAttachments,
shouldPromoteEverythingElseIdempotent,
shouldPromoteVariantsIdempotent,
shouldUseFilesApiForModel,
splitCaptionAndRows,
stateOfFile,
stopLlamaServerRouter,
stripInjections,
stripInternalToolKeys,
substituteInstalledPrecision,
substitutionNote,
supportsMode,
syncAttachmentsToState,
toHttpOriginalUrl,
toHttpPreviewUrl,
toOpenAIPromptParts,
toOverlayMode,
toPng,
trackInjection,
tsForFilename,
tunedPresetFor,
unloadAgentModel,
unloadVisionPrimer,
updateLastUsedModelForAgentModel,
upsertAttachment,
validateImageGenerationParams,
withInstalledPrecision,
withProxyMarks,
wrapInjection,
writeBackgroundRequestsAtomic,
writeStateAtomic
};
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
var __commonJS = (cb, mod) => function __require2() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target2) => (target2 = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target2, "default", { value: mod, enumerable: true }) : target2,
mod
));
// node_modules/flatbuffers/js/constants.js
var require_constants = __commonJS({
"node_modules/flatbuffers/js/constants.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SIZE_PREFIX_LENGTH = exports.FILE_IDENTIFIER_LENGTH = exports.SIZEOF_INT = exports.SIZEOF_SHORT = void 0;
exports.SIZEOF_SHORT = 2;
exports.SIZEOF_INT = 4;
exports.FILE_IDENTIFIER_LENGTH = 4;
exports.SIZE_PREFIX_LENGTH = 4;
}
});
// node_modules/flatbuffers/js/utils.js
var require_utils = __commonJS({
"node_modules/flatbuffers/js/utils.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isLittleEndian = exports.float64 = exports.float32 = exports.int32 = void 0;
exports.int32 = new Int32Array(2);
exports.float32 = new Float32Array(exports.int32.buffer);
exports.float64 = new Float64Array(exports.int32.buffer);
exports.isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1;
}
});
// node_modules/flatbuffers/js/encoding.js
var require_encoding = __commonJS({
"node_modules/flatbuffers/js/encoding.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Encoding = void 0;
var Encoding;
(function(Encoding2) {
Encoding2[Encoding2["UTF8_BYTES"] = 1] = "UTF8_BYTES";
Encoding2[Encoding2["UTF16_STRING"] = 2] = "UTF16_STRING";
})(Encoding || (exports.Encoding = Encoding = {}));
}
});
// node_modules/flatbuffers/js/byte-buffer.js
var require_byte_buffer = __commonJS({
"node_modules/flatbuffers/js/byte-buffer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ByteBuffer = void 0;
var constants_js_1 = require_constants();
var encoding_js_1 = require_encoding();
var utils_js_1 = require_utils();
var ByteBuffer3 = class _ByteBuffer {
/**
* Create a new ByteBuffer with a given array of bytes (`Uint8Array`)
*/
constructor(bytes_) {
this.bytes_ = bytes_;
this.position_ = 0;
this.text_decoder_ = new TextDecoder();
}
/**
* Create and allocate a new ByteBuffer with a given size.
*/
static allocate(byte_size) {
return new _ByteBuffer(new Uint8Array(byte_size));
}
clear() {
this.position_ = 0;
}
/**
* Get the underlying `Uint8Array`.
*/
bytes() {
return this.bytes_;
}
/**
* Get the buffer's position.
*/
position() {
return this.position_;
}
/**
* Set the buffer's position.
*/
setPosition(position) {
this.position_ = position;
}
/**
* Get the buffer's capacity.
*/
capacity() {
return this.bytes_.length;
}
readInt8(offset) {
return this.readUint8(offset) << 24 >> 24;
}
readUint8(offset) {
return this.bytes_[offset];
}
readInt16(offset) {
return this.readUint16(offset) << 16 >> 16;
}
readUint16(offset) {
return this.bytes_[offset] | this.bytes_[offset + 1] << 8;
}
readInt32(offset) {
return this.bytes_[offset] | this.bytes_[offset + 1] << 8 | this.bytes_[offset + 2] << 16 | this.bytes_[offset + 3] << 24;
}
readUint32(offset) {
return this.readInt32(offset) >>> 0;
}
readInt64(offset) {
return BigInt.asIntN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32)));
}
readUint64(offset) {
return BigInt.asUintN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32)));
}
readFloat32(offset) {
utils_js_1.int32[0] = this.readInt32(offset);
return utils_js_1.float32[0];
}
readFloat64(offset) {
utils_js_1.int32[utils_js_1.isLittleEndian ? 0 : 1] = this.readInt32(offset);
utils_js_1.int32[utils_js_1.isLittleEndian ? 1 : 0] = this.readInt32(offset + 4);
return utils_js_1.float64[0];
}
writeInt8(offset, value) {
this.bytes_[offset] = value;
}
writeUint8(offset, value) {
this.bytes_[offset] = value;
}
writeInt16(offset, value) {
this.bytes_[offset] = value;
this.bytes_[offset + 1] = value >> 8;
}
writeUint16(offset, value) {
this.bytes_[offset] = value;
this.bytes_[offset + 1] = value >> 8;
}
writeInt32(offset, value) {
this.bytes_[offset] = value;
this.bytes_[offset + 1] = value >> 8;
this.bytes_[offset + 2] = value >> 16;
this.bytes_[offset + 3] = value >> 24;
}
writeUint32(offset, value) {
this.bytes_[offset] = value;
this.bytes_[offset + 1] = value >> 8;
this.bytes_[offset + 2] = value >> 16;
this.bytes_[offset + 3] = value >> 24;
}
writeInt64(offset, value) {
this.writeInt32(offset, Number(BigInt.asIntN(32, value)));
this.writeInt32(offset + 4, Number(BigInt.asIntN(32, value >> BigInt(32))));
}
writeUint64(offset, value) {
this.writeUint32(offset, Number(BigInt.asUintN(32, value)));
this.writeUint32(offset + 4, Number(BigInt.asUintN(32, value >> BigInt(32))));
}
writeFloat32(offset, value) {
utils_js_1.float32[0] = value;
this.writeInt32(offset, utils_js_1.int32[0]);
}
writeFloat64(offset, value) {
utils_js_1.float64[0] = value;
this.writeInt32(offset, utils_js_1.int32[utils_js_1.isLittleEndian ? 0 : 1]);
this.writeInt32(offset + 4, utils_js_1.int32[utils_js_1.isLittleEndian ? 1 : 0]);
}
/**
* Return the file identifier. Behavior is undefined for FlatBuffers whose
* schema does not include a file_identifier (likely points at padding or the
* start of a the root vtable).
*/
getBufferIdentifier() {
if (this.bytes_.length < this.position_ + constants_js_1.SIZEOF_INT + constants_js_1.FILE_IDENTIFIER_LENGTH) {
throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");
}
let result = "";
for (let i = 0; i < constants_js_1.FILE_IDENTIFIER_LENGTH; i++) {
result += String.fromCharCode(this.readInt8(this.position_ + constants_js_1.SIZEOF_INT + i));
}
return result;
}
/**
* Look up a field in the vtable, return an offset into the object, or 0 if the
* field is not present.
*/
__offset(bb_pos, vtable_offset) {
const vtable = bb_pos - this.readInt32(bb_pos);
return vtable_offset < this.readInt16(vtable) ? this.readInt16(vtable + vtable_offset) : 0;
}
/**
* Initialize any Table-derived type to point to the union at the given offset.
*/
__union(t, offset) {
t.bb_pos = offset + this.readInt32(offset);
t.bb = this;
return t;
}
/**
* Create a JavaScript string from UTF-8 data stored inside the FlatBuffer.
* This allocates a new string and converts to wide chars upon each access.
*
* To avoid the conversion to string, pass Encoding.UTF8_BYTES as the
* "optionalEncoding" argument. This is useful for avoiding conversion when
* the data will just be packaged back up in another FlatBuffer later on.
*
* @param offset
* @param opt_encoding Defaults to UTF16_STRING
*/
__string(offset, opt_encoding) {
offset += this.readInt32(offset);
const length = this.readInt32(offset);
offset += constants_js_1.SIZEOF_INT;
const utf8bytes = this.bytes_.subarray(offset, offset + length);
if (opt_encoding === encoding_js_1.Encoding.UTF8_BYTES)
return utf8bytes;
else
return this.text_decoder_.decode(utf8bytes);
}
/**
* Handle unions that can contain string as its member, if a Table-derived type then initialize it,
* if a string then return a new one
*
* WARNING: strings are immutable in JS so we can't change the string that the user gave us, this
* makes the behaviour of __union_with_string different compared to __union
*/
__union_with_string(o, offset) {
if (typeof o === "string") {
return this.__string(offset);
}
return this.__union(o, offset);
}
/**
* Retrieve the relative offset stored at "offset"
*/
__indirect(offset) {
return offset + this.readInt32(offset);
}
/**
* Get the start of data of a vector whose offset is stored at "offset" in this object.
*/
__vector(offset) {
return offset + this.readInt32(offset) + constants_js_1.SIZEOF_INT;
}
/**
* Get the length of a vector whose offset is stored at "offset" in this object.
*/
__vector_len(offset) {
return this.readInt32(offset + this.readInt32(offset));
}
__has_identifier(ident) {
if (ident.length != constants_js_1.FILE_IDENTIFIER_LENGTH) {
throw new Error("FlatBuffers: file identifier must be length " + constants_js_1.FILE_IDENTIFIER_LENGTH);
}
for (let i = 0; i < constants_js_1.FILE_IDENTIFIER_LENGTH; i++) {
if (ident.charCodeAt(i) != this.readInt8(this.position() + constants_js_1.SIZEOF_INT + i)) {
return false;
}
}
return true;
}
/**
* A helper function for generating list for obj api
*/
createScalarList(listAccessor, listLength) {
const ret = [];
for (let i = 0; i < listLength; ++i) {
const val = listAccessor(i);
if (val !== null) {
ret.push(val);
}
}
return ret;
}
/**
* A helper function for generating list for obj api
* @param listAccessor function that accepts an index and return data at that index
* @param listLength listLength
* @param res result list
*/
createObjList(listAccessor, listLength) {
const ret = [];
for (let i = 0; i < listLength; ++i) {
const val = listAccessor(i);
if (val !== null) {
ret.push(val.unpack());
}
}
return ret;
}
};
exports.ByteBuffer = ByteBuffer3;
}
});
// node_modules/flatbuffers/js/builder.js
var require_builder = __commonJS({
"node_modules/flatbuffers/js/builder.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Builder = void 0;
var byte_buffer_js_1 = require_byte_buffer();
var constants_js_1 = require_constants();
var Builder2 = class _Builder {
/**
* Create a FlatBufferBuilder.
*/
constructor(opt_initial_size) {
this.minalign = 1;
this.vtable = null;
this.vtable_in_use = 0;
this.isNested = false;
this.object_start = 0;
this.vtables = [];
this.vector_num_elems = 0;
this.force_defaults = false;
this.string_maps = null;
this.text_encoder = new TextEncoder();
let initial_size;
if (!opt_initial_size) {
initial_size = 1024;
} else {
initial_size = opt_initial_size;
}
this.bb = byte_buffer_js_1.ByteBuffer.allocate(initial_size);
this.space = initial_size;
}
clear() {
this.bb.clear();
this.space = this.bb.capacity();
this.minalign = 1;
this.vtable = null;
this.vtable_in_use = 0;
this.isNested = false;
this.object_start = 0;
this.vtables = [];
this.vector_num_elems = 0;
this.force_defaults = false;
this.string_maps = null;
}
/**
* In order to save space, fields that are set to their default value
* don't get serialized into the buffer. Forcing defaults provides a
* way to manually disable this optimization.
*
* @param forceDefaults true always serializes default values
*/
forceDefaults(forceDefaults) {
this.force_defaults = forceDefaults;
}
/**
* Get the ByteBuffer representing the FlatBuffer. Only call this after you've
* called finish(). The actual data starts at the ByteBuffer's current position,
* not necessarily at 0.
*/
dataBuffer() {
return this.bb;
}
/**
* Get the bytes representing the FlatBuffer. Only call this after you've
* called finish().
*/
asUint8Array() {
return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset());
}
/**
* Prepare to write an element of `size` after `additional_bytes` have been
* written, e.g. if you write a string, you need to align such the int length
* field is aligned to 4 bytes, and the string data follows it directly. If all
* you need to do is alignment, `additional_bytes` will be 0.
*
* @param size This is the of the new element to write
* @param additional_bytes The padding size
*/
prep(size, additional_bytes) {
if (size > this.minalign) {
this.minalign = size;
}
const align_size = ~(this.bb.capacity() - this.space + additional_bytes) + 1 & size - 1;
while (this.space < align_size + size + additional_bytes) {
const old_buf_size = this.bb.capacity();
this.bb = _Builder.growByteBuffer(this.bb);
this.space += this.bb.capacity() - old_buf_size;
}
this.pad(align_size);
}
pad(byte_size) {
for (let i = 0; i < byte_size; i++) {
this.bb.writeInt8(--this.space, 0);
}
}
writeInt8(value) {
this.bb.writeInt8(this.space -= 1, value);
}
writeInt16(value) {
this.bb.writeInt16(this.space -= 2, value);
}
writeInt32(value) {
this.bb.writeInt32(this.space -= 4, value);
}
writeInt64(value) {
this.bb.writeInt64(this.space -= 8, value);
}
writeFloat32(value) {
this.bb.writeFloat32(this.space -= 4, value);
}
writeFloat64(value) {
this.bb.writeFloat64(this.space -= 8, value);
}
/**
* Add an `int8` to the buffer, properly aligned, and grows the buffer (if necessary).
* @param value The `int8` to add the buffer.
*/
addInt8(value) {
this.prep(1, 0);
this.writeInt8(value);
}
/**
* Add an `int16` to the buffer, properly aligned, and grows the buffer (if necessary).
* @param value The `int16` to add the buffer.
*/
addInt16(value) {
this.prep(2, 0);
this.writeInt16(value);
}
/**
* Add an `int32` to the buffer, properly aligned, and grows the buffer (if necessary).
* @param value The `int32` to add the buffer.
*/
addInt32(value) {
this.prep(4, 0);
this.writeInt32(value);
}
/**
* Add an `int64` to the buffer, properly aligned, and grows the buffer (if necessary).
* @param value The `int64` to add the buffer.
*/
addInt64(value) {
this.prep(8, 0);
this.writeInt64(value);
}
/**
* Add a `float32` to the buffer, properly aligned, and grows the buffer (if necessary).
* @param value The `float32` to add the buffer.
*/
addFloat32(value) {
this.prep(4, 0);
this.writeFloat32(value);
}
/**
* Add a `float64` to the buffer, properly aligned, and grows the buffer (if necessary).
* @param value The `float64` to add the buffer.
*/
addFloat64(value) {
this.prep(8, 0);
this.writeFloat64(value);
}
addFieldInt8(voffset, value, defaultValue) {
if (this.force_defaults || value != defaultValue) {
this.addInt8(value);
this.slot(voffset);
}
}
addFieldInt16(voffset, value, defaultValue) {
if (this.force_defaults || value != defaultValue) {
this.addInt16(value);
this.slot(voffset);
}
}
addFieldInt32(voffset, value, defaultValue) {
if (this.force_defaults || value != defaultValue) {
this.addInt32(value);
this.slot(voffset);
}
}
addFieldInt64(voffset, value, defaultValue) {
if (this.force_defaults || value !== defaultValue) {
this.addInt64(value);
this.slot(voffset);
}
}
addFieldFloat32(voffset, value, defaultValue) {
if (this.force_defaults || value != defaultValue) {
this.addFloat32(value);
this.slot(voffset);
}
}
addFieldFloat64(voffset, value, defaultValue) {
if (this.force_defaults || value != defaultValue) {
this.addFloat64(value);
this.slot(voffset);
}
}
addFieldOffset(voffset, value, defaultValue) {
if (this.force_defaults || value != defaultValue) {
this.addOffset(value);
this.slot(voffset);
}
}
/**
* Structs are stored inline, so nothing additional is being added. `d` is always 0.
*/
addFieldStruct(voffset, value, defaultValue) {
if (value != defaultValue) {
this.nested(value);
this.slot(voffset);
}
}
/**
* Structures are always stored inline, they need to be created right
* where they're used. You'll get this assertion failure if you
* created it elsewhere.
*/
nested(obj) {
if (obj != this.offset()) {
throw new TypeError("FlatBuffers: struct must be serialized inline.");
}
}
/**
* Should not be creating any other object, string or vector
* while an object is being constructed
*/
notNested() {
if (this.isNested) {
throw new TypeError("FlatBuffers: object serialization must not be nested.");
}
}
/**
* Set the current vtable at `voffset` to the current location in the buffer.
*/
slot(voffset) {
if (this.vtable !== null)
this.vtable[voffset] = this.offset();
}
/**
* @returns Offset relative to the end of the buffer.
*/
offset() {
return this.bb.capacity() - this.space;
}
/**
* Doubles the size of the backing ByteBuffer and copies the old data towards
* the end of the new buffer (since we build the buffer backwards).
*
* @param bb The current buffer with the existing data
* @returns A new byte buffer with the old data copied
* to it. The data is located at the end of the buffer.
*
* uint8Array.set() formally takes {Array<number>|ArrayBufferView}, so to pass
* it a uint8Array we need to suppress the type check:
* @suppress {checkTypes}
*/
static growByteBuffer(bb) {
const old_buf_size = bb.capacity();
if (old_buf_size & 3221225472) {
throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");
}
const new_buf_size = old_buf_size << 1;
const nbb = byte_buffer_js_1.ByteBuffer.allocate(new_buf_size);
nbb.setPosition(new_buf_size - old_buf_size);
nbb.bytes().set(bb.bytes(), new_buf_size - old_buf_size);
return nbb;
}
/**
* Adds on offset, relative to where it will be written.
*
* @param offset The offset to add.
*/
addOffset(offset) {
this.prep(constants_js_1.SIZEOF_INT, 0);
this.writeInt32(this.offset() - offset + constants_js_1.SIZEOF_INT);
}
/**
* Start encoding a new object in the buffer. Users will not usually need to
* call this directly. The FlatBuffers compiler will generate helper methods
* that call this method internally.
*/
startObject(numfields) {
this.notNested();
if (this.vtable == null) {
this.vtable = [];
}
this.vtable_in_use = numfields;
for (let i = 0; i < numfields; i++) {
this.vtable[i] = 0;
}
this.isNested = true;
this.object_start = this.offset();
}
/**
* Finish off writing the object that is under construction.
*
* @returns The offset to the object inside `dataBuffer`
*/
endObject() {
if (this.vtable == null || !this.isNested) {
throw new Error("FlatBuffers: endObject called without startObject");
}
this.addInt32(0);
const vtableloc = this.offset();
let i = this.vtable_in_use - 1;
for (; i >= 0 && this.vtable[i] == 0; i--) {
}
const trimmed_size = i + 1;
for (; i >= 0; i--) {
this.addInt16(this.vtable[i] != 0 ? vtableloc - this.vtable[i] : 0);
}
const standard_fields = 2;
this.addInt16(vtableloc - this.object_start);
const len = (trimmed_size + standard_fields) * constants_js_1.SIZEOF_SHORT;
this.addInt16(len);
let existing_vtable = 0;
const vt1 = this.space;
outer_loop: for (i = 0; i < this.vtables.length; i++) {
const vt2 = this.bb.capacity() - this.vtables[i];
if (len == this.bb.readInt16(vt2)) {
for (let j = constants_js_1.SIZEOF_SHORT; j < len; j += constants_js_1.SIZEOF_SHORT) {
if (this.bb.readInt16(vt1 + j) != this.bb.readInt16(vt2 + j)) {
continue outer_loop;
}
}
existing_vtable = this.vtables[i];
break;
}
}
if (existing_vtable) {
this.space = this.bb.capacity() - vtableloc;
this.bb.writeInt32(this.space, existing_vtable - vtableloc);
} else {
this.vtables.push(this.offset());
this.bb.writeInt32(this.bb.capacity() - vtableloc, this.offset() - vtableloc);
}
this.isNested = false;
return vtableloc;
}
/**
* Finalize a buffer, poiting to the given `root_table`.
*/
finish(root_table, opt_file_identifier, opt_size_prefix) {
const size_prefix = opt_size_prefix ? constants_js_1.SIZE_PREFIX_LENGTH : 0;
if (opt_file_identifier) {
const file_identifier = opt_file_identifier;
this.prep(this.minalign, constants_js_1.SIZEOF_INT + constants_js_1.FILE_IDENTIFIER_LENGTH + size_prefix);
if (file_identifier.length != constants_js_1.FILE_IDENTIFIER_LENGTH) {
throw new TypeError("FlatBuffers: file identifier must be length " + constants_js_1.FILE_IDENTIFIER_LENGTH);
}
for (let i = constants_js_1.FILE_IDENTIFIER_LENGTH - 1; i >= 0; i--) {
this.writeInt8(file_identifier.charCodeAt(i));
}
}
this.prep(this.minalign, constants_js_1.SIZEOF_INT + size_prefix);
this.addOffset(root_table);
if (size_prefix) {
this.addInt32(this.bb.capacity() - this.space);
}
this.bb.setPosition(this.space);
}
/**
* Finalize a size prefixed buffer, pointing to the given `root_table`.
*/
finishSizePrefixed(root_table, opt_file_identifier) {
this.finish(root_table, opt_file_identifier, true);
}
/**
* This checks a required field has been set in a given table that has
* just been constructed.
*/
requiredField(table, field) {
const table_start = this.bb.capacity() - table;
const vtable_start = table_start - this.bb.readInt32(table_start);
const ok = field < this.bb.readInt16(vtable_start) && this.bb.readInt16(vtable_start + field) != 0;
if (!ok) {
throw new TypeError("FlatBuffers: field " + field + " must be set");
}
}
/**
* Start a new array/vector of objects. Users usually will not call
* this directly. The FlatBuffers compiler will create a start/end
* method for vector types in generated code.
*
* @param elem_size The size of each element in the array
* @param num_elems The number of elements in the array
* @param alignment The alignment of the array
*/
startVector(elem_size, num_elems, alignment) {
this.notNested();
this.vector_num_elems = num_elems;
this.prep(constants_js_1.SIZEOF_INT, elem_size * num_elems);
this.prep(alignment, elem_size * num_elems);
}
/**
* Finish off the creation of an array and all its elements. The array must be
* created with `startVector`.
*
* @returns The offset at which the newly created array
* starts.
*/
endVector() {
this.writeInt32(this.vector_num_elems);
return this.offset();
}
/**
* Encode the string `s` in the buffer using UTF-8. If the string passed has
* already been seen, we return the offset of the already written string
*
* @param s The string to encode
* @return The offset in the buffer where the encoded string starts
*/
createSharedString(s) {
if (!s) {
return 0;
}
if (!this.string_maps) {
this.string_maps = /* @__PURE__ */ new Map();
}
if (this.string_maps.has(s)) {
return this.string_maps.get(s);
}
const offset = this.createString(s);
this.string_maps.set(s, offset);
return offset;
}
/**
* Encode the string `s` in the buffer using UTF-8. If a Uint8Array is passed
* instead of a string, it is assumed to contain valid UTF-8 encoded data.
*
* @param s The string to encode
* @return The offset in the buffer where the encoded string starts
*/
createString(s) {
if (s === null || s === void 0) {
return 0;
}
let utf8;
if (s instanceof Uint8Array) {
utf8 = s;
} else {
utf8 = this.text_encoder.encode(s);
}
this.addInt8(0);
this.startVector(1, utf8.length, 1);
this.bb.setPosition(this.space -= utf8.length);
this.bb.bytes().set(utf8, this.space);
return this.endVector();
}
/**
* Create a byte vector.
*
* @param v The bytes to add
* @returns The offset in the buffer where the byte vector starts
*/
createByteVector(v) {
if (v === null || v === void 0) {
return 0;
}
this.startVector(1, v.length, 1);
this.bb.setPosition(this.space -= v.length);
this.bb.bytes().set(v, this.space);
return this.endVector();
}
/**
* A helper function to pack an object
*
* @returns offset of obj
*/
createObjectOffset(obj) {
if (obj === null) {
return 0;
}
if (typeof obj === "string") {
return this.createString(obj);
} else {
return obj.pack(this);
}
}
/**
* A helper function to pack a list of object
*
* @returns list of offsets of each non null object
*/
createObjectOffsetList(list) {
const ret = [];
for (let i = 0; i < list.length; ++i) {
const val = list[i];
if (val !== null) {
ret.push(this.createObjectOffset(val));
} else {
throw new TypeError("FlatBuffers: Argument for createObjectOffsetList cannot contain null.");
}
}
return ret;
}
createStructOffsetList(list, startFunc) {
startFunc(this, list.length);
this.createObjectOffsetList(list.slice().reverse());
return this.endVector();
}
};
exports.Builder = Builder2;
}
});
// node_modules/flatbuffers/js/flatbuffers.js
var require_flatbuffers = __commonJS({
"node_modules/flatbuffers/js/flatbuffers.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Encoding = exports.ByteBuffer = exports.Builder = exports.isLittleEndian = exports.int32 = exports.float64 = exports.float32 = exports.SIZE_PREFIX_LENGTH = exports.SIZEOF_SHORT = exports.SIZEOF_INT = exports.FILE_IDENTIFIER_LENGTH = void 0;
var constants_js_1 = require_constants();
Object.defineProperty(exports, "FILE_IDENTIFIER_LENGTH", { enumerable: true, get: function() {
return constants_js_1.FILE_IDENTIFIER_LENGTH;
} });
Object.defineProperty(exports, "SIZEOF_INT", { enumerable: true, get: function() {
return constants_js_1.SIZEOF_INT;
} });
Object.defineProperty(exports, "SIZEOF_SHORT", { enumerable: true, get: function() {
return constants_js_1.SIZEOF_SHORT;
} });
Object.defineProperty(exports, "SIZE_PREFIX_LENGTH", { enumerable: true, get: function() {
return constants_js_1.SIZE_PREFIX_LENGTH;
} });
var utils_js_1 = require_utils();
Object.defineProperty(exports, "float32", { enumerable: true, get: function() {
return utils_js_1.float32;
} });
Object.defineProperty(exports, "float64", { enumerable: true, get: function() {
return utils_js_1.float64;
} });
Object.defineProperty(exports, "int32", { enumerable: true, get: function() {
return utils_js_1.int32;
} });
Object.defineProperty(exports, "isLittleEndian", { enumerable: true, get: function() {
return utils_js_1.isLittleEndian;
} });
var builder_js_1 = require_builder();
Object.defineProperty(exports, "Builder", { enumerable: true, get: function() {
return builder_js_1.Builder;
} });
var byte_buffer_js_1 = require_byte_buffer();
Object.defineProperty(exports, "ByteBuffer", { enumerable: true, get: function() {
return byte_buffer_js_1.ByteBuffer;
} });
var encoding_js_1 = require_encoding();
Object.defineProperty(exports, "Encoding", { enumerable: true, get: function() {
return encoding_js_1.Encoding;
} });
}
});
// node_modules/exifr/dist/full.umd.js
var require_full_umd = __commonJS({
"node_modules/exifr/dist/full.umd.js"(exports, module) {
!(function(e, t) {
"object" == typeof exports && "undefined" != typeof module ? t(exports) : "function" == typeof define && define.amd ? define("exifr", ["exports"], t) : t((e = "undefined" != typeof globalThis ? globalThis : e || self).exifr = {});
})(exports, (function(e) {
"use strict";
var t = "undefined" != typeof self ? self : global;
const i = "undefined" != typeof navigator, n = i && "undefined" == typeof HTMLImageElement, s = !("undefined" == typeof global || "undefined" == typeof process || !process.versions || !process.versions.node), r = t.Buffer, a = t.BigInt, o = !!r, l = (e2) => e2;
function h(e2, t2 = l) {
if (s) try {
return "function" == typeof __require ? Promise.resolve(t2(__require(e2))) : import(
/* webpackIgnore: true */
e2
).then(t2);
} catch (t3) {
console.warn(`Couldn't load ${e2}`);
}
}
let u = t.fetch;
const c = (e2) => u = e2;
if (!t.fetch) {
const e2 = h("http", ((e3) => e3)), t2 = h("https", ((e3) => e3)), i2 = (n2, { headers: s2 } = {}) => new Promise((async (r2, a2) => {
let { port: o2, hostname: l2, pathname: h2, protocol: u2, search: c2 } = new URL(n2);
const f2 = { method: "GET", hostname: l2, path: encodeURI(h2) + c2, headers: s2 };
"" !== o2 && (f2.port = Number(o2));
const d2 = ("https:" === u2 ? await t2 : await e2).request(f2, ((e3) => {
if (301 === e3.statusCode || 302 === e3.statusCode) {
let t3 = new URL(e3.headers.location, n2).toString();
return i2(t3, { headers: s2 }).then(r2).catch(a2);
}
r2({ status: e3.statusCode, arrayBuffer: () => new Promise(((t3) => {
let i3 = [];
e3.on("data", ((e4) => i3.push(e4))), e3.on("end", (() => t3(Buffer.concat(i3))));
})) });
}));
d2.on("error", a2), d2.end();
}));
c(i2);
}
function f(e2, t2, i2) {
return t2 in e2 ? Object.defineProperty(e2, t2, { value: i2, enumerable: true, configurable: true, writable: true }) : e2[t2] = i2, e2;
}
const d = (e2) => g(e2) ? void 0 : e2, p = (e2) => void 0 !== e2;
function g(e2) {
return void 0 === e2 || (e2 instanceof Map ? 0 === e2.size : 0 === Object.values(e2).filter(p).length);
}
function m(e2) {
let t2 = new Error(e2);
throw delete t2.stack, t2;
}
function S(e2) {
return "" === (e2 = (function(e3) {
for (; e3.endsWith("\0"); ) e3 = e3.slice(0, -1);
return e3;
})(e2).trim()) ? void 0 : e2;
}
function C(e2) {
let t2 = (function(e3) {
let t3 = 0;
return e3.ifd0.enabled && (t3 += 1024), e3.exif.enabled && (t3 += 2048), e3.makerNote && (t3 += 2048), e3.userComment && (t3 += 1024), e3.gps.enabled && (t3 += 512), e3.interop.enabled && (t3 += 100), e3.ifd1.enabled && (t3 += 1024), t3 + 2048;
})(e2);
return e2.jfif.enabled && (t2 += 50), e2.xmp.enabled && (t2 += 2e4), e2.iptc.enabled && (t2 += 14e3), e2.icc.enabled && (t2 += 6e3), t2;
}
const y = (e2) => String.fromCharCode.apply(null, e2), b = "undefined" != typeof TextDecoder ? new TextDecoder("utf-8") : void 0;
function P(e2) {
return b ? b.decode(e2) : o ? Buffer.from(e2).toString("utf8") : decodeURIComponent(escape(y(e2)));
}
class I {
static from(e2, t2) {
return e2 instanceof this && e2.le === t2 ? e2 : new I(e2, void 0, void 0, t2);
}
constructor(e2, t2 = 0, i2, n2) {
if ("boolean" == typeof n2 && (this.le = n2), Array.isArray(e2) && (e2 = new Uint8Array(e2)), 0 === e2) this.byteOffset = 0, this.byteLength = 0;
else if (e2 instanceof ArrayBuffer) {
void 0 === i2 && (i2 = e2.byteLength - t2);
let n3 = new DataView(e2, t2, i2);
this._swapDataView(n3);
} else if (e2 instanceof Uint8Array || e2 instanceof DataView || e2 instanceof I) {
void 0 === i2 && (i2 = e2.byteLength - t2), (t2 += e2.byteOffset) + i2 > e2.byteOffset + e2.byteLength && m("Creating view outside of available memory in ArrayBuffer");
let n3 = new DataView(e2.buffer, t2, i2);
this._swapDataView(n3);
} else if ("number" == typeof e2) {
let t3 = new DataView(new ArrayBuffer(e2));
this._swapDataView(t3);
} else m("Invalid input argument for BufferView: " + e2);
}
_swapArrayBuffer(e2) {
this._swapDataView(new DataView(e2));
}
_swapBuffer(e2) {
this._swapDataView(new DataView(e2.buffer, e2.byteOffset, e2.byteLength));
}
_swapDataView(e2) {
this.dataView = e2, this.buffer = e2.buffer, this.byteOffset = e2.byteOffset, this.byteLength = e2.byteLength;
}
_lengthToEnd(e2) {
return this.byteLength - e2;
}
set(e2, t2, i2 = I) {
return e2 instanceof DataView || e2 instanceof I ? e2 = new Uint8Array(e2.buffer, e2.byteOffset, e2.byteLength) : e2 instanceof ArrayBuffer && (e2 = new Uint8Array(e2)), e2 instanceof Uint8Array || m("BufferView.set(): Invalid data argument."), this.toUint8().set(e2, t2), new i2(this, t2, e2.byteLength);
}
subarray(e2, t2) {
return t2 = t2 || this._lengthToEnd(e2), new I(this, e2, t2);
}
toUint8() {
return new Uint8Array(this.buffer, this.byteOffset, this.byteLength);
}
getUint8Array(e2, t2) {
return new Uint8Array(this.buffer, this.byteOffset + e2, t2);
}
getString(e2 = 0, t2 = this.byteLength) {
return P(this.getUint8Array(e2, t2));
}
getLatin1String(e2 = 0, t2 = this.byteLength) {
let i2 = this.getUint8Array(e2, t2);
return y(i2);
}
getUnicodeString(e2 = 0, t2 = this.byteLength) {
const i2 = [];
for (let n2 = 0; n2 < t2 && e2 + n2 < this.byteLength; n2 += 2) i2.push(this.getUint16(e2 + n2));
return y(i2);
}
getInt8(e2) {
return this.dataView.getInt8(e2);
}
getUint8(e2) {
return this.dataView.getUint8(e2);
}
getInt16(e2, t2 = this.le) {
return this.dataView.getInt16(e2, t2);
}
getInt32(e2, t2 = this.le) {
return this.dataView.getInt32(e2, t2);
}
getUint16(e2, t2 = this.le) {
return this.dataView.getUint16(e2, t2);
}
getUint32(e2, t2 = this.le) {
return this.dataView.getUint32(e2, t2);
}
getFloat32(e2, t2 = this.le) {
return this.dataView.getFloat32(e2, t2);
}
getFloat64(e2, t2 = this.le) {
return this.dataView.getFloat64(e2, t2);
}
getFloat(e2, t2 = this.le) {
return this.dataView.getFloat32(e2, t2);
}
getDouble(e2, t2 = this.le) {
return this.dataView.getFloat64(e2, t2);
}
getUintBytes(e2, t2, i2) {
switch (t2) {
case 1:
return this.getUint8(e2, i2);
case 2:
return this.getUint16(e2, i2);
case 4:
return this.getUint32(e2, i2);
case 8:
return this.getUint64 && this.getUint64(e2, i2);
}
}
getUint(e2, t2, i2) {
switch (t2) {
case 8:
return this.getUint8(e2, i2);
case 16:
return this.getUint16(e2, i2);
case 32:
return this.getUint32(e2, i2);
case 64:
return this.getUint64 && this.getUint64(e2, i2);
}
}
toString(e2) {
return this.dataView.toString(e2, this.constructor.name);
}
ensureChunk() {
}
}
function k(e2, t2) {
m(`${e2} '${t2}' was not loaded, try using full build of exifr.`);
}
class w extends Map {
constructor(e2) {
super(), this.kind = e2;
}
get(e2, t2) {
return this.has(e2) || k(this.kind, e2), t2 && (e2 in t2 || (function(e3, t3) {
m(`Unknown ${e3} '${t3}'.`);
})(this.kind, e2), t2[e2].enabled || k(this.kind, e2)), super.get(e2);
}
keyList() {
return Array.from(this.keys());
}
}
var T = new w("file parser"), A = new w("segment parser"), D = new w("file reader");
const O = "Invalid input argument";
function x(e2, t2) {
return "string" == typeof e2 ? v(e2, t2) : i && !n && e2 instanceof HTMLImageElement ? v(e2.src, t2) : e2 instanceof Uint8Array || e2 instanceof ArrayBuffer || e2 instanceof DataView ? new I(e2) : i && e2 instanceof Blob ? M(e2, t2, "blob", U) : void m(O);
}
function v(e2, t2) {
return (n2 = e2).startsWith("data:") || n2.length > 1e4 ? R(e2, t2, "base64") : s && e2.includes("://") ? M(e2, t2, "url", L) : s ? R(e2, t2, "fs") : i ? M(e2, t2, "url", L) : void m(O);
var n2;
}
async function M(e2, t2, i2, n2) {
return D.has(i2) ? R(e2, t2, i2) : n2 ? (async function(e3, t3) {
let i3 = await t3(e3);
return new I(i3);
})(e2, n2) : void m(`Parser ${i2} is not loaded`);
}
async function R(e2, t2, i2) {
let n2 = new (D.get(i2))(e2, t2);
return await n2.read(), n2;
}
const L = (e2) => u(e2).then(((e3) => e3.arrayBuffer())), U = (e2) => new Promise(((t2, i2) => {
let n2 = new FileReader();
n2.onloadend = () => t2(n2.result || new ArrayBuffer()), n2.onerror = i2, n2.readAsArrayBuffer(e2);
}));
class F extends Map {
get tagKeys() {
return this.allKeys || (this.allKeys = Array.from(this.keys())), this.allKeys;
}
get tagValues() {
return this.allValues || (this.allValues = Array.from(this.values())), this.allValues;
}
}
function B(e2, t2, i2) {
let n2 = new F();
for (let [e3, t3] of i2) n2.set(e3, t3);
if (Array.isArray(t2)) for (let i3 of t2) e2.set(i3, n2);
else e2.set(t2, n2);
return n2;
}
function E(e2, t2, i2) {
let n2, s2 = e2.get(t2);
for (n2 of i2) s2.set(n2[0], n2[1]);
}
const N = /* @__PURE__ */ new Map(), G = /* @__PURE__ */ new Map(), V = /* @__PURE__ */ new Map(), z4 = 37500, H = 37510, j = 700, W = 33723, K = 34675, X = 34665, _ = 34853, Y = 40965, $ = ["chunked", "firstChunkSize", "firstChunkSizeNode", "firstChunkSizeBrowser", "chunkSize", "chunkLimit"], J = ["jfif", "xmp", "icc", "iptc", "ihdr"], q = ["tiff", ...J], Q = ["ifd0", "ifd1", "exif", "gps", "interop"], Z = [...q, ...Q], ee = ["makerNote", "userComment"], te = ["translateKeys", "translateValues", "reviveValues", "multiSegment"], ie = [...te, "sanitize", "mergeOutput", "silentErrors"];
class ne {
get translate() {
return this.translateKeys || this.translateValues || this.reviveValues;
}
}
class se extends ne {
get needed() {
return this.enabled || this.deps.size > 0;
}
constructor(e2, t2, i2, n2) {
if (super(), f(this, "enabled", false), f(this, "skip", /* @__PURE__ */ new Set()), f(this, "pick", /* @__PURE__ */ new Set()), f(this, "deps", /* @__PURE__ */ new Set()), f(this, "translateKeys", false), f(this, "translateValues", false), f(this, "reviveValues", false), this.key = e2, this.enabled = t2, this.parse = this.enabled, this.applyInheritables(n2), this.canBeFiltered = Q.includes(e2), this.canBeFiltered && (this.dict = N.get(e2)), void 0 !== i2) if (Array.isArray(i2)) this.parse = this.enabled = true, this.canBeFiltered && i2.length > 0 && this.translateTagSet(i2, this.pick);
else if ("object" == typeof i2) {
if (this.enabled = true, this.parse = false !== i2.parse, this.canBeFiltered) {
let { pick: e3, skip: t3 } = i2;
e3 && e3.length > 0 && this.translateTagSet(e3, this.pick), t3 && t3.length > 0 && this.translateTagSet(t3, this.skip);
}
this.applyInheritables(i2);
} else true === i2 || false === i2 ? this.parse = this.enabled = i2 : m(`Invalid options argument: ${i2}`);
}
applyInheritables(e2) {
let t2, i2;
for (t2 of te) i2 = e2[t2], void 0 !== i2 && (this[t2] = i2);
}
translateTagSet(e2, t2) {
if (this.dict) {
let i2, n2, { tagKeys: s2, tagValues: r2 } = this.dict;
for (i2 of e2) "string" == typeof i2 ? (n2 = r2.indexOf(i2), -1 === n2 && (n2 = s2.indexOf(Number(i2))), -1 !== n2 && t2.add(Number(s2[n2]))) : t2.add(i2);
} else for (let i2 of e2) t2.add(i2);
}
finalizeFilters() {
!this.enabled && this.deps.size > 0 ? (this.enabled = true, ue(this.pick, this.deps)) : this.enabled && this.pick.size > 0 && ue(this.pick, this.deps);
}
}
var re = { jfif: false, tiff: true, xmp: false, icc: false, iptc: false, ifd0: true, ifd1: false, exif: true, gps: true, interop: false, ihdr: void 0, makerNote: false, userComment: false, multiSegment: false, skip: [], pick: [], translateKeys: true, translateValues: true, reviveValues: true, sanitize: true, mergeOutput: true, silentErrors: true, chunked: true, firstChunkSize: void 0, firstChunkSizeNode: 512, firstChunkSizeBrowser: 65536, chunkSize: 65536, chunkLimit: 5 }, ae = /* @__PURE__ */ new Map();
class oe extends ne {
static useCached(e2) {
let t2 = ae.get(e2);
return void 0 !== t2 || (t2 = new this(e2), ae.set(e2, t2)), t2;
}
constructor(e2) {
super(), true === e2 ? this.setupFromTrue() : void 0 === e2 ? this.setupFromUndefined() : Array.isArray(e2) ? this.setupFromArray(e2) : "object" == typeof e2 ? this.setupFromObject(e2) : m(`Invalid options argument ${e2}`), void 0 === this.firstChunkSize && (this.firstChunkSize = i ? this.firstChunkSizeBrowser : this.firstChunkSizeNode), this.mergeOutput && (this.ifd1.enabled = false), this.filterNestedSegmentTags(), this.traverseTiffDependencyTree(), this.checkLoadedPlugins();
}
setupFromUndefined() {
let e2;
for (e2 of $) this[e2] = re[e2];
for (e2 of ie) this[e2] = re[e2];
for (e2 of ee) this[e2] = re[e2];
for (e2 of Z) this[e2] = new se(e2, re[e2], void 0, this);
}
setupFromTrue() {
let e2;
for (e2 of $) this[e2] = re[e2];
for (e2 of ie) this[e2] = re[e2];
for (e2 of ee) this[e2] = true;
for (e2 of Z) this[e2] = new se(e2, true, void 0, this);
}
setupFromArray(e2) {
let t2;
for (t2 of $) this[t2] = re[t2];
for (t2 of ie) this[t2] = re[t2];
for (t2 of ee) this[t2] = re[t2];
for (t2 of Z) this[t2] = new se(t2, false, void 0, this);
this.setupGlobalFilters(e2, void 0, Q);
}
setupFromObject(e2) {
let t2;
for (t2 of (Q.ifd0 = Q.ifd0 || Q.image, Q.ifd1 = Q.ifd1 || Q.thumbnail, Object.assign(this, e2), $)) this[t2] = he(e2[t2], re[t2]);
for (t2 of ie) this[t2] = he(e2[t2], re[t2]);
for (t2 of ee) this[t2] = he(e2[t2], re[t2]);
for (t2 of q) this[t2] = new se(t2, re[t2], e2[t2], this);
for (t2 of Q) this[t2] = new se(t2, re[t2], e2[t2], this.tiff);
this.setupGlobalFilters(e2.pick, e2.skip, Q, Z), true === e2.tiff ? this.batchEnableWithBool(Q, true) : false === e2.tiff ? this.batchEnableWithUserValue(Q, e2) : Array.isArray(e2.tiff) ? this.setupGlobalFilters(e2.tiff, void 0, Q) : "object" == typeof e2.tiff && this.setupGlobalFilters(e2.tiff.pick, e2.tiff.skip, Q);
}
batchEnableWithBool(e2, t2) {
for (let i2 of e2) this[i2].enabled = t2;
}
batchEnableWithUserValue(e2, t2) {
for (let i2 of e2) {
let e3 = t2[i2];
this[i2].enabled = false !== e3 && void 0 !== e3;
}
}
setupGlobalFilters(e2, t2, i2, n2 = i2) {
if (e2 && e2.length) {
for (let e3 of n2) this[e3].enabled = false;
let t3 = le(e2, i2);
for (let [e3, i3] of t3) ue(this[e3].pick, i3), this[e3].enabled = true;
} else if (t2 && t2.length) {
let e3 = le(t2, i2);
for (let [t3, i3] of e3) ue(this[t3].skip, i3);
}
}
filterNestedSegmentTags() {
let { ifd0: e2, exif: t2, xmp: i2, iptc: n2, icc: s2 } = this;
this.makerNote ? t2.deps.add(z4) : t2.skip.add(z4), this.userComment ? t2.deps.add(H) : t2.skip.add(H), i2.enabled || e2.skip.add(j), n2.enabled || e2.skip.add(W), s2.enabled || e2.skip.add(K);
}
traverseTiffDependencyTree() {
let { ifd0: e2, exif: t2, gps: i2, interop: n2 } = this;
n2.needed && (t2.deps.add(Y), e2.deps.add(Y)), t2.needed && e2.deps.add(X), i2.needed && e2.deps.add(_), this.tiff.enabled = Q.some(((e3) => true === this[e3].enabled)) || this.makerNote || this.userComment;
for (let e3 of Q) this[e3].finalizeFilters();
}
get onlyTiff() {
return !J.map(((e2) => this[e2].enabled)).some(((e2) => true === e2)) && this.tiff.enabled;
}
checkLoadedPlugins() {
for (let e2 of q) this[e2].enabled && !A.has(e2) && k("segment parser", e2);
}
}
function le(e2, t2) {
let i2, n2, s2, r2, a2 = [];
for (s2 of t2) {
for (r2 of (i2 = N.get(s2), n2 = [], i2)) (e2.includes(r2[0]) || e2.includes(r2[1])) && n2.push(r2[0]);
n2.length && a2.push([s2, n2]);
}
return a2;
}
function he(e2, t2) {
return void 0 !== e2 ? e2 : void 0 !== t2 ? t2 : void 0;
}
function ue(e2, t2) {
for (let i2 of t2) e2.add(i2);
}
f(oe, "default", re);
class ce {
constructor(e2) {
f(this, "parsers", {}), f(this, "output", {}), f(this, "errors", []), f(this, "pushToErrors", ((e3) => this.errors.push(e3))), this.options = oe.useCached(e2);
}
async read(e2) {
this.file = await x(e2, this.options);
}
setup() {
if (this.fileParser) return;
let { file: e2 } = this, t2 = e2.getUint16(0);
for (let [i2, n2] of T) if (n2.canHandle(e2, t2)) return this.fileParser = new n2(this.options, this.file, this.parsers), e2[i2] = true;
this.file.close && this.file.close(), m("Unknown file format");
}
async parse() {
let { output: e2, errors: t2 } = this;
return this.setup(), this.options.silentErrors ? (await this.executeParsers().catch(this.pushToErrors), t2.push(...this.fileParser.errors)) : await this.executeParsers(), this.file.close && this.file.close(), this.options.silentErrors && t2.length > 0 && (e2.errors = t2), d(e2);
}
async executeParsers() {
let { output: e2 } = this;
await this.fileParser.parse();
let t2 = Object.values(this.parsers).map((async (t3) => {
let i2 = await t3.parse();
t3.assignToOutput(e2, i2);
}));
this.options.silentErrors && (t2 = t2.map(((e3) => e3.catch(this.pushToErrors)))), await Promise.all(t2);
}
async extractThumbnail() {
this.setup();
let { options: e2, file: t2 } = this, i2 = A.get("tiff", e2);
var n2;
if (t2.tiff ? n2 = { start: 0, type: "tiff" } : t2.jpeg && (n2 = await this.fileParser.getOrFindSegment("tiff")), void 0 === n2) return;
let s2 = await this.fileParser.ensureSegmentChunk(n2), r2 = this.parsers.tiff = new i2(s2, e2, t2), a2 = await r2.extractThumbnail();
return t2.close && t2.close(), a2;
}
}
async function fe(e2, t2) {
let i2 = new ce(t2);
return await i2.read(e2), i2.parse();
}
var de = Object.freeze({ __proto__: null, parse: fe, Exifr: ce, fileParsers: T, segmentParsers: A, fileReaders: D, tagKeys: N, tagValues: G, tagRevivers: V, createDictionary: B, extendDictionary: E, fetchUrlAsArrayBuffer: L, readBlobAsArrayBuffer: U, chunkedProps: $, otherSegments: J, segments: q, tiffBlocks: Q, segmentsAndBlocks: Z, tiffExtractables: ee, inheritables: te, allFormatters: ie, Options: oe });
class pe {
constructor(e2, t2, i2) {
f(this, "errors", []), f(this, "ensureSegmentChunk", (async (e3) => {
let t3 = e3.start, i3 = e3.size || 65536;
if (this.file.chunked) if (this.file.available(t3, i3)) e3.chunk = this.file.subarray(t3, i3);
else try {
e3.chunk = await this.file.readChunk(t3, i3);
} catch (t4) {
m(`Couldn't read segment: ${JSON.stringify(e3)}. ${t4.message}`);
}
else this.file.byteLength > t3 + i3 ? e3.chunk = this.file.subarray(t3, i3) : void 0 === e3.size ? e3.chunk = this.file.subarray(t3) : m("Segment unreachable: " + JSON.stringify(e3));
return e3.chunk;
})), this.extendOptions && this.extendOptions(e2), this.options = e2, this.file = t2, this.parsers = i2;
}
injectSegment(e2, t2) {
this.options[e2].enabled && this.createParser(e2, t2);
}
createParser(e2, t2) {
let i2 = new (A.get(e2))(t2, this.options, this.file);
return this.parsers[e2] = i2;
}
createParsers(e2) {
for (let t2 of e2) {
let { type: e3, chunk: i2 } = t2, n2 = this.options[e3];
if (n2 && n2.enabled) {
let t3 = this.parsers[e3];
t3 && t3.append || t3 || this.createParser(e3, i2);
}
}
}
async readSegments(e2) {
let t2 = e2.map(this.ensureSegmentChunk);
await Promise.all(t2);
}
}
class ge {
static findPosition(e2, t2) {
let i2 = e2.getUint16(t2 + 2) + 2, n2 = "function" == typeof this.headerLength ? this.headerLength(e2, t2, i2) : this.headerLength, s2 = t2 + n2, r2 = i2 - n2;
return { offset: t2, length: i2, headerLength: n2, start: s2, size: r2, end: s2 + r2 };
}
static parse(e2, t2 = {}) {
return new this(e2, new oe({ [this.type]: t2 }), e2).parse();
}
normalizeInput(e2) {
return e2 instanceof I ? e2 : new I(e2);
}
constructor(e2, t2 = {}, i2) {
f(this, "errors", []), f(this, "raw", /* @__PURE__ */ new Map()), f(this, "handleError", ((e3) => {
if (!this.options.silentErrors) throw e3;
this.errors.push(e3.message);
})), this.chunk = this.normalizeInput(e2), this.file = i2, this.type = this.constructor.type, this.globalOptions = this.options = t2, this.localOptions = t2[this.type], this.canTranslate = this.localOptions && this.localOptions.translate;
}
translate() {
this.canTranslate && (this.translated = this.translateBlock(this.raw, this.type));
}
get output() {
return this.translated ? this.translated : this.raw ? Object.fromEntries(this.raw) : void 0;
}
translateBlock(e2, t2) {
let i2 = V.get(t2), n2 = G.get(t2), s2 = N.get(t2), r2 = this.options[t2], a2 = r2.reviveValues && !!i2, o2 = r2.translateValues && !!n2, l2 = r2.translateKeys && !!s2, h2 = {};
for (let [t3, r3] of e2) a2 && i2.has(t3) ? r3 = i2.get(t3)(r3) : o2 && n2.has(t3) && (r3 = this.translateValue(r3, n2.get(t3))), l2 && s2.has(t3) && (t3 = s2.get(t3) || t3), h2[t3] = r3;
return h2;
}
translateValue(e2, t2) {
return t2[e2] || t2.DEFAULT || e2;
}
assignToOutput(e2, t2) {
this.assignObjectToOutput(e2, this.constructor.type, t2);
}
assignObjectToOutput(e2, t2, i2) {
if (this.globalOptions.mergeOutput) return Object.assign(e2, i2);
e2[t2] ? Object.assign(e2[t2], i2) : e2[t2] = i2;
}
}
f(ge, "headerLength", 4), f(ge, "type", void 0), f(ge, "multiSegment", false), f(ge, "canHandle", (() => false));
function me(e2) {
return 192 === e2 || 194 === e2 || 196 === e2 || 219 === e2 || 221 === e2 || 218 === e2 || 254 === e2;
}
function Se(e2) {
return e2 >= 224 && e2 <= 239;
}
function Ce(e2, t2, i2) {
for (let [n2, s2] of A) if (s2.canHandle(e2, t2, i2)) return n2;
}
class ye extends pe {
constructor(...e2) {
super(...e2), f(this, "appSegments", []), f(this, "jpegSegments", []), f(this, "unknownSegments", []);
}
static canHandle(e2, t2) {
return 65496 === t2;
}
async parse() {
await this.findAppSegments(), await this.readSegments(this.appSegments), this.mergeMultiSegments(), this.createParsers(this.mergedAppSegments || this.appSegments);
}
setupSegmentFinderArgs(e2) {
true === e2 ? (this.findAll = true, this.wanted = new Set(A.keyList())) : (e2 = void 0 === e2 ? A.keyList().filter(((e3) => this.options[e3].enabled)) : e2.filter(((e3) => this.options[e3].enabled && A.has(e3))), this.findAll = false, this.remaining = new Set(e2), this.wanted = new Set(e2)), this.unfinishedMultiSegment = false;
}
async findAppSegments(e2 = 0, t2) {
this.setupSegmentFinderArgs(t2);
let { file: i2, findAll: n2, wanted: s2, remaining: r2 } = this;
if (!n2 && this.file.chunked && (n2 = Array.from(s2).some(((e3) => {
let t3 = A.get(e3), i3 = this.options[e3];
return t3.multiSegment && i3.multiSegment;
})), n2 && await this.file.readWhole()), e2 = this.findAppSegmentsInRange(e2, i2.byteLength), !this.options.onlyTiff && i2.chunked) {
let t3 = false;
for (; r2.size > 0 && !t3 && (i2.canReadNextChunk || this.unfinishedMultiSegment); ) {
let { nextChunkOffset: n3 } = i2, s3 = this.appSegments.some(((e3) => !this.file.available(e3.offset || e3.start, e3.length || e3.size)));
if (t3 = e2 > n3 && !s3 ? !await i2.readNextChunk(e2) : !await i2.readNextChunk(n3), void 0 === (e2 = this.findAppSegmentsInRange(e2, i2.byteLength))) return;
}
}
}
findAppSegmentsInRange(e2, t2) {
t2 -= 2;
let i2, n2, s2, r2, a2, o2, { file: l2, findAll: h2, wanted: u2, remaining: c2, options: f2 } = this;
for (; e2 < t2; e2++) if (255 === l2.getUint8(e2)) {
if (i2 = l2.getUint8(e2 + 1), Se(i2)) {
if (n2 = l2.getUint16(e2 + 2), s2 = Ce(l2, e2, n2), s2 && u2.has(s2) && (r2 = A.get(s2), a2 = r2.findPosition(l2, e2), o2 = f2[s2], a2.type = s2, this.appSegments.push(a2), !h2 && (r2.multiSegment && o2.multiSegment ? (this.unfinishedMultiSegment = a2.chunkNumber < a2.chunkCount, this.unfinishedMultiSegment || c2.delete(s2)) : c2.delete(s2), 0 === c2.size))) break;
f2.recordUnknownSegments && (a2 = ge.findPosition(l2, e2), a2.marker = i2, this.unknownSegments.push(a2)), e2 += n2 + 1;
} else if (me(i2)) {
if (n2 = l2.getUint16(e2 + 2), 218 === i2 && false !== f2.stopAfterSos) return;
f2.recordJpegSegments && this.jpegSegments.push({ offset: e2, length: n2, marker: i2 }), e2 += n2 + 1;
}
}
return e2;
}
mergeMultiSegments() {
if (!this.appSegments.some(((e3) => e3.multiSegment))) return;
let e2 = (function(e3, t2) {
let i2, n2, s2, r2 = /* @__PURE__ */ new Map();
for (let a2 = 0; a2 < e3.length; a2++) i2 = e3[a2], n2 = i2[t2], r2.has(n2) ? s2 = r2.get(n2) : r2.set(n2, s2 = []), s2.push(i2);
return Array.from(r2);
})(this.appSegments, "type");
this.mergedAppSegments = e2.map((([e3, t2]) => {
let i2 = A.get(e3, this.options);
if (i2.handleMultiSegments) {
return { type: e3, chunk: i2.handleMultiSegments(t2) };
}
return t2[0];
}));
}
getSegment(e2) {
return this.appSegments.find(((t2) => t2.type === e2));
}
async getOrFindSegment(e2) {
let t2 = this.getSegment(e2);
return void 0 === t2 && (await this.findAppSegments(0, [e2]), t2 = this.getSegment(e2)), t2;
}
}
f(ye, "type", "jpeg"), T.set("jpeg", ye);
const be = [void 0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4];
class Pe extends ge {
parseHeader() {
var e2 = this.chunk.getUint16();
18761 === e2 ? this.le = true : 19789 === e2 && (this.le = false), this.chunk.le = this.le, this.headerParsed = true;
}
parseTags(e2, t2, i2 = /* @__PURE__ */ new Map()) {
let { pick: n2, skip: s2 } = this.options[t2];
n2 = new Set(n2);
let r2 = n2.size > 0, a2 = 0 === s2.size, o2 = this.chunk.getUint16(e2);
e2 += 2;
for (let l2 = 0; l2 < o2; l2++) {
let o3 = this.chunk.getUint16(e2);
if (r2) {
if (n2.has(o3) && (i2.set(o3, this.parseTag(e2, o3, t2)), n2.delete(o3), 0 === n2.size)) break;
} else !a2 && s2.has(o3) || i2.set(o3, this.parseTag(e2, o3, t2));
e2 += 12;
}
return i2;
}
parseTag(e2, t2, i2) {
let { chunk: n2 } = this, s2 = n2.getUint16(e2 + 2), r2 = n2.getUint32(e2 + 4), a2 = be[s2];
if (a2 * r2 <= 4 ? e2 += 8 : e2 = n2.getUint32(e2 + 8), (s2 < 1 || s2 > 13) && m(`Invalid TIFF value type. block: ${i2.toUpperCase()}, tag: ${t2.toString(16)}, type: ${s2}, offset ${e2}`), e2 > n2.byteLength && m(`Invalid TIFF value offset. block: ${i2.toUpperCase()}, tag: ${t2.toString(16)}, type: ${s2}, offset ${e2} is outside of chunk size ${n2.byteLength}`), 1 === s2) return n2.getUint8Array(e2, r2);
if (2 === s2) return S(n2.getString(e2, r2));
if (7 === s2) return n2.getUint8Array(e2, r2);
if (1 === r2) return this.parseTagValue(s2, e2);
{
let t3 = new ((function(e3) {
switch (e3) {
case 1:
return Uint8Array;
case 3:
return Uint16Array;
case 4:
return Uint32Array;
case 5:
return Array;
case 6:
return Int8Array;
case 8:
return Int16Array;
case 9:
return Int32Array;
case 10:
return Array;
case 11:
return Float32Array;
case 12:
return Float64Array;
default:
return Array;
}
})(s2))(r2), i3 = a2;
for (let n3 = 0; n3 < r2; n3++) t3[n3] = this.parseTagValue(s2, e2), e2 += i3;
return t3;
}
}
parseTagValue(e2, t2) {
let { chunk: i2 } = this;
switch (e2) {
case 1:
return i2.getUint8(t2);
case 3:
return i2.getUint16(t2);
case 4:
return i2.getUint32(t2);
case 5:
return i2.getUint32(t2) / i2.getUint32(t2 + 4);
case 6:
return i2.getInt8(t2);
case 8:
return i2.getInt16(t2);
case 9:
return i2.getInt32(t2);
case 10:
return i2.getInt32(t2) / i2.getInt32(t2 + 4);
case 11:
return i2.getFloat(t2);
case 12:
return i2.getDouble(t2);
case 13:
return i2.getUint32(t2);
default:
m(`Invalid tiff type ${e2}`);
}
}
}
class Ie extends Pe {
static canHandle(e2, t2) {
return 225 === e2.getUint8(t2 + 1) && 1165519206 === e2.getUint32(t2 + 4) && 0 === e2.getUint16(t2 + 8);
}
async parse() {
this.parseHeader();
let { options: e2 } = this;
return e2.ifd0.enabled && await this.parseIfd0Block(), e2.exif.enabled && await this.safeParse("parseExifBlock"), e2.gps.enabled && await this.safeParse("parseGpsBlock"), e2.interop.enabled && await this.safeParse("parseInteropBlock"), e2.ifd1.enabled && await this.safeParse("parseThumbnailBlock"), this.createOutput();
}
safeParse(e2) {
let t2 = this[e2]();
return void 0 !== t2.catch && (t2 = t2.catch(this.handleError)), t2;
}
findIfd0Offset() {
void 0 === this.ifd0Offset && (this.ifd0Offset = this.chunk.getUint32(4));
}
findIfd1Offset() {
if (void 0 === this.ifd1Offset) {
this.findIfd0Offset();
let e2 = this.chunk.getUint16(this.ifd0Offset), t2 = this.ifd0Offset + 2 + 12 * e2;
this.ifd1Offset = this.chunk.getUint32(t2);
}
}
parseBlock(e2, t2) {
let i2 = /* @__PURE__ */ new Map();
return this[t2] = i2, this.parseTags(e2, t2, i2), i2;
}
async parseIfd0Block() {
if (this.ifd0) return;
let { file: e2 } = this;
this.findIfd0Offset(), this.ifd0Offset < 8 && m("Malformed EXIF data"), !e2.chunked && this.ifd0Offset > e2.byteLength && m(`IFD0 offset points to outside of file.
this.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${e2.byteLength}`), e2.tiff && await e2.ensureChunk(this.ifd0Offset, C(this.options));
let t2 = this.parseBlock(this.ifd0Offset, "ifd0");
return 0 !== t2.size ? (this.exifOffset = t2.get(X), this.interopOffset = t2.get(Y), this.gpsOffset = t2.get(_), this.xmp = t2.get(j), this.iptc = t2.get(W), this.icc = t2.get(K), this.options.sanitize && (t2.delete(X), t2.delete(Y), t2.delete(_), t2.delete(j), t2.delete(W), t2.delete(K)), t2) : void 0;
}
async parseExifBlock() {
if (this.exif) return;
if (this.ifd0 || await this.parseIfd0Block(), void 0 === this.exifOffset) return;
this.file.tiff && await this.file.ensureChunk(this.exifOffset, C(this.options));
let e2 = this.parseBlock(this.exifOffset, "exif");
return this.interopOffset || (this.interopOffset = e2.get(Y)), this.makerNote = e2.get(z4), this.userComment = e2.get(H), this.options.sanitize && (e2.delete(Y), e2.delete(z4), e2.delete(H)), this.unpack(e2, 41728), this.unpack(e2, 41729), e2;
}
unpack(e2, t2) {
let i2 = e2.get(t2);
i2 && 1 === i2.length && e2.set(t2, i2[0]);
}
async parseGpsBlock() {
if (this.gps) return;
if (this.ifd0 || await this.parseIfd0Block(), void 0 === this.gpsOffset) return;
let e2 = this.parseBlock(this.gpsOffset, "gps");
return e2 && e2.has(2) && e2.has(4) && (e2.set("latitude", ke(...e2.get(2), e2.get(1))), e2.set("longitude", ke(...e2.get(4), e2.get(3)))), e2;
}
async parseInteropBlock() {
if (!this.interop && (this.ifd0 || await this.parseIfd0Block(), void 0 !== this.interopOffset || this.exif || await this.parseExifBlock(), void 0 !== this.interopOffset)) return this.parseBlock(this.interopOffset, "interop");
}
async parseThumbnailBlock(e2 = false) {
if (!this.ifd1 && !this.ifd1Parsed && (!this.options.mergeOutput || e2)) return this.findIfd1Offset(), this.ifd1Offset > 0 && (this.parseBlock(this.ifd1Offset, "ifd1"), this.ifd1Parsed = true), this.ifd1;
}
async extractThumbnail() {
if (this.headerParsed || this.parseHeader(), this.ifd1Parsed || await this.parseThumbnailBlock(true), void 0 === this.ifd1) return;
let e2 = this.ifd1.get(513), t2 = this.ifd1.get(514);
return this.chunk.getUint8Array(e2, t2);
}
get image() {
return this.ifd0;
}
get thumbnail() {
return this.ifd1;
}
createOutput() {
let e2, t2, i2, n2 = {};
for (t2 of Q) if (e2 = this[t2], !g(e2)) if (i2 = this.canTranslate ? this.translateBlock(e2, t2) : Object.fromEntries(e2), this.options.mergeOutput) {
if ("ifd1" === t2) continue;
Object.assign(n2, i2);
} else n2[t2] = i2;
return this.makerNote && (n2.makerNote = this.makerNote), this.userComment && (n2.userComment = this.userComment), n2;
}
assignToOutput(e2, t2) {
if (this.globalOptions.mergeOutput) Object.assign(e2, t2);
else for (let [i2, n2] of Object.entries(t2)) this.assignObjectToOutput(e2, i2, n2);
}
}
function ke(e2, t2, i2, n2) {
var s2 = e2 + t2 / 60 + i2 / 3600;
return "S" !== n2 && "W" !== n2 || (s2 *= -1), s2;
}
f(Ie, "type", "tiff"), f(Ie, "headerLength", 10), A.set("tiff", Ie);
var we = Object.freeze({ __proto__: null, default: de, Exifr: ce, fileParsers: T, segmentParsers: A, fileReaders: D, tagKeys: N, tagValues: G, tagRevivers: V, createDictionary: B, extendDictionary: E, fetchUrlAsArrayBuffer: L, readBlobAsArrayBuffer: U, chunkedProps: $, otherSegments: J, segments: q, tiffBlocks: Q, segmentsAndBlocks: Z, tiffExtractables: ee, inheritables: te, allFormatters: ie, Options: oe, parse: fe });
const Te = { ifd0: false, ifd1: false, exif: false, gps: false, interop: false, sanitize: false, reviveValues: true, translateKeys: false, translateValues: false, mergeOutput: false }, Ae = Object.assign({}, Te, { firstChunkSize: 4e4, gps: [1, 2, 3, 4] });
async function De(e2) {
let t2 = new ce(Ae);
await t2.read(e2);
let i2 = await t2.parse();
if (i2 && i2.gps) {
let { latitude: e3, longitude: t3 } = i2.gps;
return { latitude: e3, longitude: t3 };
}
}
const Oe = Object.assign({}, Te, { tiff: false, ifd1: true, mergeOutput: false });
async function xe(e2) {
let t2 = new ce(Oe);
await t2.read(e2);
let i2 = await t2.extractThumbnail();
return i2 && o ? r.from(i2) : i2;
}
async function ve(e2) {
let t2 = await this.thumbnail(e2);
if (void 0 !== t2) {
let e3 = new Blob([t2]);
return URL.createObjectURL(e3);
}
}
const Me = Object.assign({}, Te, { firstChunkSize: 4e4, ifd0: [274] });
async function Re(e2) {
let t2 = new ce(Me);
await t2.read(e2);
let i2 = await t2.parse();
if (i2 && i2.ifd0) return i2.ifd0[274];
}
const Le = Object.freeze({ 1: { dimensionSwapped: false, scaleX: 1, scaleY: 1, deg: 0, rad: 0 }, 2: { dimensionSwapped: false, scaleX: -1, scaleY: 1, deg: 0, rad: 0 }, 3: { dimensionSwapped: false, scaleX: 1, scaleY: 1, deg: 180, rad: 180 * Math.PI / 180 }, 4: { dimensionSwapped: false, scaleX: -1, scaleY: 1, deg: 180, rad: 180 * Math.PI / 180 }, 5: { dimensionSwapped: true, scaleX: 1, scaleY: -1, deg: 90, rad: 90 * Math.PI / 180 }, 6: { dimensionSwapped: true, scaleX: 1, scaleY: 1, deg: 90, rad: 90 * Math.PI / 180 }, 7: { dimensionSwapped: true, scaleX: 1, scaleY: -1, deg: 270, rad: 270 * Math.PI / 180 }, 8: { dimensionSwapped: true, scaleX: 1, scaleY: 1, deg: 270, rad: 270 * Math.PI / 180 } });
if (e.rotateCanvas = true, e.rotateCss = true, "object" == typeof navigator) {
let t2 = navigator.userAgent;
if (t2.includes("iPad") || t2.includes("iPhone")) {
let i2 = t2.match(/OS (\d+)_(\d+)/);
if (i2) {
let [, t3, n2] = i2, s2 = Number(t3) + 0.1 * Number(n2);
e.rotateCanvas = s2 < 13.4, e.rotateCss = false;
}
} else if (t2.includes("OS X 10")) {
let [, i2] = t2.match(/OS X 10[_.](\d+)/);
e.rotateCanvas = e.rotateCss = Number(i2) < 15;
}
if (t2.includes("Chrome/")) {
let [, i2] = t2.match(/Chrome\/(\d+)/);
e.rotateCanvas = e.rotateCss = Number(i2) < 81;
} else if (t2.includes("Firefox/")) {
let [, i2] = t2.match(/Firefox\/(\d+)/);
e.rotateCanvas = e.rotateCss = Number(i2) < 77;
}
}
async function Ue(t2) {
let i2 = await Re(t2);
return Object.assign({ canvas: e.rotateCanvas, css: e.rotateCss }, Le[i2]);
}
class Fe extends I {
constructor(...e2) {
super(...e2), f(this, "ranges", new Be()), 0 !== this.byteLength && this.ranges.add(0, this.byteLength);
}
_tryExtend(e2, t2, i2) {
if (0 === e2 && 0 === this.byteLength && i2) {
let e3 = new DataView(i2.buffer || i2, i2.byteOffset, i2.byteLength);
this._swapDataView(e3);
} else {
let i3 = e2 + t2;
if (i3 > this.byteLength) {
let { dataView: e3 } = this._extend(i3);
this._swapDataView(e3);
}
}
}
_extend(e2) {
let t2;
t2 = o ? r.allocUnsafe(e2) : new Uint8Array(e2);
let i2 = new DataView(t2.buffer, t2.byteOffset, t2.byteLength);
return t2.set(new Uint8Array(this.buffer, this.byteOffset, this.byteLength), 0), { uintView: t2, dataView: i2 };
}
subarray(e2, t2, i2 = false) {
return t2 = t2 || this._lengthToEnd(e2), i2 && this._tryExtend(e2, t2), this.ranges.add(e2, t2), super.subarray(e2, t2);
}
set(e2, t2, i2 = false) {
i2 && this._tryExtend(t2, e2.byteLength, e2);
let n2 = super.set(e2, t2);
return this.ranges.add(t2, n2.byteLength), n2;
}
async ensureChunk(e2, t2) {
this.chunked && (this.ranges.available(e2, t2) || await this.readChunk(e2, t2));
}
available(e2, t2) {
return this.ranges.available(e2, t2);
}
}
class Be {
constructor() {
f(this, "list", []);
}
get length() {
return this.list.length;
}
add(e2, t2, i2 = 0) {
let n2 = e2 + t2, s2 = this.list.filter(((t3) => Ee(e2, t3.offset, n2) || Ee(e2, t3.end, n2)));
if (s2.length > 0) {
e2 = Math.min(e2, ...s2.map(((e3) => e3.offset))), n2 = Math.max(n2, ...s2.map(((e3) => e3.end))), t2 = n2 - e2;
let i3 = s2.shift();
i3.offset = e2, i3.length = t2, i3.end = n2, this.list = this.list.filter(((e3) => !s2.includes(e3)));
} else this.list.push({ offset: e2, length: t2, end: n2 });
}
available(e2, t2) {
let i2 = e2 + t2;
return this.list.some(((t3) => t3.offset <= e2 && i2 <= t3.end));
}
}
function Ee(e2, t2, i2) {
return e2 <= t2 && t2 <= i2;
}
class Ne extends Fe {
constructor(e2, t2) {
super(0), f(this, "chunksRead", 0), this.input = e2, this.options = t2;
}
async readWhole() {
this.chunked = false, await this.readChunk(this.nextChunkOffset);
}
async readChunked() {
this.chunked = true, await this.readChunk(0, this.options.firstChunkSize);
}
async readNextChunk(e2 = this.nextChunkOffset) {
if (this.fullyRead) return this.chunksRead++, false;
let t2 = this.options.chunkSize, i2 = await this.readChunk(e2, t2);
return !!i2 && i2.byteLength === t2;
}
async readChunk(e2, t2) {
if (this.chunksRead++, 0 !== (t2 = this.safeWrapAddress(e2, t2))) return this._readChunk(e2, t2);
}
safeWrapAddress(e2, t2) {
return void 0 !== this.size && e2 + t2 > this.size ? Math.max(0, this.size - e2) : t2;
}
get nextChunkOffset() {
if (0 !== this.ranges.list.length) return this.ranges.list[0].length;
}
get canReadNextChunk() {
return this.chunksRead < this.options.chunkLimit;
}
get fullyRead() {
return void 0 !== this.size && this.nextChunkOffset === this.size;
}
read() {
return this.options.chunked ? this.readChunked() : this.readWhole();
}
close() {
}
}
D.set("blob", class extends Ne {
async readWhole() {
this.chunked = false;
let e2 = await U(this.input);
this._swapArrayBuffer(e2);
}
readChunked() {
return this.chunked = true, this.size = this.input.size, super.readChunked();
}
async _readChunk(e2, t2) {
let i2 = t2 ? e2 + t2 : void 0, n2 = this.input.slice(e2, i2), s2 = await U(n2);
return this.set(s2, e2, true);
}
});
var Ge = Object.freeze({ __proto__: null, default: we, Exifr: ce, fileParsers: T, segmentParsers: A, fileReaders: D, tagKeys: N, tagValues: G, tagRevivers: V, createDictionary: B, extendDictionary: E, fetchUrlAsArrayBuffer: L, readBlobAsArrayBuffer: U, chunkedProps: $, otherSegments: J, segments: q, tiffBlocks: Q, segmentsAndBlocks: Z, tiffExtractables: ee, inheritables: te, allFormatters: ie, Options: oe, parse: fe, gpsOnlyOptions: Ae, gps: De, thumbnailOnlyOptions: Oe, thumbnail: xe, thumbnailUrl: ve, orientationOnlyOptions: Me, orientation: Re, rotations: Le, get rotateCanvas() {
return e.rotateCanvas;
}, get rotateCss() {
return e.rotateCss;
}, rotation: Ue });
D.set("url", class extends Ne {
async readWhole() {
this.chunked = false;
let e2 = await L(this.input);
e2 instanceof ArrayBuffer ? this._swapArrayBuffer(e2) : e2 instanceof Uint8Array && this._swapBuffer(e2);
}
async _readChunk(e2, t2) {
let i2 = t2 ? e2 + t2 - 1 : void 0, n2 = this.options.httpHeaders || {};
(e2 || i2) && (n2.range = `bytes=${[e2, i2].join("-")}`);
let s2 = await u(this.input, { headers: n2 }), r2 = await s2.arrayBuffer(), a2 = r2.byteLength;
if (416 !== s2.status) return a2 !== t2 && (this.size = e2 + a2), this.set(r2, e2, true);
}
});
I.prototype.getUint64 = function(e2) {
let t2 = this.getUint32(e2), i2 = this.getUint32(e2 + 4);
return t2 < 1048575 ? t2 << 32 | i2 : void 0 !== typeof a ? (console.warn("Using BigInt because of type 64uint but JS can only handle 53b numbers."), a(t2) << a(32) | a(i2)) : void m("Trying to read 64b value but JS can only handle 53b numbers.");
};
class Ve extends pe {
parseBoxes(e2 = 0) {
let t2 = [];
for (; e2 < this.file.byteLength - 4; ) {
let i2 = this.parseBoxHead(e2);
if (t2.push(i2), 0 === i2.length) break;
e2 += i2.length;
}
return t2;
}
parseSubBoxes(e2) {
e2.boxes = this.parseBoxes(e2.start);
}
findBox(e2, t2) {
return void 0 === e2.boxes && this.parseSubBoxes(e2), e2.boxes.find(((e3) => e3.kind === t2));
}
parseBoxHead(e2) {
let t2 = this.file.getUint32(e2), i2 = this.file.getString(e2 + 4, 4), n2 = e2 + 8;
return 1 === t2 && (t2 = this.file.getUint64(e2 + 8), n2 += 8), { offset: e2, length: t2, kind: i2, start: n2 };
}
parseBoxFullHead(e2) {
if (void 0 !== e2.version) return;
let t2 = this.file.getUint32(e2.start);
e2.version = t2 >> 24, e2.start += 4;
}
}
class ze extends Ve {
static canHandle(e2, t2) {
if (0 !== t2) return false;
let i2 = e2.getUint16(2);
if (i2 > 50) return false;
let n2 = 16, s2 = [];
for (; n2 < i2; ) s2.push(e2.getString(n2, 4)), n2 += 4;
return s2.includes(this.type);
}
async parse() {
let e2 = this.file.getUint32(0), t2 = this.parseBoxHead(e2);
for (; "meta" !== t2.kind; ) e2 += t2.length, await this.file.ensureChunk(e2, 16), t2 = this.parseBoxHead(e2);
await this.file.ensureChunk(t2.offset, t2.length), this.parseBoxFullHead(t2), this.parseSubBoxes(t2), this.options.icc.enabled && await this.findIcc(t2), this.options.tiff.enabled && await this.findExif(t2);
}
async registerSegment(e2, t2, i2) {
await this.file.ensureChunk(t2, i2);
let n2 = this.file.subarray(t2, i2);
this.createParser(e2, n2);
}
async findIcc(e2) {
let t2 = this.findBox(e2, "iprp");
if (void 0 === t2) return;
let i2 = this.findBox(t2, "ipco");
if (void 0 === i2) return;
let n2 = this.findBox(i2, "colr");
void 0 !== n2 && await this.registerSegment("icc", n2.offset + 12, n2.length);
}
async findExif(e2) {
let t2 = this.findBox(e2, "iinf");
if (void 0 === t2) return;
let i2 = this.findBox(e2, "iloc");
if (void 0 === i2) return;
let n2 = this.findExifLocIdInIinf(t2), s2 = this.findExtentInIloc(i2, n2);
if (void 0 === s2) return;
let [r2, a2] = s2;
await this.file.ensureChunk(r2, a2);
let o2 = 4 + this.file.getUint32(r2);
r2 += o2, a2 -= o2, await this.registerSegment("tiff", r2, a2);
}
findExifLocIdInIinf(e2) {
this.parseBoxFullHead(e2);
let t2, i2, n2, s2, r2 = e2.start, a2 = this.file.getUint16(r2);
for (r2 += 2; a2--; ) {
if (t2 = this.parseBoxHead(r2), this.parseBoxFullHead(t2), i2 = t2.start, t2.version >= 2 && (n2 = 3 === t2.version ? 4 : 2, s2 = this.file.getString(i2 + n2 + 2, 4), "Exif" === s2)) return this.file.getUintBytes(i2, n2);
r2 += t2.length;
}
}
get8bits(e2) {
let t2 = this.file.getUint8(e2);
return [t2 >> 4, 15 & t2];
}
findExtentInIloc(e2, t2) {
this.parseBoxFullHead(e2);
let i2 = e2.start, [n2, s2] = this.get8bits(i2++), [r2, a2] = this.get8bits(i2++), o2 = 2 === e2.version ? 4 : 2, l2 = 1 === e2.version || 2 === e2.version ? 2 : 0, h2 = a2 + n2 + s2, u2 = 2 === e2.version ? 4 : 2, c2 = this.file.getUintBytes(i2, u2);
for (i2 += u2; c2--; ) {
let e3 = this.file.getUintBytes(i2, o2);
i2 += o2 + l2 + 2 + r2;
let u3 = this.file.getUint16(i2);
if (i2 += 2, e3 === t2) return u3 > 1 && console.warn("ILOC box has more than one extent but we're only processing one\nPlease create an issue at https://github.com/MikeKovarik/exifr with this file"), [this.file.getUintBytes(i2 + a2, n2), this.file.getUintBytes(i2 + a2 + n2, s2)];
i2 += u3 * h2;
}
}
}
class He extends ze {
}
f(He, "type", "heic");
class je extends ze {
}
f(je, "type", "avif"), T.set("heic", He), T.set("avif", je), B(N, ["ifd0", "ifd1"], [[256, "ImageWidth"], [257, "ImageHeight"], [258, "BitsPerSample"], [259, "Compression"], [262, "PhotometricInterpretation"], [270, "ImageDescription"], [271, "Make"], [272, "Model"], [273, "StripOffsets"], [274, "Orientation"], [277, "SamplesPerPixel"], [278, "RowsPerStrip"], [279, "StripByteCounts"], [282, "XResolution"], [283, "YResolution"], [284, "PlanarConfiguration"], [296, "ResolutionUnit"], [301, "TransferFunction"], [305, "Software"], [306, "ModifyDate"], [315, "Artist"], [316, "HostComputer"], [317, "Predictor"], [318, "WhitePoint"], [319, "PrimaryChromaticities"], [513, "ThumbnailOffset"], [514, "ThumbnailLength"], [529, "YCbCrCoefficients"], [530, "YCbCrSubSampling"], [531, "YCbCrPositioning"], [532, "ReferenceBlackWhite"], [700, "ApplicationNotes"], [33432, "Copyright"], [33723, "IPTC"], [34665, "ExifIFD"], [34675, "ICC"], [34853, "GpsIFD"], [330, "SubIFD"], [40965, "InteropIFD"], [40091, "XPTitle"], [40092, "XPComment"], [40093, "XPAuthor"], [40094, "XPKeywords"], [40095, "XPSubject"]]), B(N, "exif", [[33434, "ExposureTime"], [33437, "FNumber"], [34850, "ExposureProgram"], [34852, "SpectralSensitivity"], [34855, "ISO"], [34858, "TimeZoneOffset"], [34859, "SelfTimerMode"], [34864, "SensitivityType"], [34865, "StandardOutputSensitivity"], [34866, "RecommendedExposureIndex"], [34867, "ISOSpeed"], [34868, "ISOSpeedLatitudeyyy"], [34869, "ISOSpeedLatitudezzz"], [36864, "ExifVersion"], [36867, "DateTimeOriginal"], [36868, "CreateDate"], [36873, "GooglePlusUploadCode"], [36880, "OffsetTime"], [36881, "OffsetTimeOriginal"], [36882, "OffsetTimeDigitized"], [37121, "ComponentsConfiguration"], [37122, "CompressedBitsPerPixel"], [37377, "ShutterSpeedValue"], [37378, "ApertureValue"], [37379, "BrightnessValue"], [37380, "ExposureCompensation"], [37381, "MaxApertureValue"], [37382, "SubjectDistance"], [37383, "MeteringMode"], [37384, "LightSource"], [37385, "Flash"], [37386, "FocalLength"], [37393, "ImageNumber"], [37394, "SecurityClassification"], [37395, "ImageHistory"], [37396, "SubjectArea"], [37500, "MakerNote"], [37510, "UserComment"], [37520, "SubSecTime"], [37521, "SubSecTimeOriginal"], [37522, "SubSecTimeDigitized"], [37888, "AmbientTemperature"], [37889, "Humidity"], [37890, "Pressure"], [37891, "WaterDepth"], [37892, "Acceleration"], [37893, "CameraElevationAngle"], [40960, "FlashpixVersion"], [40961, "ColorSpace"], [40962, "ExifImageWidth"], [40963, "ExifImageHeight"], [40964, "RelatedSoundFile"], [41483, "FlashEnergy"], [41486, "FocalPlaneXResolution"], [41487, "FocalPlaneYResolution"], [41488, "FocalPlaneResolutionUnit"], [41492, "SubjectLocation"], [41493, "ExposureIndex"], [41495, "SensingMethod"], [41728, "FileSource"], [41729, "SceneType"], [41730, "CFAPattern"], [41985, "CustomRendered"], [41986, "ExposureMode"], [41987, "WhiteBalance"], [41988, "DigitalZoomRatio"], [41989, "FocalLengthIn35mmFormat"], [41990, "SceneCaptureType"], [41991, "GainControl"], [41992, "Contrast"], [41993, "Saturation"], [41994, "Sharpness"], [41996, "SubjectDistanceRange"], [42016, "ImageUniqueID"], [42032, "OwnerName"], [42033, "SerialNumber"], [42034, "LensInfo"], [42035, "LensMake"], [42036, "LensModel"], [42037, "LensSerialNumber"], [42080, "CompositeImage"], [42081, "CompositeImageCount"], [42082, "CompositeImageExposureTimes"], [42240, "Gamma"], [59932, "Padding"], [59933, "OffsetSchema"], [65e3, "OwnerName"], [65001, "SerialNumber"], [65002, "Lens"], [65100, "RawFile"], [65101, "Converter"], [65102, "WhiteBalance"], [65105, "Exposure"], [65106, "Shadows"], [65107, "Brightness"], [65108, "Contrast"], [65109, "Saturation"], [65110, "Sharpness"], [65111, "Smoothness"], [65112, "MoireFilter"], [40965, "InteropIFD"]]), B(N, "gps", [[0, "GPSVersionID"], [1, "GPSLatitudeRef"], [2, "GPSLatitude"], [3, "GPSLongitudeRef"], [4, "GPSLongitude"], [5, "GPSAltitudeRef"], [6, "GPSAltitude"], [7, "GPSTimeStamp"], [8, "GPSSatellites"], [9, "GPSStatus"], [10, "GPSMeasureMode"], [11, "GPSDOP"], [12, "GPSSpeedRef"], [13, "GPSSpeed"], [14, "GPSTrackRef"], [15, "GPSTrack"], [16, "GPSImgDirectionRef"], [17, "GPSImgDirection"], [18, "GPSMapDatum"], [19, "GPSDestLatitudeRef"], [20, "GPSDestLatitude"], [21, "GPSDestLongitudeRef"], [22, "GPSDestLongitude"], [23, "GPSDestBearingRef"], [24, "GPSDestBearing"], [25, "GPSDestDistanceRef"], [26, "GPSDestDistance"], [27, "GPSProcessingMethod"], [28, "GPSAreaInformation"], [29, "GPSDateStamp"], [30, "GPSDifferential"], [31, "GPSHPositioningError"]]), B(G, ["ifd0", "ifd1"], [[274, { 1: "Horizontal (normal)", 2: "Mirror horizontal", 3: "Rotate 180", 4: "Mirror vertical", 5: "Mirror horizontal and rotate 270 CW", 6: "Rotate 90 CW", 7: "Mirror horizontal and rotate 90 CW", 8: "Rotate 270 CW" }], [296, { 1: "None", 2: "inches", 3: "cm" }]]);
let We = B(G, "exif", [[34850, { 0: "Not defined", 1: "Manual", 2: "Normal program", 3: "Aperture priority", 4: "Shutter priority", 5: "Creative program", 6: "Action program", 7: "Portrait mode", 8: "Landscape mode" }], [37121, { 0: "-", 1: "Y", 2: "Cb", 3: "Cr", 4: "R", 5: "G", 6: "B" }], [37383, { 0: "Unknown", 1: "Average", 2: "CenterWeightedAverage", 3: "Spot", 4: "MultiSpot", 5: "Pattern", 6: "Partial", 255: "Other" }], [37384, { 0: "Unknown", 1: "Daylight", 2: "Fluorescent", 3: "Tungsten (incandescent light)", 4: "Flash", 9: "Fine weather", 10: "Cloudy weather", 11: "Shade", 12: "Daylight fluorescent (D 5700 - 7100K)", 13: "Day white fluorescent (N 4600 - 5400K)", 14: "Cool white fluorescent (W 3900 - 4500K)", 15: "White fluorescent (WW 3200 - 3700K)", 17: "Standard light A", 18: "Standard light B", 19: "Standard light C", 20: "D55", 21: "D65", 22: "D75", 23: "D50", 24: "ISO studio tungsten", 255: "Other" }], [37385, { 0: "Flash did not fire", 1: "Flash fired", 5: "Strobe return light not detected", 7: "Strobe return light detected", 9: "Flash fired, compulsory flash mode", 13: "Flash fired, compulsory flash mode, return light not detected", 15: "Flash fired, compulsory flash mode, return light detected", 16: "Flash did not fire, compulsory flash mode", 24: "Flash did not fire, auto mode", 25: "Flash fired, auto mode", 29: "Flash fired, auto mode, return light not detected", 31: "Flash fired, auto mode, return light detected", 32: "No flash function", 65: "Flash fired, red-eye reduction mode", 69: "Flash fired, red-eye reduction mode, return light not detected", 71: "Flash fired, red-eye reduction mode, return light detected", 73: "Flash fired, compulsory flash mode, red-eye reduction mode", 77: "Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected", 79: "Flash fired, compulsory flash mode, red-eye reduction mode, return light detected", 89: "Flash fired, auto mode, red-eye reduction mode", 93: "Flash fired, auto mode, return light not detected, red-eye reduction mode", 95: "Flash fired, auto mode, return light detected, red-eye reduction mode" }], [41495, { 1: "Not defined", 2: "One-chip color area sensor", 3: "Two-chip color area sensor", 4: "Three-chip color area sensor", 5: "Color sequential area sensor", 7: "Trilinear sensor", 8: "Color sequential linear sensor" }], [41728, { 1: "Film Scanner", 2: "Reflection Print Scanner", 3: "Digital Camera" }], [41729, { 1: "Directly photographed" }], [41985, { 0: "Normal", 1: "Custom", 2: "HDR (no original saved)", 3: "HDR (original saved)", 4: "Original (for HDR)", 6: "Panorama", 7: "Portrait HDR", 8: "Portrait" }], [41986, { 0: "Auto", 1: "Manual", 2: "Auto bracket" }], [41987, { 0: "Auto", 1: "Manual" }], [41990, { 0: "Standard", 1: "Landscape", 2: "Portrait", 3: "Night", 4: "Other" }], [41991, { 0: "None", 1: "Low gain up", 2: "High gain up", 3: "Low gain down", 4: "High gain down" }], [41996, { 0: "Unknown", 1: "Macro", 2: "Close", 3: "Distant" }], [42080, { 0: "Unknown", 1: "Not a Composite Image", 2: "General Composite Image", 3: "Composite Image Captured While Shooting" }]]);
const Ke = { 1: "No absolute unit of measurement", 2: "Inch", 3: "Centimeter" };
We.set(37392, Ke), We.set(41488, Ke);
const Xe = { 0: "Normal", 1: "Low", 2: "High" };
function _e(e2) {
return "object" == typeof e2 && void 0 !== e2.length ? e2[0] : e2;
}
function Ye(e2) {
let t2 = Array.from(e2).slice(1);
return t2[1] > 15 && (t2 = t2.map(((e3) => String.fromCharCode(e3)))), "0" !== t2[2] && 0 !== t2[2] || t2.pop(), t2.join(".");
}
function $e(e2) {
if ("string" == typeof e2) {
var [t2, i2, n2, s2, r2, a2] = e2.trim().split(/[-: ]/g).map(Number), o2 = new Date(t2, i2 - 1, n2);
return Number.isNaN(s2) || Number.isNaN(r2) || Number.isNaN(a2) || (o2.setHours(s2), o2.setMinutes(r2), o2.setSeconds(a2)), Number.isNaN(+o2) ? e2 : o2;
}
}
function Je(e2) {
if ("string" == typeof e2) return e2;
let t2 = [];
if (0 === e2[1] && 0 === e2[e2.length - 1]) for (let i2 = 0; i2 < e2.length; i2 += 2) t2.push(qe(e2[i2 + 1], e2[i2]));
else for (let i2 = 0; i2 < e2.length; i2 += 2) t2.push(qe(e2[i2], e2[i2 + 1]));
return S(String.fromCodePoint(...t2));
}
function qe(e2, t2) {
return e2 << 8 | t2;
}
We.set(41992, Xe), We.set(41993, Xe), We.set(41994, Xe), B(V, ["ifd0", "ifd1"], [[50827, function(e2) {
return "string" != typeof e2 ? P(e2) : e2;
}], [306, $e], [40091, Je], [40092, Je], [40093, Je], [40094, Je], [40095, Je]]), B(V, "exif", [[40960, Ye], [36864, Ye], [36867, $e], [36868, $e], [40962, _e], [40963, _e]]), B(V, "gps", [[0, (e2) => Array.from(e2).join(".")], [7, (e2) => Array.from(e2).join(":")]]);
const Qe = "http://ns.adobe.com/", Ze = "http://ns.adobe.com/xmp/extension/";
class et extends ge {
static canHandle(e2, t2) {
return 225 === e2.getUint8(t2 + 1) && 1752462448 === e2.getUint32(t2 + 4) && e2.getString(t2 + 4, Qe.length) === Qe;
}
static headerLength(e2, t2) {
return e2.getString(t2 + 4, Ze.length) === Ze ? 79 : 4 + "http://ns.adobe.com/xap/1.0/".length + 1;
}
static findPosition(e2, t2) {
let i2 = super.findPosition(e2, t2);
return i2.multiSegment = i2.extended = 79 === i2.headerLength, i2.multiSegment ? (i2.chunkCount = e2.getUint8(t2 + 72), i2.chunkNumber = e2.getUint8(t2 + 76), 0 !== e2.getUint8(t2 + 77) && i2.chunkNumber++) : (i2.chunkCount = 1 / 0, i2.chunkNumber = -1), i2;
}
static handleMultiSegments(e2) {
return e2.map(((e3) => e3.chunk.getString())).join("");
}
normalizeInput(e2) {
return "string" == typeof e2 ? e2 : I.from(e2).getString();
}
parse(e2 = this.chunk) {
if (!this.localOptions.parse) return e2;
e2 = (function(e3) {
let t3 = {}, i3 = {};
for (let e4 of ut) t3[e4] = [], i3[e4] = 0;
return e3.replace(ct, ((e4, n3, s2) => {
if ("<" === n3) {
let n4 = ++i3[s2];
return t3[s2].push(n4), `${e4}#${n4}`;
}
return `${e4}#${t3[s2].pop()}`;
}));
})(e2);
let t2 = nt.findAll(e2, "rdf", "Description");
0 === t2.length && t2.push(new nt("rdf", "Description", void 0, e2));
let i2, n2 = {};
for (let e3 of t2) for (let t3 of e3.properties) i2 = ot(t3.ns, n2), st(t3, i2);
return (function(e3) {
let t3;
for (let i3 in e3) t3 = e3[i3] = d(e3[i3]), void 0 === t3 && delete e3[i3];
return d(e3);
})(n2);
}
assignToOutput(e2, t2) {
if (this.localOptions.parse) for (let [i2, n2] of Object.entries(t2)) switch (i2) {
case "tiff":
this.assignObjectToOutput(e2, "ifd0", n2);
break;
case "exif":
this.assignObjectToOutput(e2, "exif", n2);
break;
case "xmlns":
break;
default:
this.assignObjectToOutput(e2, i2, n2);
}
else e2.xmp = t2;
}
}
f(et, "type", "xmp"), f(et, "multiSegment", true), A.set("xmp", et);
class tt {
static findAll(e2) {
return lt(e2, /([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm).map(tt.unpackMatch);
}
static unpackMatch(e2) {
let t2 = e2[1], i2 = e2[2], n2 = e2[3].slice(1, -1);
return n2 = ht(n2), new tt(t2, i2, n2);
}
constructor(e2, t2, i2) {
this.ns = e2, this.name = t2, this.value = i2;
}
serialize() {
return this.value;
}
}
const it = "[\\w\\d-]+";
class nt {
static findAll(e2, t2, i2) {
if (void 0 !== t2 || void 0 !== i2) {
t2 = t2 || it, i2 = i2 || it;
var n2 = new RegExp(`<(${t2}):(${i2})(#\\d+)?((\\s+?[\\w\\d-:]+=("[^"]*"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)`, "gm");
} else n2 = /<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm;
return lt(e2, n2).map(nt.unpackMatch);
}
static unpackMatch(e2) {
let t2 = e2[1], i2 = e2[2], n2 = e2[4], s2 = e2[8];
return new nt(t2, i2, n2, s2);
}
constructor(e2, t2, i2, n2) {
this.ns = e2, this.name = t2, this.attrString = i2, this.innerXml = n2, this.attrs = tt.findAll(i2), this.children = nt.findAll(n2), this.value = 0 === this.children.length ? ht(n2) : void 0, this.properties = [...this.attrs, ...this.children];
}
get isPrimitive() {
return void 0 !== this.value && 0 === this.attrs.length && 0 === this.children.length;
}
get isListContainer() {
return 1 === this.children.length && this.children[0].isList;
}
get isList() {
let { ns: e2, name: t2 } = this;
return "rdf" === e2 && ("Seq" === t2 || "Bag" === t2 || "Alt" === t2);
}
get isListItem() {
return "rdf" === this.ns && "li" === this.name;
}
serialize() {
if (0 === this.properties.length && void 0 === this.value) return;
if (this.isPrimitive) return this.value;
if (this.isListContainer) return this.children[0].serialize();
if (this.isList) return at(this.children.map(rt));
if (this.isListItem && 1 === this.children.length && 0 === this.attrs.length) return this.children[0].serialize();
let e2 = {};
for (let t2 of this.properties) st(t2, e2);
return void 0 !== this.value && (e2.value = this.value), d(e2);
}
}
function st(e2, t2) {
let i2 = e2.serialize();
void 0 !== i2 && (t2[e2.name] = i2);
}
var rt = (e2) => e2.serialize(), at = (e2) => 1 === e2.length ? e2[0] : e2, ot = (e2, t2) => t2[e2] ? t2[e2] : t2[e2] = {};
function lt(e2, t2) {
let i2, n2 = [];
if (!e2) return n2;
for (; null !== (i2 = t2.exec(e2)); ) n2.push(i2);
return n2;
}
function ht(e2) {
if ((function(e3) {
return null == e3 || "null" === e3 || "undefined" === e3 || "" === e3 || "" === e3.trim();
})(e2)) return;
let t2 = Number(e2);
if (!Number.isNaN(t2)) return t2;
let i2 = e2.toLowerCase();
return "true" === i2 || "false" !== i2 && e2.trim();
}
const ut = ["rdf:li", "rdf:Seq", "rdf:Bag", "rdf:Alt", "rdf:Description"], ct = new RegExp(`(<|\\/)(${ut.join("|")})`, "g");
var ft = Object.freeze({ __proto__: null, default: Ge, Exifr: ce, fileParsers: T, segmentParsers: A, fileReaders: D, tagKeys: N, tagValues: G, tagRevivers: V, createDictionary: B, extendDictionary: E, fetchUrlAsArrayBuffer: L, readBlobAsArrayBuffer: U, chunkedProps: $, otherSegments: J, segments: q, tiffBlocks: Q, segmentsAndBlocks: Z, tiffExtractables: ee, inheritables: te, allFormatters: ie, Options: oe, parse: fe, gpsOnlyOptions: Ae, gps: De, thumbnailOnlyOptions: Oe, thumbnail: xe, thumbnailUrl: ve, orientationOnlyOptions: Me, orientation: Re, rotations: Le, get rotateCanvas() {
return e.rotateCanvas;
}, get rotateCss() {
return e.rotateCss;
}, rotation: Ue });
const dt = ["xmp", "icc", "iptc", "tiff"], pt = () => {
};
async function gt(e2, t2, i2) {
let n2 = i2[e2];
return n2.enabled = true, n2.parse = true, A.get(e2).parse(t2, n2);
}
let mt = h("fs", ((e2) => e2.promises));
D.set("fs", class extends Ne {
async readWhole() {
this.chunked = false, this.fs = await mt;
let e2 = await this.fs.readFile(this.input);
this._swapBuffer(e2);
}
async readChunked() {
this.chunked = true, this.fs = await mt, await this.open(), await this.readChunk(0, this.options.firstChunkSize);
}
async open() {
void 0 === this.fh && (this.fh = await this.fs.open(this.input, "r"), this.size = (await this.fh.stat(this.input)).size);
}
async _readChunk(e2, t2) {
void 0 === this.fh && await this.open(), e2 + t2 > this.size && (t2 = this.size - e2);
var i2 = this.subarray(e2, t2, true);
return await this.fh.read(i2.dataView, 0, t2, e2), i2;
}
async close() {
if (this.fh) {
let e2 = this.fh;
this.fh = void 0, await e2.close();
}
}
});
D.set("base64", class extends Ne {
constructor(...e2) {
super(...e2), this.input = this.input.replace(/^data:([^;]+);base64,/gim, ""), this.size = this.input.length / 4 * 3, this.input.endsWith("==") ? this.size -= 2 : this.input.endsWith("=") && (this.size -= 1);
}
async _readChunk(e2, t2) {
let i2, n2, s2 = this.input;
void 0 === e2 ? (e2 = 0, i2 = 0, n2 = 0) : (i2 = 4 * Math.floor(e2 / 3), n2 = e2 - i2 / 4 * 3), void 0 === t2 && (t2 = this.size);
let a2 = e2 + t2, l2 = i2 + 4 * Math.ceil(a2 / 3);
s2 = s2.slice(i2, l2);
let h2 = Math.min(t2, this.size - e2);
if (o) {
let t3 = r.from(s2, "base64").slice(n2, n2 + h2);
return this.set(t3, e2, true);
}
{
let t3 = this.subarray(e2, h2, true), i3 = atob(s2), r2 = t3.toUint8();
for (let e3 = 0; e3 < h2; e3++) r2[e3] = i3.charCodeAt(n2 + e3);
return t3;
}
}
});
class St extends pe {
static canHandle(e2, t2) {
return 18761 === t2 || 19789 === t2;
}
extendOptions(e2) {
let { ifd0: t2, xmp: i2, iptc: n2, icc: s2 } = e2;
i2.enabled && t2.deps.add(j), n2.enabled && t2.deps.add(W), s2.enabled && t2.deps.add(K), t2.finalizeFilters();
}
async parse() {
let { tiff: e2, xmp: t2, iptc: i2, icc: n2 } = this.options;
if (e2.enabled || t2.enabled || i2.enabled || n2.enabled) {
let e3 = Math.max(C(this.options), this.options.chunkSize);
await this.file.ensureChunk(0, e3), this.createParser("tiff", this.file), this.parsers.tiff.parseHeader(), await this.parsers.tiff.parseIfd0Block(), this.adaptTiffPropAsSegment("xmp"), this.adaptTiffPropAsSegment("iptc"), this.adaptTiffPropAsSegment("icc");
}
}
adaptTiffPropAsSegment(e2) {
if (this.parsers.tiff[e2]) {
let t2 = this.parsers.tiff[e2];
this.injectSegment(e2, t2);
}
}
}
f(St, "type", "tiff"), T.set("tiff", St);
let Ct = h("zlib");
const yt = "XML:com.adobe.xmp", bt = "ihdr", Pt = "iccp", It = "text", kt = "itxt", wt = [bt, Pt, It, kt, "exif"];
class Tt extends pe {
constructor(...e2) {
super(...e2), f(this, "catchError", ((e3) => this.errors.push(e3))), f(this, "metaChunks", []), f(this, "unknownChunks", []);
}
static canHandle(e2, t2) {
return 35152 === t2 && 2303741511 === e2.getUint32(0) && 218765834 === e2.getUint32(4);
}
async parse() {
let { file: e2 } = this;
await this.findPngChunksInRange("\x89PNG\r\n\n".length, e2.byteLength), await this.readSegments(this.metaChunks), this.findIhdr(), this.parseTextChunks(), await this.findExif().catch(this.catchError), await this.findXmp().catch(this.catchError), await this.findIcc().catch(this.catchError);
}
async findPngChunksInRange(e2, t2) {
let { file: i2 } = this;
for (; e2 < t2; ) {
let t3 = i2.getUint32(e2), n2 = i2.getUint32(e2 + 4), s2 = i2.getString(e2 + 4, 4).toLowerCase(), r2 = t3 + 4 + 4 + 4, a2 = { type: s2, offset: e2, length: r2, start: e2 + 4 + 4, size: t3, marker: n2 };
wt.includes(s2) ? this.metaChunks.push(a2) : this.unknownChunks.push(a2), e2 += r2;
}
}
parseTextChunks() {
let e2 = this.metaChunks.filter(((e3) => e3.type === It));
for (let t2 of e2) {
let [e3, i2] = this.file.getString(t2.start, t2.size).split("\0");
this.injectKeyValToIhdr(e3, i2);
}
}
injectKeyValToIhdr(e2, t2) {
let i2 = this.parsers.ihdr;
i2 && i2.raw.set(e2, t2);
}
findIhdr() {
let e2 = this.metaChunks.find(((e3) => e3.type === bt));
e2 && false !== this.options.ihdr.enabled && this.createParser(bt, e2.chunk);
}
async findExif() {
let e2 = this.metaChunks.find(((e3) => "exif" === e3.type));
e2 && this.injectSegment("tiff", e2.chunk);
}
async findXmp() {
let e2 = this.metaChunks.filter(((e3) => e3.type === kt));
for (let t2 of e2) {
t2.chunk.getString(0, yt.length) === yt && this.injectSegment("xmp", t2.chunk);
}
}
async findIcc() {
let e2 = this.metaChunks.find(((e3) => e3.type === Pt));
if (!e2) return;
let { chunk: t2 } = e2, i2 = t2.getUint8Array(0, 81), n2 = 0;
for (; n2 < 80 && 0 !== i2[n2]; ) n2++;
let r2 = n2 + 2, a2 = t2.getString(0, n2);
if (this.injectKeyValToIhdr("ProfileName", a2), s) {
let e3 = await Ct, i3 = t2.getUint8Array(r2);
i3 = e3.inflateSync(i3), this.injectSegment("icc", i3);
}
}
}
f(Tt, "type", "png"), T.set("png", Tt), B(N, "interop", [[1, "InteropIndex"], [2, "InteropVersion"], [4096, "RelatedImageFileFormat"], [4097, "RelatedImageWidth"], [4098, "RelatedImageHeight"]]), E(N, "ifd0", [[11, "ProcessingSoftware"], [254, "SubfileType"], [255, "OldSubfileType"], [263, "Thresholding"], [264, "CellWidth"], [265, "CellLength"], [266, "FillOrder"], [269, "DocumentName"], [280, "MinSampleValue"], [281, "MaxSampleValue"], [285, "PageName"], [286, "XPosition"], [287, "YPosition"], [290, "GrayResponseUnit"], [297, "PageNumber"], [321, "HalftoneHints"], [322, "TileWidth"], [323, "TileLength"], [332, "InkSet"], [337, "TargetPrinter"], [18246, "Rating"], [18249, "RatingPercent"], [33550, "PixelScale"], [34264, "ModelTransform"], [34377, "PhotoshopSettings"], [50706, "DNGVersion"], [50707, "DNGBackwardVersion"], [50708, "UniqueCameraModel"], [50709, "LocalizedCameraModel"], [50736, "DNGLensInfo"], [50739, "ShadowScale"], [50740, "DNGPrivateData"], [33920, "IntergraphMatrix"], [33922, "ModelTiePoint"], [34118, "SEMInfo"], [34735, "GeoTiffDirectory"], [34736, "GeoTiffDoubleParams"], [34737, "GeoTiffAsciiParams"], [50341, "PrintIM"], [50721, "ColorMatrix1"], [50722, "ColorMatrix2"], [50723, "CameraCalibration1"], [50724, "CameraCalibration2"], [50725, "ReductionMatrix1"], [50726, "ReductionMatrix2"], [50727, "AnalogBalance"], [50728, "AsShotNeutral"], [50729, "AsShotWhiteXY"], [50730, "BaselineExposure"], [50731, "BaselineNoise"], [50732, "BaselineSharpness"], [50734, "LinearResponseLimit"], [50735, "CameraSerialNumber"], [50741, "MakerNoteSafety"], [50778, "CalibrationIlluminant1"], [50779, "CalibrationIlluminant2"], [50781, "RawDataUniqueID"], [50827, "OriginalRawFileName"], [50828, "OriginalRawFileData"], [50831, "AsShotICCProfile"], [50832, "AsShotPreProfileMatrix"], [50833, "CurrentICCProfile"], [50834, "CurrentPreProfileMatrix"], [50879, "ColorimetricReference"], [50885, "SRawType"], [50898, "PanasonicTitle"], [50899, "PanasonicTitle2"], [50931, "CameraCalibrationSig"], [50932, "ProfileCalibrationSig"], [50933, "ProfileIFD"], [50934, "AsShotProfileName"], [50936, "ProfileName"], [50937, "ProfileHueSatMapDims"], [50938, "ProfileHueSatMapData1"], [50939, "ProfileHueSatMapData2"], [50940, "ProfileToneCurve"], [50941, "ProfileEmbedPolicy"], [50942, "ProfileCopyright"], [50964, "ForwardMatrix1"], [50965, "ForwardMatrix2"], [50966, "PreviewApplicationName"], [50967, "PreviewApplicationVersion"], [50968, "PreviewSettingsName"], [50969, "PreviewSettingsDigest"], [50970, "PreviewColorSpace"], [50971, "PreviewDateTime"], [50972, "RawImageDigest"], [50973, "OriginalRawFileDigest"], [50981, "ProfileLookTableDims"], [50982, "ProfileLookTableData"], [51043, "TimeCodes"], [51044, "FrameRate"], [51058, "TStop"], [51081, "ReelName"], [51089, "OriginalDefaultFinalSize"], [51090, "OriginalBestQualitySize"], [51091, "OriginalDefaultCropSize"], [51105, "CameraLabel"], [51107, "ProfileHueSatMapEncoding"], [51108, "ProfileLookTableEncoding"], [51109, "BaselineExposureOffset"], [51110, "DefaultBlackRender"], [51111, "NewRawImageDigest"], [51112, "RawToPreviewGain"]]);
let At = [[273, "StripOffsets"], [279, "StripByteCounts"], [288, "FreeOffsets"], [289, "FreeByteCounts"], [291, "GrayResponseCurve"], [292, "T4Options"], [293, "T6Options"], [300, "ColorResponseUnit"], [320, "ColorMap"], [324, "TileOffsets"], [325, "TileByteCounts"], [326, "BadFaxLines"], [327, "CleanFaxData"], [328, "ConsecutiveBadFaxLines"], [330, "SubIFD"], [333, "InkNames"], [334, "NumberofInks"], [336, "DotRange"], [338, "ExtraSamples"], [339, "SampleFormat"], [340, "SMinSampleValue"], [341, "SMaxSampleValue"], [342, "TransferRange"], [343, "ClipPath"], [344, "XClipPathUnits"], [345, "YClipPathUnits"], [346, "Indexed"], [347, "JPEGTables"], [351, "OPIProxy"], [400, "GlobalParametersIFD"], [401, "ProfileType"], [402, "FaxProfile"], [403, "CodingMethods"], [404, "VersionYear"], [405, "ModeNumber"], [433, "Decode"], [434, "DefaultImageColor"], [435, "T82Options"], [437, "JPEGTables"], [512, "JPEGProc"], [515, "JPEGRestartInterval"], [517, "JPEGLosslessPredictors"], [518, "JPEGPointTransforms"], [519, "JPEGQTables"], [520, "JPEGDCTables"], [521, "JPEGACTables"], [559, "StripRowCounts"], [999, "USPTOMiscellaneous"], [18247, "XP_DIP_XML"], [18248, "StitchInfo"], [28672, "SonyRawFileType"], [28688, "SonyToneCurve"], [28721, "VignettingCorrection"], [28722, "VignettingCorrParams"], [28724, "ChromaticAberrationCorrection"], [28725, "ChromaticAberrationCorrParams"], [28726, "DistortionCorrection"], [28727, "DistortionCorrParams"], [29895, "SonyCropTopLeft"], [29896, "SonyCropSize"], [32781, "ImageID"], [32931, "WangTag1"], [32932, "WangAnnotation"], [32933, "WangTag3"], [32934, "WangTag4"], [32953, "ImageReferencePoints"], [32954, "RegionXformTackPoint"], [32955, "WarpQuadrilateral"], [32956, "AffineTransformMat"], [32995, "Matteing"], [32996, "DataType"], [32997, "ImageDepth"], [32998, "TileDepth"], [33300, "ImageFullWidth"], [33301, "ImageFullHeight"], [33302, "TextureFormat"], [33303, "WrapModes"], [33304, "FovCot"], [33305, "MatrixWorldToScreen"], [33306, "MatrixWorldToCamera"], [33405, "Model2"], [33421, "CFARepeatPatternDim"], [33422, "CFAPattern2"], [33423, "BatteryLevel"], [33424, "KodakIFD"], [33445, "MDFileTag"], [33446, "MDScalePixel"], [33447, "MDColorTable"], [33448, "MDLabName"], [33449, "MDSampleInfo"], [33450, "MDPrepDate"], [33451, "MDPrepTime"], [33452, "MDFileUnits"], [33589, "AdventScale"], [33590, "AdventRevision"], [33628, "UIC1Tag"], [33629, "UIC2Tag"], [33630, "UIC3Tag"], [33631, "UIC4Tag"], [33918, "IntergraphPacketData"], [33919, "IntergraphFlagRegisters"], [33921, "INGRReserved"], [34016, "Site"], [34017, "ColorSequence"], [34018, "IT8Header"], [34019, "RasterPadding"], [34020, "BitsPerRunLength"], [34021, "BitsPerExtendedRunLength"], [34022, "ColorTable"], [34023, "ImageColorIndicator"], [34024, "BackgroundColorIndicator"], [34025, "ImageColorValue"], [34026, "BackgroundColorValue"], [34027, "PixelIntensityRange"], [34028, "TransparencyIndicator"], [34029, "ColorCharacterization"], [34030, "HCUsage"], [34031, "TrapIndicator"], [34032, "CMYKEquivalent"], [34152, "AFCP_IPTC"], [34232, "PixelMagicJBIGOptions"], [34263, "JPLCartoIFD"], [34306, "WB_GRGBLevels"], [34310, "LeafData"], [34687, "TIFF_FXExtensions"], [34688, "MultiProfiles"], [34689, "SharedData"], [34690, "T88Options"], [34732, "ImageLayer"], [34750, "JBIGOptions"], [34856, "Opto-ElectricConvFactor"], [34857, "Interlace"], [34908, "FaxRecvParams"], [34909, "FaxSubAddress"], [34910, "FaxRecvTime"], [34929, "FedexEDR"], [34954, "LeafSubIFD"], [37387, "FlashEnergy"], [37388, "SpatialFrequencyResponse"], [37389, "Noise"], [37390, "FocalPlaneXResolution"], [37391, "FocalPlaneYResolution"], [37392, "FocalPlaneResolutionUnit"], [37397, "ExposureIndex"], [37398, "TIFF-EPStandardID"], [37399, "SensingMethod"], [37434, "CIP3DataFile"], [37435, "CIP3Sheet"], [37436, "CIP3Side"], [37439, "StoNits"], [37679, "MSDocumentText"], [37680, "MSPropertySetStorage"], [37681, "MSDocumentTextPosition"], [37724, "ImageSourceData"], [40965, "InteropIFD"], [40976, "SamsungRawPointersOffset"], [40977, "SamsungRawPointersLength"], [41217, "SamsungRawByteOrder"], [41218, "SamsungRawUnknown"], [41484, "SpatialFrequencyResponse"], [41485, "Noise"], [41489, "ImageNumber"], [41490, "SecurityClassification"], [41491, "ImageHistory"], [41494, "TIFF-EPStandardID"], [41995, "DeviceSettingDescription"], [42112, "GDALMetadata"], [42113, "GDALNoData"], [44992, "ExpandSoftware"], [44993, "ExpandLens"], [44994, "ExpandFilm"], [44995, "ExpandFilterLens"], [44996, "ExpandScanner"], [44997, "ExpandFlashLamp"], [46275, "HasselbladRawImage"], [48129, "PixelFormat"], [48130, "Transformation"], [48131, "Uncompressed"], [48132, "ImageType"], [48256, "ImageWidth"], [48257, "ImageHeight"], [48258, "WidthResolution"], [48259, "HeightResolution"], [48320, "ImageOffset"], [48321, "ImageByteCount"], [48322, "AlphaOffset"], [48323, "AlphaByteCount"], [48324, "ImageDataDiscard"], [48325, "AlphaDataDiscard"], [50215, "OceScanjobDesc"], [50216, "OceApplicationSelector"], [50217, "OceIDNumber"], [50218, "OceImageLogic"], [50255, "Annotations"], [50459, "HasselbladExif"], [50547, "OriginalFileName"], [50560, "USPTOOriginalContentType"], [50656, "CR2CFAPattern"], [50710, "CFAPlaneColor"], [50711, "CFALayout"], [50712, "LinearizationTable"], [50713, "BlackLevelRepeatDim"], [50714, "BlackLevel"], [50715, "BlackLevelDeltaH"], [50716, "BlackLevelDeltaV"], [50717, "WhiteLevel"], [50718, "DefaultScale"], [50719, "DefaultCropOrigin"], [50720, "DefaultCropSize"], [50733, "BayerGreenSplit"], [50737, "ChromaBlurRadius"], [50738, "AntiAliasStrength"], [50752, "RawImageSegmentation"], [50780, "BestQualityScale"], [50784, "AliasLayerMetadata"], [50829, "ActiveArea"], [50830, "MaskedAreas"], [50935, "NoiseReductionApplied"], [50974, "SubTileBlockSize"], [50975, "RowInterleaveFactor"], [51008, "OpcodeList1"], [51009, "OpcodeList2"], [51022, "OpcodeList3"], [51041, "NoiseProfile"], [51114, "CacheVersion"], [51125, "DefaultUserCrop"], [51157, "NikonNEFInfo"], [65024, "KdcIFD"]];
E(N, "ifd0", At), E(N, "exif", At), B(G, "gps", [[23, { M: "Magnetic North", T: "True North" }], [25, { K: "Kilometers", M: "Miles", N: "Nautical Miles" }]]);
class Dt extends ge {
static canHandle(e2, t2) {
return 224 === e2.getUint8(t2 + 1) && 1246120262 === e2.getUint32(t2 + 4) && 0 === e2.getUint8(t2 + 8);
}
parse() {
return this.parseTags(), this.translate(), this.output;
}
parseTags() {
this.raw = /* @__PURE__ */ new Map([[0, this.chunk.getUint16(0)], [2, this.chunk.getUint8(2)], [3, this.chunk.getUint16(3)], [5, this.chunk.getUint16(5)], [7, this.chunk.getUint8(7)], [8, this.chunk.getUint8(8)]]);
}
}
f(Dt, "type", "jfif"), f(Dt, "headerLength", 9), A.set("jfif", Dt), B(N, "jfif", [[0, "JFIFVersion"], [2, "ResolutionUnit"], [3, "XResolution"], [5, "YResolution"], [7, "ThumbnailWidth"], [8, "ThumbnailHeight"]]);
class Ot extends ge {
parse() {
return this.parseTags(), this.translate(), this.output;
}
parseTags() {
this.raw = new Map([[0, this.chunk.getUint32(0)], [4, this.chunk.getUint32(4)], [8, this.chunk.getUint8(8)], [9, this.chunk.getUint8(9)], [10, this.chunk.getUint8(10)], [11, this.chunk.getUint8(11)], [12, this.chunk.getUint8(12)], ...Array.from(this.raw)]);
}
}
f(Ot, "type", "ihdr"), A.set("ihdr", Ot), B(N, "ihdr", [[0, "ImageWidth"], [4, "ImageHeight"], [8, "BitDepth"], [9, "ColorType"], [10, "Compression"], [11, "Filter"], [12, "Interlace"]]), B(G, "ihdr", [[9, { 0: "Grayscale", 2: "RGB", 3: "Palette", 4: "Grayscale with Alpha", 6: "RGB with Alpha", DEFAULT: "Unknown" }], [10, { 0: "Deflate/Inflate", DEFAULT: "Unknown" }], [11, { 0: "Adaptive", DEFAULT: "Unknown" }], [12, { 0: "Noninterlaced", 1: "Adam7 Interlace", DEFAULT: "Unknown" }]]);
const xt = "\0\0\0\0";
class vt extends ge {
static canHandle(e2, t2) {
return 226 === e2.getUint8(t2 + 1) && 1229144927 === e2.getUint32(t2 + 4);
}
static findPosition(e2, t2) {
let i2 = super.findPosition(e2, t2);
return i2.chunkNumber = e2.getUint8(t2 + 16), i2.chunkCount = e2.getUint8(t2 + 17), i2.multiSegment = i2.chunkCount > 1, i2;
}
static handleMultiSegments(e2) {
return (function(e3) {
let t2 = (function(e4) {
let t3 = e4[0].constructor, i2 = 0;
for (let t4 of e4) i2 += t4.length;
let n2 = new t3(i2), s2 = 0;
for (let t4 of e4) n2.set(t4, s2), s2 += t4.length;
return n2;
})(e3.map(((e4) => e4.chunk.toUint8())));
return new I(t2);
})(e2);
}
parse() {
return this.raw = /* @__PURE__ */ new Map(), this.parseHeader(), this.parseTags(), this.translate(), this.output;
}
parseHeader() {
let { raw: e2 } = this;
this.chunk.byteLength < 84 && m("ICC header is too short");
for (let [t2, i2] of Object.entries(Mt)) {
t2 = parseInt(t2, 10);
let n2 = i2(this.chunk, t2);
n2 !== xt && e2.set(t2, n2);
}
}
parseTags() {
let e2, t2, i2, n2, s2, { raw: r2 } = this, a2 = this.chunk.getUint32(128), o2 = 132, l2 = this.chunk.byteLength;
for (; a2--; ) {
if (e2 = this.chunk.getString(o2, 4), t2 = this.chunk.getUint32(o2 + 4), i2 = this.chunk.getUint32(o2 + 8), n2 = this.chunk.getString(t2, 4), t2 + i2 > l2) return void console.warn("reached the end of the first ICC chunk. Enable options.tiff.multiSegment to read all ICC segments.");
s2 = this.parseTag(n2, t2, i2), void 0 !== s2 && s2 !== xt && r2.set(e2, s2), o2 += 12;
}
}
parseTag(e2, t2, i2) {
switch (e2) {
case "desc":
return this.parseDesc(t2);
case "mluc":
return this.parseMluc(t2);
case "text":
return this.parseText(t2, i2);
case "sig ":
return this.parseSig(t2);
}
if (!(t2 + i2 > this.chunk.byteLength)) return this.chunk.getUint8Array(t2, i2);
}
parseDesc(e2) {
let t2 = this.chunk.getUint32(e2 + 8) - 1;
return S(this.chunk.getString(e2 + 12, t2));
}
parseText(e2, t2) {
return S(this.chunk.getString(e2 + 8, t2 - 8));
}
parseSig(e2) {
return S(this.chunk.getString(e2 + 8, 4));
}
parseMluc(e2) {
let { chunk: t2 } = this, i2 = t2.getUint32(e2 + 8), n2 = t2.getUint32(e2 + 12), s2 = e2 + 16, r2 = [];
for (let a2 = 0; a2 < i2; a2++) {
let i3 = t2.getString(s2 + 0, 2), a3 = t2.getString(s2 + 2, 2), o2 = t2.getUint32(s2 + 4), l2 = t2.getUint32(s2 + 8) + e2, h2 = S(t2.getUnicodeString(l2, o2));
r2.push({ lang: i3, country: a3, text: h2 }), s2 += n2;
}
return 1 === i2 ? r2[0].text : r2;
}
translateValue(e2, t2) {
return "string" == typeof e2 ? t2[e2] || t2[e2.toLowerCase()] || e2 : t2[e2] || e2;
}
}
f(vt, "type", "icc"), f(vt, "multiSegment", true), f(vt, "headerLength", 18);
const Mt = { 4: Rt, 8: function(e2, t2) {
return [e2.getUint8(t2), e2.getUint8(t2 + 1) >> 4, e2.getUint8(t2 + 1) % 16].map(((e3) => e3.toString(10))).join(".");
}, 12: Rt, 16: Rt, 20: Rt, 24: function(e2, t2) {
const i2 = e2.getUint16(t2), n2 = e2.getUint16(t2 + 2) - 1, s2 = e2.getUint16(t2 + 4), r2 = e2.getUint16(t2 + 6), a2 = e2.getUint16(t2 + 8), o2 = e2.getUint16(t2 + 10);
return new Date(Date.UTC(i2, n2, s2, r2, a2, o2));
}, 36: Rt, 40: Rt, 48: Rt, 52: Rt, 64: (e2, t2) => e2.getUint32(t2), 80: Rt };
function Rt(e2, t2) {
return S(e2.getString(t2, 4));
}
A.set("icc", vt), B(N, "icc", [[4, "ProfileCMMType"], [8, "ProfileVersion"], [12, "ProfileClass"], [16, "ColorSpaceData"], [20, "ProfileConnectionSpace"], [24, "ProfileDateTime"], [36, "ProfileFileSignature"], [40, "PrimaryPlatform"], [44, "CMMFlags"], [48, "DeviceManufacturer"], [52, "DeviceModel"], [56, "DeviceAttributes"], [64, "RenderingIntent"], [68, "ConnectionSpaceIlluminant"], [80, "ProfileCreator"], [84, "ProfileID"], ["Header", "ProfileHeader"], ["MS00", "WCSProfiles"], ["bTRC", "BlueTRC"], ["bXYZ", "BlueMatrixColumn"], ["bfd", "UCRBG"], ["bkpt", "MediaBlackPoint"], ["calt", "CalibrationDateTime"], ["chad", "ChromaticAdaptation"], ["chrm", "Chromaticity"], ["ciis", "ColorimetricIntentImageState"], ["clot", "ColorantTableOut"], ["clro", "ColorantOrder"], ["clrt", "ColorantTable"], ["cprt", "ProfileCopyright"], ["crdi", "CRDInfo"], ["desc", "ProfileDescription"], ["devs", "DeviceSettings"], ["dmdd", "DeviceModelDesc"], ["dmnd", "DeviceMfgDesc"], ["dscm", "ProfileDescriptionML"], ["fpce", "FocalPlaneColorimetryEstimates"], ["gTRC", "GreenTRC"], ["gXYZ", "GreenMatrixColumn"], ["gamt", "Gamut"], ["kTRC", "GrayTRC"], ["lumi", "Luminance"], ["meas", "Measurement"], ["meta", "Metadata"], ["mmod", "MakeAndModel"], ["ncl2", "NamedColor2"], ["ncol", "NamedColor"], ["ndin", "NativeDisplayInfo"], ["pre0", "Preview0"], ["pre1", "Preview1"], ["pre2", "Preview2"], ["ps2i", "PS2RenderingIntent"], ["ps2s", "PostScript2CSA"], ["psd0", "PostScript2CRD0"], ["psd1", "PostScript2CRD1"], ["psd2", "PostScript2CRD2"], ["psd3", "PostScript2CRD3"], ["pseq", "ProfileSequenceDesc"], ["psid", "ProfileSequenceIdentifier"], ["psvm", "PS2CRDVMSize"], ["rTRC", "RedTRC"], ["rXYZ", "RedMatrixColumn"], ["resp", "OutputResponse"], ["rhoc", "ReflectionHardcopyOrigColorimetry"], ["rig0", "PerceptualRenderingIntentGamut"], ["rig2", "SaturationRenderingIntentGamut"], ["rpoc", "ReflectionPrintOutputColorimetry"], ["sape", "SceneAppearanceEstimates"], ["scoe", "SceneColorimetryEstimates"], ["scrd", "ScreeningDesc"], ["scrn", "Screening"], ["targ", "CharTarget"], ["tech", "Technology"], ["vcgt", "VideoCardGamma"], ["view", "ViewingConditions"], ["vued", "ViewingCondDesc"], ["wtpt", "MediaWhitePoint"]]);
const Lt = { "4d2p": "Erdt Systems", AAMA: "Aamazing Technologies", ACER: "Acer", ACLT: "Acolyte Color Research", ACTI: "Actix Sytems", ADAR: "Adara Technology", ADBE: "Adobe", ADI: "ADI Systems", AGFA: "Agfa Graphics", ALMD: "Alps Electric", ALPS: "Alps Electric", ALWN: "Alwan Color Expertise", AMTI: "Amiable Technologies", AOC: "AOC International", APAG: "Apago", APPL: "Apple Computer", AST: "AST", "AT&T": "AT&T", BAEL: "BARBIERI electronic", BRCO: "Barco NV", BRKP: "Breakpoint", BROT: "Brother", BULL: "Bull", BUS: "Bus Computer Systems", "C-IT": "C-Itoh", CAMR: "Intel", CANO: "Canon", CARR: "Carroll Touch", CASI: "Casio", CBUS: "Colorbus PL", CEL: "Crossfield", CELx: "Crossfield", CGS: "CGS Publishing Technologies International", CHM: "Rochester Robotics", CIGL: "Colour Imaging Group, London", CITI: "Citizen", CL00: "Candela", CLIQ: "Color IQ", CMCO: "Chromaco", CMiX: "CHROMiX", COLO: "Colorgraphic Communications", COMP: "Compaq", COMp: "Compeq/Focus Technology", CONR: "Conrac Display Products", CORD: "Cordata Technologies", CPQ: "Compaq", CPRO: "ColorPro", CRN: "Cornerstone", CTX: "CTX International", CVIS: "ColorVision", CWC: "Fujitsu Laboratories", DARI: "Darius Technology", DATA: "Dataproducts", DCP: "Dry Creek Photo", DCRC: "Digital Contents Resource Center, Chung-Ang University", DELL: "Dell Computer", DIC: "Dainippon Ink and Chemicals", DICO: "Diconix", DIGI: "Digital", "DL&C": "Digital Light & Color", DPLG: "Doppelganger", DS: "Dainippon Screen", DSOL: "DOOSOL", DUPN: "DuPont", EPSO: "Epson", ESKO: "Esko-Graphics", ETRI: "Electronics and Telecommunications Research Institute", EVER: "Everex Systems", EXAC: "ExactCODE", Eizo: "Eizo", FALC: "Falco Data Products", FF: "Fuji Photo Film", FFEI: "FujiFilm Electronic Imaging", FNRD: "Fnord Software", FORA: "Fora", FORE: "Forefront Technology", FP: "Fujitsu", FPA: "WayTech Development", FUJI: "Fujitsu", FX: "Fuji Xerox", GCC: "GCC Technologies", GGSL: "Global Graphics Software", GMB: "Gretagmacbeth", GMG: "GMG", GOLD: "GoldStar Technology", GOOG: "Google", GPRT: "Giantprint", GTMB: "Gretagmacbeth", GVC: "WayTech Development", GW2K: "Sony", HCI: "HCI", HDM: "Heidelberger Druckmaschinen", HERM: "Hermes", HITA: "Hitachi America", HP: "Hewlett-Packard", HTC: "Hitachi", HiTi: "HiTi Digital", IBM: "IBM", IDNT: "Scitex", IEC: "Hewlett-Packard", IIYA: "Iiyama North America", IKEG: "Ikegami Electronics", IMAG: "Image Systems", IMI: "Ingram Micro", INTC: "Intel", INTL: "N/A (INTL)", INTR: "Intra Electronics", IOCO: "Iocomm International Technology", IPS: "InfoPrint Solutions Company", IRIS: "Scitex", ISL: "Ichikawa Soft Laboratory", ITNL: "N/A (ITNL)", IVM: "IVM", IWAT: "Iwatsu Electric", Idnt: "Scitex", Inca: "Inca Digital Printers", Iris: "Scitex", JPEG: "Joint Photographic Experts Group", JSFT: "Jetsoft Development", JVC: "JVC Information Products", KART: "Scitex", KFC: "KFC Computek Components", KLH: "KLH Computers", KMHD: "Konica Minolta", KNCA: "Konica", KODA: "Kodak", KYOC: "Kyocera", Kart: "Scitex", LCAG: "Leica", LCCD: "Leeds Colour", LDAK: "Left Dakota", LEAD: "Leading Technology", LEXM: "Lexmark International", LINK: "Link Computer", LINO: "Linotronic", LITE: "Lite-On", Leaf: "Leaf", Lino: "Linotronic", MAGC: "Mag Computronic", MAGI: "MAG Innovision", MANN: "Mannesmann", MICN: "Micron Technology", MICR: "Microtek", MICV: "Microvitec", MINO: "Minolta", MITS: "Mitsubishi Electronics America", MITs: "Mitsuba", MNLT: "Minolta", MODG: "Modgraph", MONI: "Monitronix", MONS: "Monaco Systems", MORS: "Morse Technology", MOTI: "Motive Systems", MSFT: "Microsoft", MUTO: "MUTOH INDUSTRIES", Mits: "Mitsubishi Electric", NANA: "NANAO", NEC: "NEC", NEXP: "NexPress Solutions", NISS: "Nissei Sangyo America", NKON: "Nikon", NONE: "none", OCE: "Oce Technologies", OCEC: "OceColor", OKI: "Oki", OKID: "Okidata", OKIP: "Okidata", OLIV: "Olivetti", OLYM: "Olympus", ONYX: "Onyx Graphics", OPTI: "Optiquest", PACK: "Packard Bell", PANA: "Matsushita Electric Industrial", PANT: "Pantone", PBN: "Packard Bell", PFU: "PFU", PHIL: "Philips Consumer Electronics", PNTX: "HOYA", POne: "Phase One A/S", PREM: "Premier Computer Innovations", PRIN: "Princeton Graphic Systems", PRIP: "Princeton Publishing Labs", QLUX: "Hong Kong", QMS: "QMS", QPCD: "QPcard AB", QUAD: "QuadLaser", QUME: "Qume", RADI: "Radius", RDDx: "Integrated Color Solutions", RDG: "Roland DG", REDM: "REDMS Group", RELI: "Relisys", RGMS: "Rolf Gierling Multitools", RICO: "Ricoh", RNLD: "Edmund Ronald", ROYA: "Royal", RPC: "Ricoh Printing Systems", RTL: "Royal Information Electronics", SAMP: "Sampo", SAMS: "Samsung", SANT: "Jaime Santana Pomares", SCIT: "Scitex", SCRN: "Dainippon Screen", SDP: "Scitex", SEC: "Samsung", SEIK: "Seiko Instruments", SEIk: "Seikosha", SGUY: "ScanGuy.com", SHAR: "Sharp Laboratories", SICC: "International Color Consortium", SONY: "Sony", SPCL: "SpectraCal", STAR: "Star", STC: "Sampo Technology", Scit: "Scitex", Sdp: "Scitex", Sony: "Sony", TALO: "Talon Technology", TAND: "Tandy", TATU: "Tatung", TAXA: "TAXAN America", TDS: "Tokyo Denshi Sekei", TECO: "TECO Information Systems", TEGR: "Tegra", TEKT: "Tektronix", TI: "Texas Instruments", TMKR: "TypeMaker", TOSB: "Toshiba", TOSH: "Toshiba", TOTK: "TOTOKU ELECTRIC", TRIU: "Triumph", TSBT: "Toshiba", TTX: "TTX Computer Products", TVM: "TVM Professional Monitor", TW: "TW Casper", ULSX: "Ulead Systems", UNIS: "Unisys", UTZF: "Utz Fehlau & Sohn", VARI: "Varityper", VIEW: "Viewsonic", VISL: "Visual communication", VIVO: "Vivo Mobile Communication", WANG: "Wang", WLBR: "Wilbur Imaging", WTG2: "Ware To Go", WYSE: "WYSE Technology", XERX: "Xerox", XRIT: "X-Rite", ZRAN: "Zoran", Zebr: "Zebra Technologies", appl: "Apple Computer", bICC: "basICColor", berg: "bergdesign", ceyd: "Integrated Color Solutions", clsp: "MacDermid ColorSpan", ds: "Dainippon Screen", dupn: "DuPont", ffei: "FujiFilm Electronic Imaging", flux: "FluxData", iris: "Scitex", kart: "Scitex", lcms: "Little CMS", lino: "Linotronic", none: "none", ob4d: "Erdt Systems", obic: "Medigraph", quby: "Qubyx Sarl", scit: "Scitex", scrn: "Dainippon Screen", sdp: "Scitex", siwi: "SIWI GRAFIKA", yxym: "YxyMaster" }, Ut = { scnr: "Scanner", mntr: "Monitor", prtr: "Printer", link: "Device Link", abst: "Abstract", spac: "Color Space Conversion Profile", nmcl: "Named Color", cenc: "ColorEncodingSpace profile", mid: "MultiplexIdentification profile", mlnk: "MultiplexLink profile", mvis: "MultiplexVisualization profile", nkpf: "Nikon Input Device Profile (NON-STANDARD!)" };
B(G, "icc", [[4, Lt], [12, Ut], [40, Object.assign({}, Lt, Ut)], [48, Lt], [80, Lt], [64, { 0: "Perceptual", 1: "Relative Colorimetric", 2: "Saturation", 3: "Absolute Colorimetric" }], ["tech", { amd: "Active Matrix Display", crt: "Cathode Ray Tube Display", kpcd: "Photo CD", pmd: "Passive Matrix Display", dcam: "Digital Camera", dcpj: "Digital Cinema Projector", dmpc: "Digital Motion Picture Camera", dsub: "Dye Sublimation Printer", epho: "Electrophotographic Printer", esta: "Electrostatic Printer", flex: "Flexography", fprn: "Film Writer", fscn: "Film Scanner", grav: "Gravure", ijet: "Ink Jet Printer", imgs: "Photo Image Setter", mpfr: "Motion Picture Film Recorder", mpfs: "Motion Picture Film Scanner", offs: "Offset Lithography", pjtv: "Projection Television", rpho: "Photographic Paper Printer", rscn: "Reflective Scanner", silk: "Silkscreen", twax: "Thermal Wax Printer", vidc: "Video Camera", vidm: "Video Monitor" }]]);
class Ft extends ge {
static canHandle(e2, t2, i2) {
return 237 === e2.getUint8(t2 + 1) && "Photoshop" === e2.getString(t2 + 4, 9) && void 0 !== this.containsIptc8bim(e2, t2, i2);
}
static headerLength(e2, t2, i2) {
let n2, s2 = this.containsIptc8bim(e2, t2, i2);
if (void 0 !== s2) return n2 = e2.getUint8(t2 + s2 + 7), n2 % 2 != 0 && (n2 += 1), 0 === n2 && (n2 = 4), s2 + 8 + n2;
}
static containsIptc8bim(e2, t2, i2) {
for (let n2 = 0; n2 < i2; n2++) if (this.isIptcSegmentHead(e2, t2 + n2)) return n2;
}
static isIptcSegmentHead(e2, t2) {
return 56 === e2.getUint8(t2) && 943868237 === e2.getUint32(t2) && 1028 === e2.getUint16(t2 + 4);
}
parse() {
let { raw: e2 } = this, t2 = this.chunk.byteLength - 1, i2 = false;
for (let n2 = 0; n2 < t2; n2++) if (28 === this.chunk.getUint8(n2) && 2 === this.chunk.getUint8(n2 + 1)) {
i2 = true;
let t3 = this.chunk.getUint16(n2 + 3), s2 = this.chunk.getUint8(n2 + 2), r2 = this.chunk.getLatin1String(n2 + 5, t3);
e2.set(s2, this.pluralizeValue(e2.get(s2), r2)), n2 += 4 + t3;
} else if (i2) break;
return this.translate(), this.output;
}
pluralizeValue(e2, t2) {
return void 0 !== e2 ? e2 instanceof Array ? (e2.push(t2), e2) : [e2, t2] : t2;
}
}
f(Ft, "type", "iptc"), f(Ft, "translateValues", false), f(Ft, "reviveValues", false), A.set("iptc", Ft), B(N, "iptc", [[0, "ApplicationRecordVersion"], [3, "ObjectTypeReference"], [4, "ObjectAttributeReference"], [5, "ObjectName"], [7, "EditStatus"], [8, "EditorialUpdate"], [10, "Urgency"], [12, "SubjectReference"], [15, "Category"], [20, "SupplementalCategories"], [22, "FixtureIdentifier"], [25, "Keywords"], [26, "ContentLocationCode"], [27, "ContentLocationName"], [30, "ReleaseDate"], [35, "ReleaseTime"], [37, "ExpirationDate"], [38, "ExpirationTime"], [40, "SpecialInstructions"], [42, "ActionAdvised"], [45, "ReferenceService"], [47, "ReferenceDate"], [50, "ReferenceNumber"], [55, "DateCreated"], [60, "TimeCreated"], [62, "DigitalCreationDate"], [63, "DigitalCreationTime"], [65, "OriginatingProgram"], [70, "ProgramVersion"], [75, "ObjectCycle"], [80, "Byline"], [85, "BylineTitle"], [90, "City"], [92, "Sublocation"], [95, "State"], [100, "CountryCode"], [101, "Country"], [103, "OriginalTransmissionReference"], [105, "Headline"], [110, "Credit"], [115, "Source"], [116, "CopyrightNotice"], [118, "Contact"], [120, "Caption"], [121, "LocalCaption"], [122, "Writer"], [125, "RasterizedCaption"], [130, "ImageType"], [131, "ImageOrientation"], [135, "LanguageIdentifier"], [150, "AudioType"], [151, "AudioSamplingRate"], [152, "AudioSamplingResolution"], [153, "AudioDuration"], [154, "AudioOutcue"], [184, "JobID"], [185, "MasterDocumentID"], [186, "ShortDocumentID"], [187, "UniqueDocumentID"], [188, "OwnerID"], [200, "ObjectPreviewFileFormat"], [201, "ObjectPreviewFileVersion"], [202, "ObjectPreviewData"], [221, "Prefs"], [225, "ClassifyState"], [228, "SimilarityIndex"], [230, "DocumentNotes"], [231, "DocumentHistory"], [232, "ExifCameraInfo"], [255, "CatalogSets"]]), B(G, "iptc", [[10, { 0: "0 (reserved)", 1: "1 (most urgent)", 2: "2", 3: "3", 4: "4", 5: "5 (normal urgency)", 6: "6", 7: "7", 8: "8 (least urgent)", 9: "9 (user-defined priority)" }], [75, { a: "Morning", b: "Both Morning and Evening", p: "Evening" }], [131, { L: "Landscape", P: "Portrait", S: "Square" }]]), e.Exifr = ce, e.Options = oe, e.allFormatters = ie, e.chunkedProps = $, e.createDictionary = B, e.default = ft, e.extendDictionary = E, e.fetchUrlAsArrayBuffer = L, e.fileParsers = T, e.fileReaders = D, e.gps = De, e.gpsOnlyOptions = Ae, e.inheritables = te, e.orientation = Re, e.orientationOnlyOptions = Me, e.otherSegments = J, e.parse = fe, e.readBlobAsArrayBuffer = U, e.rotation = Ue, e.rotations = Le, e.segmentParsers = A, e.segments = q, e.segmentsAndBlocks = Z, e.sidecar = async function(e2, t2, i2) {
let n2 = new oe(t2);
n2.chunked = false, void 0 === i2 && "string" == typeof e2 && (i2 = (function(e3) {
let t3 = e3.toLowerCase().split(".").pop();
if (/* @__PURE__ */ (function(e4) {
return "exif" === e4 || "tiff" === e4 || "tif" === e4;
})(t3)) return "tiff";
if (dt.includes(t3)) return t3;
})(e2));
let s2 = await x(e2, n2);
if (i2) {
if (dt.includes(i2)) return gt(i2, s2, n2);
m("Invalid segment type");
} else {
if ((function(e3) {
let t3 = e3.getString(0, 50).trim();
return t3.includes("<?xpacket") || t3.includes("<x:");
})(s2)) return gt("xmp", s2, n2);
for (let [e3] of A) {
if (!dt.includes(e3)) continue;
let t3 = await gt(e3, s2, n2).catch(pt);
if (t3) return t3;
}
m("Unknown file format");
}
}, e.tagKeys = N, e.tagRevivers = V, e.tagValues = G, e.thumbnail = xe, e.thumbnailOnlyOptions = Oe, e.thumbnailUrl = ve, e.tiffBlocks = Q, e.tiffExtractables = ee, Object.defineProperty(e, "__esModule", { value: true });
}));
}
});
// src/helpers/pluginMeta.ts
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
function getModuleDir() {
try {
return path.dirname(fileURLToPath(import.meta.url));
} catch {
return process.cwd();
}
}
function readJsonFile(filePath) {
try {
const raw = fs.readFileSync(filePath, "utf8");
return JSON.parse(raw);
} catch {
return null;
}
}
function findUpwards(startDir, fileName, maxDepth = 8) {
let dir = startDir;
for (let i = 0; i < maxDepth; i++) {
const candidate = path.join(dir, fileName);
if (fs.existsSync(candidate)) return candidate;
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
return null;
}
function getPluginMeta() {
const moduleDir = getModuleDir();
const packageJsonPath = findUpwards(moduleDir, "package.json");
const manifestJsonPath = findUpwards(moduleDir, "manifest.json");
const packageJson = packageJsonPath ? readJsonFile(packageJsonPath) : null;
const manifestJson = manifestJsonPath ? readJsonFile(manifestJsonPath) : null;
const version = String(packageJson?.version || "unknown");
const owner = String(manifestJson?.owner || "").trim();
const name = String(manifestJson?.name || "").trim();
const revisionsUrl = owner && name ? `https://raw.githubusercontent.com/${owner}/${name}-docs/main/docs/CHANGELOG.md` : "https://raw.githubusercontent.com";
const pluginIdentifier = owner && name ? `${owner}/${name}` : name ? name : "unknown";
return { version, owner, name, revisionsUrl, pluginIdentifier };
}
function formatToolMetaBlock(meta = getPluginMeta()) {
return `Plugin-Identifier: ${meta.pluginIdentifier}
Plugin version: ${meta.version}`;
}
// src/services/defaultParamsDrawThingsTxt2Img.ts
var defaultParams = {
aesthetic_score: 6.5,
batch_count: 1,
batch_size: 1,
causal_inference: 0,
causal_inference_pad: 0,
cfg_zero_init_steps: 1,
cfg_zero_star: false,
clip_l_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
clip_skip: 1,
clip_weight: 1,
controls: [],
crop_left: 0,
crop_top: 0,
fps: 25,
guidance_embed: 1,
guidance_scale: 1,
guiding_frame_noise: 0.019999999552965164,
height: 1024,
hires_fix: false,
hires_fix_height: 512,
hires_fix_strength: 0.4000000059604645,
hires_fix_width: 384,
image_guidance: 1.5,
image_prior_steps: 5,
loras: [],
mask_blur: 1.5,
mask_blur_outset: 0,
model: "z_image_turbo_1.0_q6p.ckpt",
motion_scale: 127,
negative_aesthetic_score: 0,
// negative_original_height: 512, negative_original_width: 512,
negative_prompt: "",
negative_prompt_for_image_prior: true,
num_frames: 1,
open_clip_g_text: "Could this be it, or not, I am not sure really.",
// original_height: 768, original_width: 576,
preserve_original_after_inpaint: true,
prompt: "3d fluffy llama, closeup cute and adorable, cute big circular reflective eyes, long fuzzy fur, pixar render, unreal engine cinematic smooth, intricate detail, cinematic",
refiner_model: null,
refiner_start: 0.4000000059604645,
resolution_dependent_shift: true,
sampler: "UniPC Trailing",
seed: 175308301,
seed_mode: "Scale Alike",
separate_clip_l: false,
separate_open_clip_g: false,
separate_t5: false,
sharpness: 0,
shift: 3,
speed_up_with_guidance_embed: true,
stage_2_guidance: 1,
stage_2_shift: 1,
start_frame_guidance: 1.2000000476837158,
steps: 8,
stochastic_sampling_gamma: 0.3,
strength: 1,
t5_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
t5_text_encoder_decoding: true,
// target_height: 768, target_width: 576,
tea_cache: false,
tea_cache_end: 100,
tea_cache_max_skip_steps: 3,
tea_cache_start: 5,
tea_cache_threshold: 0.20000000298023224,
tiled_decoding: true,
tiled_diffusion: false,
upscaler: null,
upscaler_scale: 0,
width: 768,
zero_negative_prompt: false
};
var generateRuntimeDefaults = {
saveOriginal: true,
previewInChat: true
};
var engineConnectionDefaults = {
transport: "auto",
http: {
baseUrl: "http://127.0.0.1:7860",
host: "127.0.0.1",
port: 7860
},
grpc: {
target: "127.0.0.1:7859",
service: "ImageGenerationService",
compression: "identity",
acceptEncoding: "",
protoPath: void 0
},
sharedSecret: null
};
function getEngineConnectionDefaults(overrides) {
const host = overrides?.host || engineConnectionDefaults.http.host;
const httpPort = overrides?.httpPort || engineConnectionDefaults.http.port;
const grpcPort = overrides?.grpcPort || parseInt(engineConnectionDefaults.grpc.target.split(":")[1], 10);
return {
...engineConnectionDefaults,
http: {
...engineConnectionDefaults.http,
baseUrl: `http://${host}:${httpPort}`,
host,
port: httpPort
},
grpc: {
...engineConnectionDefaults.grpc,
target: `${host}:${grpcPort}`
}
};
}
// src/services/drawthingsLimits.ts
var drawthingsLimits = {
// Limits for RENDERED output (requested_effective)
min: 256,
minDim: 256,
// Minimum dimension per side
maxWidth: 2048,
// Maximum render width
maxHeight: 2048,
// Maximum render height (note: was 2048 in old docs)
// Limits for INPUT images (adjusted) - Canvas & Moodboard
targetSum: 2240,
// Sum constraint: width + height ≤ 2240 (image2image / edit)
targetSumZoom: 4096,
// Sum constraint for zoom profile input (Pass 2 canvas; tuned for SeedVR2)
targetSumRestore: 704,
// Source sum threshold below which restore-pass fires before zoom-in
targetSumHandover: 1344,
// Restore-pass output sum (Pass 1 -> Pass 2 handover point); decoupled from targetSum
align: 64,
// Dimensions must be multiples of 64
// Postprocessing when requested_raw exceeds render limits
upscaler: "4x_ultrasharp_f16.ckpt",
upscalerScaleFactor: 2,
// Upscale method used when _dt_needs_upscaler is true.
upscaleMethod: "zoom-pass",
// Minimum scale factor (max(rawW/adjW, rawH/adjH)) to trigger upscaling.
minUpscaleFactorUpscaler: 1.5,
minUpscaleFactorZoomPass: 1.5,
// Preview generation for ALL MediaTypes (attachment, variant, image, picture).
previewMaxSum: 1792,
previewQuality: 80,
previewFormat: "jpeg"
};
// src/services/defaultParamsDrawThingsImg2Img.ts
var defaultParamsImg2Img = {
aesthetic_score: 6.5,
batch_count: 1,
batch_size: 1,
causal_inference: 0,
causal_inference_pad: 0,
cfg_zero_init_steps: 1,
cfg_zero_star: false,
clip_l_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
clip_skip: 1,
clip_weight: 1,
controls: [],
crop_left: 0,
crop_top: 0,
fps: 5,
guidance_embed: 3.5,
guidance_scale: 1,
guiding_frame_noise: 0.02,
// Ensure size keys exist for filtering; service overwrites with actual PNG size
width: 768,
height: 1024,
hires_fix: false,
hires_fix_height: 512,
hires_fix_strength: 0.4,
// hires_fix_width: 384,
image_guidance: 1.5,
image_prior_steps: 5,
loras: [],
mask_blur: 1.5,
mask_blur_outset: 0,
model: "krea_2_turbo_q6p.ckpt",
motion_scale: 127,
negative_aesthetic_score: 0,
// negative_original_height: 512, negative_original_width: 512,
negative_prompt: "",
negative_prompt_for_image_prior: true,
num_frames: 1,
open_clip_g_text: "Could this be it, or not, I am not sure really.",
// original_height: 512, original_width: 512,
preserve_original_after_inpaint: true,
prompt: "",
refiner_model: null,
refiner_start: 0.4,
resolution_dependent_shift: true,
sampler: "Euler A Trailing",
seed: 175308301,
seed_mode: "Scale Alike",
separate_clip_l: false,
separate_open_clip_g: false,
separate_t5: false,
sharpness: 0,
shift: 3,
speed_up_with_guidance_embed: true,
stage_2_guidance: 1,
stage_2_shift: 1,
start_frame_guidance: 1.2,
steps: 8,
stochastic_sampling_gamma: 0.3,
strength: 0.925,
t5_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
t5_text_encoder_decoding: true,
// target_height: 512, target_width: 512,
tea_cache: false,
tea_cache_end: 100,
tea_cache_max_skip_steps: 3,
tea_cache_start: 5,
tea_cache_threshold: 0.2,
tiled_decoding: false,
tiled_diffusion: false,
upscaler: null,
upscaler_scale: 0,
zero_negative_prompt: false
};
// src/services/defaultParamsDrawThingsEdit.ts
var defaultParamsImg2Img2 = {
aesthetic_score: 6.5,
batch_count: 1,
batch_size: 1,
causal_inference: 0,
causal_inference_pad: 0,
cfg_zero_init_steps: 0,
cfg_zero_star: false,
clip_l_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
clip_skip: 1,
clip_weight: 1,
controls: [],
crop_left: 0,
crop_top: 0,
fps: 25,
guidance_embed: 1,
guidance_scale: 1,
guiding_frame_noise: 0.019999999552965164,
// Ensure size keys exist for filtering; service overwrites with actual PNG size
width: 768,
height: 1024,
hires_fix: false,
hires_fix_height: 512,
hires_fix_strength: 0.4000000059604645,
// hires_fix_width: 384,
image_guidance: 1.5,
image_prior_steps: 5,
loras: [],
mask_blur: 2.5,
mask_blur_outset: 0,
model: "flux_2_klein_9b_kv_q6p.ckpt",
motion_scale: 127,
negative_aesthetic_score: 0,
// negative_original_height: 512, negative_original_width: 512,
negative_prompt: "",
negative_prompt_for_image_prior: true,
num_frames: 1,
open_clip_g_text: "Could this be it, or not, I am not sure really.",
// original_height: 512, original_width: 512,
preserve_original_after_inpaint: true,
prompt: "",
refiner_model: null,
refiner_start: 0.4000000059604645,
resolution_dependent_shift: true,
sampler: "DDIM Trailing",
seed: 175308301,
seed_mode: "Scale Alike",
separate_clip_l: false,
separate_open_clip_g: false,
separate_t5: false,
sharpness: 0,
shift: 3,
speed_up_with_guidance_embed: true,
stage_2_guidance: 1,
stage_2_shift: 1,
start_frame_guidance: 1.2000000476837158,
steps: 12,
stochastic_sampling_gamma: 0.3,
strength: 1,
t5_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
t5_text_encoder_decoding: true,
// target_height: 512, target_width: 512,
tea_cache: false,
tea_cache_end: 100,
tea_cache_max_skip_steps: 3,
tea_cache_start: 5,
tea_cache_threshold: 0.20000000298023224,
tiled_decoding: false,
tiled_diffusion: false,
upscaler: null,
upscaler_scale: 0,
zero_negative_prompt: false
};
// src/services/defaultParamsDrawThingsText2Video.ts
var defaultParamsText2Video = {
aesthetic_score: 6,
batch_count: 1,
batch_size: 1,
causal_inference: 0,
causal_inference_pad: 0,
cfg_zero_init_steps: 0,
cfg_zero_star: false,
clip_l_text: "",
clip_skip: 1,
clip_weight: 1,
compression_artifacts: "h264",
compression_artifacts_quality: 43.1,
controls: [],
crop_left: 0,
crop_top: 0,
fps: 25,
guidance_embed: 3.5,
guidance_scale: 1,
guiding_frame_noise: 0.02,
height: 1024,
hires_fix: false,
hires_fix_height: 768,
hires_fix_strength: 0.7,
hires_fix_width: 576,
image_guidance: 1.5,
image_prior_steps: 5,
loras: [],
mask_blur: 1.5,
mask_blur_outset: 0,
model: "ltx_2.3_22b_distilled_1.1_q6p.ckpt",
motion_scale: 127,
negative_aesthetic_score: 2.5,
// negative_original_height: 512, negative_original_width: 512,
negative_prompt: "",
negative_prompt_for_image_prior: true,
num_frames: 65,
open_clip_g_text: "",
// original_height: 1024, original_width: 768,
preserve_original_after_inpaint: true,
prompt: "3d fluffy llama, closeup cute and adorable, cute big circular reflective eyes, long fuzzy fur, pixar render, unreal engine cinematic smooth, intricate detail, cinematic",
refiner_model: null,
refiner_start: 0.85,
resolution_dependent_shift: true,
sampler: "DDIM Trailing",
seed: 175308301,
seed_mode: "Scale Alike",
separate_clip_l: false,
separate_open_clip_g: false,
separate_t5: false,
sharpness: 0,
shift: 7,
speed_up_with_guidance_embed: true,
stage_2_guidance: 1,
stage_2_shift: 1,
start_frame_guidance: 1,
steps: 12,
stochastic_sampling_gamma: 0.3,
strength: 1,
t5_text: "",
t5_text_encoder_decoding: true,
// target_height: 1024, target_width: 768,
tea_cache: false,
tea_cache_end: 100,
tea_cache_max_skip_steps: 3,
tea_cache_start: 5,
tea_cache_threshold: 0.06,
tiled_decoding: false,
tiled_diffusion: false,
upscaler: null,
upscaler_scale: 0,
width: 768,
zero_negative_prompt: false
};
// src/services/defaultParamsDrawThingsImage2Video.ts
var defaultParamsImage2Video = {
aesthetic_score: 6,
batch_count: 1,
batch_size: 1,
causal_inference: 0,
causal_inference_pad: 0,
cfg_zero_init_steps: 0,
cfg_zero_star: false,
clip_l_text: "",
clip_skip: 1,
clip_weight: 1,
compression_artifacts: "h264",
compression_artifacts_quality: 43.1,
controls: [],
crop_left: 0,
crop_top: 0,
fps: 25,
guidance_embed: 3.5,
guidance_scale: 1,
guiding_frame_noise: 0.02,
// Ensure size keys exist for filtering; service overwrites with actual PNG size
width: 768,
height: 1024,
hires_fix: false,
hires_fix_height: 768,
hires_fix_strength: 0.7,
// hires_fix_width: 576,
image_guidance: 1.5,
image_prior_steps: 5,
loras: [],
mask_blur: 1.5,
mask_blur_outset: 0,
model: "ltx_2.3_22b_distilled_1.1_q6p.ckpt",
motion_scale: 127,
negative_aesthetic_score: 2.5,
// negative_original_height: 512, negative_original_width: 512,
negative_prompt: "",
negative_prompt_for_image_prior: true,
num_frames: 65,
open_clip_g_text: "",
// original_height: 512, original_width: 512,
preserve_original_after_inpaint: true,
prompt: "",
refiner_model: null,
refiner_start: 0.85,
resolution_dependent_shift: true,
sampler: "DDIM Trailing",
seed: 175308301,
seed_mode: "Scale Alike",
separate_clip_l: false,
separate_open_clip_g: false,
separate_t5: false,
sharpness: 0,
shift: 7,
speed_up_with_guidance_embed: true,
stage_2_guidance: 1,
stage_2_shift: 1,
start_frame_guidance: 1,
steps: 8,
stochastic_sampling_gamma: 0.3,
strength: 1,
t5_text: "",
t5_text_encoder_decoding: true,
// target_height: 512, target_width: 512,
tea_cache: false,
tea_cache_end: 100,
tea_cache_max_skip_steps: 3,
tea_cache_start: 5,
tea_cache_threshold: 0.06,
tiled_decoding: false,
tiled_diffusion: false,
upscaler: null,
upscaler_scale: 0,
zero_negative_prompt: false
};
// src/services/flux2_9bParamsDrawThings.ts
var flux2_9bOverlays = {
txt2img: {
model: "flux_2_klein_9b_kv_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 6,
resolution_dependent_shift: false,
shift: 6,
sharpness: 0,
strength: 1,
mask_blur: 2.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
},
img2img: {
model: "flux_2_klein_9b_kv_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 6,
resolution_dependent_shift: false,
shift: 6,
sharpness: 0,
strength: 0.925,
mask_blur: 2.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
},
edit: {
maxReferenceImages: 4,
model: "flux_2_klein_9b_kv_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 12,
resolution_dependent_shift: true,
shift: 6,
sharpness: 0,
strength: 1,
mask_blur: 2.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
}
};
// src/services/flux3ParamsDrawThings.ts
var flux3Overlays = {
txt2img: {
model: "flux_3_klein_f16.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 16,
resolution_dependent_shift: false,
shift: 16,
sharpness: 0,
strength: 1,
mask_blur: 2.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
},
img2img: null,
edit: {
maxReferenceImages: 10,
model: "flux_3_klein_f16.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 16,
resolution_dependent_shift: false,
shift: 16,
sharpness: 0,
strength: 1,
mask_blur: 2.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
}
};
// src/services/krea_2ParamsDrawThings.ts
var krea_2Overlays = {
txt2img: {
model: "krea_2_turbo_q6p.ckpt",
guidance_scale: 1,
sampler: "Euler A Trailing",
steps: 8,
shift: 3,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
},
img2img: {
model: "krea_2_turbo_q6p.ckpt",
guidance_scale: 1,
sampler: "Euler A Trailing",
steps: 8,
shift: 3,
sharpness: 0,
strength: 0.925,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
}
};
// src/services/ltx2_3ParamsDrawThings.ts
var ltx2_3Overlays = {
txt2vid: {
model: "ltx_2.3_22b_distilled_1.1_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 12,
shift: 7,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [],
compression_artifacts: "h264",
compression_artifacts_quality: 43.1
},
img2vid: {
maxReferenceImages: 1,
model: "ltx_2.3_22b_distilled_1.1_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 12,
shift: 7,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [],
compression_artifacts: "h264",
compression_artifacts_quality: 43.1
}
};
// src/services/minimax_h3ParamsDrawThings.ts
var minimax_h3Overlays = {
txt2vid: {
model: "minimax_h3_fl2va_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 8,
shift: 12,
shift_for_audio: 3,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [
{
mode: "all",
file: "minimax_h3_fl2v_turbo_4step_v1.2_768p_comfyui_bf16_lora_f16.ckpt",
weight: 0.9
}
],
compression_artifacts: "h264",
compression_artifacts_quality: 43.1,
tiled_decoding: true,
decoding_tile_height: 256,
decoding_tile_overlap: 64,
decoding_tile_width: 256
},
img2vid: {
maxReferenceImages: 2,
model: "minimax_h3_fl2va_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 8,
shift: 12,
shift_for_audio: 3,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [
{
mode: "all",
file: "minimax_h3_fl2v_turbo_4step_v1.2_768p_comfyui_bf16_lora_f16.ckpt",
weight: 0.9
}
],
compression_artifacts: "h264",
compression_artifacts_quality: 43.1,
tiled_decoding: true,
decoding_tile_height: 256,
decoding_tile_overlap: 64,
decoding_tile_width: 256
}
};
// src/services/minimax_h3_ref2vaParamsDrawThings.ts
var minimax_h3_ref2vaOverlays = {
txt2vid: {
model: "minimax_h3_ref2va_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 10,
shift: 12,
shift_for_audio: 3,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [
{
mode: "all",
file: "minimax_h3_ref2v_turbo_8step_v1.0_768p_comfyui_bf16_lora_f16.ckpt",
weight: 0.9
}
],
compression_artifacts: "h264",
compression_artifacts_quality: 43.1,
tiled_decoding: true,
decoding_tile_height: 256,
decoding_tile_overlap: 64,
decoding_tile_width: 256
},
img2vid: {
maxReferenceImages: 4,
model: "minimax_h3_ref2va_q6p.ckpt",
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 10,
shift: 12,
shift_for_audio: 3,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [
{
mode: "all",
file: "minimax_h3_ref2v_turbo_8step_v1.0_768p_comfyui_bf16_lora_f16.ckpt",
weight: 0.9
}
],
compression_artifacts: "h264",
compression_artifacts_quality: 43.1,
tiled_decoding: true,
decoding_tile_height: 256,
decoding_tile_overlap: 64,
decoding_tile_width: 256
}
};
// src/services/qwen_imageParamsDrawThings.ts
var qwen_imageOverlays = {
txt2img: {
model: "qwen_image_2512_bf16_q6p.ckpt",
negative_prompt: "\u4F4E\u5206\u8FA8\u7387\uFF0C\u4F4E\u753B\u8D28\uFF0C\u80A2\u4F53\u7578\u5F62\uFF0C\u624B\u6307\u7578\u5F62\uFF0C\u753B\u9762\u8FC7\u9971\u548C\uFF0C\u8721\u50CF\u611F\uFF0C\u4EBA\u8138\u65E0\u7EC6\u8282\uFF0C\u8FC7\u5EA6\u5149\u6ED1\uFF0C\u753B\u9762\u5177\u6709AI\u611F\u3002\u6784\u56FE\u6DF7\u4E71\u3002\u6587\u5B57\u6A21\u7CCA\uFF0C\u626D\u66F2\u3002",
guidance_scale: 1,
sampler: "UniPC Trailing",
steps: 10,
shift: 3,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [
{
mode: "all",
file: "qwen_image_2512_lightning_4_step_v1.0_lora_f16.ckpt",
weight: 1
}
]
},
img2img: {
model: "qwen_image_edit_2511_q6p.ckpt",
guidance_scale: 1,
sampler: "UniPC Trailing",
steps: 8,
shift: 3,
sharpness: 0,
strength: 0.9,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [
{
mode: "all",
file: "qwen_image_edit_2511_lightning_4_step_v1.0_lora_f16.ckpt",
weight: 1
}
]
},
edit: {
maxReferenceImages: 4,
model: "qwen_image_edit_2511_q6p.ckpt",
guidance_scale: 1,
sampler: "UniPC Trailing",
steps: 8,
shift: 3,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: [
{
mode: "all",
file: "qwen_image_edit_2511_lightning_4_step_v1.0_lora_f16.ckpt",
weight: 1
}
]
}
};
// src/services/qwen_image_2_1ParamsDrawThings.ts
var NEGATIVE_PROMPT = "\u4F4E\u5206\u8FA8\u7387\uFF0C\u4F4E\u753B\u8D28\uFF0C\u80A2\u4F53\u7578\u5F62\uFF0C\u624B\u6307\u7578\u5F62\uFF0C\u753B\u9762\u8FC7\u9971\u548C\uFF0C\u8721\u50CF\u611F\uFF0C\u4EBA\u8138\u65E0\u7EC6\u8282\uFF0C\u8FC7\u5EA6\u5149\u6ED1\uFF0C\u753B\u9762\u5177\u6709AI\u611F\u3002\u6784\u56FE\u6DF7\u4E71\u3002\u6587\u5B57\u6A21\u7CCA\uFF0C\u626D\u66F2\u3002";
var qwen_image_2_1Overlays = {
txt2img: {
turbo: {
model: "qwen_image_2.1_turbo_q6p.ckpt",
negative_prompt: NEGATIVE_PROMPT,
guidance_embed: 3.5,
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 8,
resolution_dependent_shift: false,
shift: 4,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
clip_l_text: "",
open_clip_g_text: "",
t5_text: "",
controls: [],
loras: []
},
base: {
model: "qwen_image_2.1_q6p.ckpt",
negative_prompt: NEGATIVE_PROMPT,
guidance_embed: 3.5,
guidance_scale: 4,
sampler: "DDIM Trailing",
steps: 16,
resolution_dependent_shift: false,
shift: 4,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
clip_l_text: "",
open_clip_g_text: "",
t5_text: "",
controls: [],
loras: [
{
mode: "all",
file: "qwen_image_2.1_viggle_turbo_v0.3_6step_lora_r256_lora_f16.ckpt",
weight: 0.25
}
]
}
},
img2img: null,
edit: {
turbo: {
maxReferenceImages: 10,
model: "qwen_image_2.1_turbo_q6p.ckpt",
guidance_embed: 3.5,
guidance_scale: 1,
sampler: "DDIM Trailing",
steps: 8,
resolution_dependent_shift: true,
shift: 4,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
clip_l_text: "",
open_clip_g_text: "",
t5_text: "",
controls: [],
loras: []
},
base: {
maxReferenceImages: 10,
model: "qwen_image_2.1_q6p.ckpt",
guidance_embed: 3.5,
guidance_scale: 4,
sampler: "DDIM Trailing",
steps: 16,
resolution_dependent_shift: false,
shift: 4,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
clip_l_text: "",
open_clip_g_text: "",
t5_text: "",
controls: [],
loras: [
{
mode: "all",
file: "qwen_image_2.1_viggle_turbo_v0.3_6step_lora_r256_lora_f16.ckpt",
weight: 0.25
}
]
}
}
};
// src/services/z_imageParamsDrawThings.ts
var z_imageOverlays = {
txt2img: {
model: "z_image_turbo_1.0_q6p.ckpt",
guidance_scale: 1,
sampler: "UniPC Trailing",
steps: 8,
shift: 3,
sharpness: 0,
strength: 1,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
},
img2img: {
model: "z_image_turbo_1.0_q6p.ckpt",
guidance_scale: 1,
sampler: "UniPC Trailing",
steps: 8,
shift: 3,
sharpness: 0,
strength: 0.925,
mask_blur: 1.5,
mask_blur_outset: 0,
refiner_model: null,
controls: [],
loras: []
}
};
// src/services/overlays.generated.ts
var OVERLAY_REGISTRY = {
flux2_9b: flux2_9bOverlays,
flux3: flux3Overlays,
krea_2: krea_2Overlays,
ltx2_3: ltx2_3Overlays,
minimax_h3: minimax_h3Overlays,
minimax_h3_ref2va: minimax_h3_ref2vaOverlays,
qwen_image: qwen_imageOverlays,
qwen_image_2_1: qwen_image_2_1Overlays,
z_image: z_imageOverlays
};
// src/services/overlayTypes.ts
var DEFAULT_MAX_REFERENCE_IMAGES = 4;
// src/services/modelOverlays.ts
var MODES = ["txt2img", "img2img", "edit", "txt2vid", "img2vid"];
var LEGACY_IDS = {
"z-image": "z_image",
krea: "krea_2",
krea2: "krea_2",
"qwen-image": "qwen_image",
"qwen-edit": "qwen_image",
"qwen-image-2.1": "qwen_image_2_1:base",
"qwen-image-2.1-turbo": "qwen_image_2_1:turbo",
flux: "flux2_9b",
"flux-2": "flux2_9b",
"flux-3": "flux3",
"flux-3-klein": "flux3",
ltx: "ltx2_3",
minimax: "minimax_h3",
"minimax-ref": "minimax_h3_ref2va"
};
function normalizeModelId(modelId) {
return LEGACY_IDS[modelId] ?? modelId;
}
function isLegacyPresetName(name) {
return Object.prototype.hasOwnProperty.call(LEGACY_IDS, name);
}
function legacyNamesOf(modelId) {
return Object.entries(LEGACY_IDS).filter(([, id]) => id === modelId).map(([name]) => name);
}
var isVariantTable = (value) => !!value && typeof value === "object" && !("model" in value) && Object.values(value).every((v) => !!v && typeof v === "object");
var variantsOf = (file) => [
...new Set(MODES.flatMap((mode) => isVariantTable(file[mode]) ? Object.keys(file[mode]) : []))
];
var emptyOverlay = () => ({ txt2img: null, img2img: null, edit: null, txt2vid: null, img2vid: null });
var modelOverlays = { auto: emptyOverlay() };
for (const [key, file] of Object.entries(OVERLAY_REGISTRY)) {
const variants = variantsOf(file);
for (const variant of variants.length ? variants : [null]) {
const overlay = emptyOverlay();
for (const mode of MODES) {
const entry = file[mode] ?? null;
overlay[mode] = entry === null ? null : isVariantTable(entry) ? variant ? entry[variant] ?? null : null : entry;
}
modelOverlays[variant ? `${key}:${variant}` : key] = overlay;
}
}
modelOverlays.custom = emptyOverlay();
var MODEL_IDS = Object.keys(modelOverlays);
var MODEL_FAMILIES = MODEL_IDS;
var stripToolFields = ({ maxReferenceImages: _max, ...params }) => params;
function getModelOverlay(modelId, mode) {
if (!modelId || modelId === "auto") return null;
const entry = modelOverlays[normalizeModelId(modelId)];
if (!entry) {
console.error(`Unknown model '${modelId}', using defaults`);
return null;
}
if (mode === "zoom" || mode === "restore") return null;
const overlay = entry[mode];
return overlay ? stripToolFields(overlay) : null;
}
function getMaxReferenceImages(modelId, mode) {
const value = modelId ? modelOverlays[normalizeModelId(modelId)]?.[mode]?.maxReferenceImages : void 0;
return typeof value === "number" && value >= 1 ? Math.floor(value) : DEFAULT_MAX_REFERENCE_IMAGES;
}
function isValidModelId(value) {
return typeof value === "string" && MODEL_IDS.includes(normalizeModelId(value));
}
function getModelFilename(modelId, mode) {
if (!modelId || modelId === "auto") return null;
const overlay = modelOverlays[normalizeModelId(modelId)]?.[mode];
return typeof overlay?.model === "string" ? overlay.model : null;
}
function getModelRequiredFiles(modelId, mode) {
const files = [];
if (!modelId || modelId === "auto") return files;
const overlay = modelOverlays[normalizeModelId(modelId)]?.[mode];
if (!overlay) return files;
if (typeof overlay.model === "string") files.push(overlay.model);
if (Array.isArray(overlay.loras)) {
for (const lora of overlay.loras) {
if (typeof lora === "object" && lora !== null && typeof lora.file === "string") files.push(lora.file);
}
}
return files;
}
// src/services/modelInventory.ts
import fs2 from "node:fs";
import path2 from "node:path";
// src/catalog/modelZoo.runtime.json
var modelZoo_runtime_default = { schema: "dtc.model-catalog.runtime.v1", sources: { drawThingsCommunity: "db37e657ad329dd16c2f1200bb47f940369cd9f4", communityModels: "e9851164709187e7249471701708301842f9f222" }, families: { auraflow: { label: "AuraFlow", kind: "image" }, "cosmos2.5_2b": { label: "Cosmos 2.5 2B", kind: "image" }, ernie_image: { label: "ERNIE Image", kind: "image", fallback: { params: { steps: 30, guidance_scale: 4, shift: 4, sampler: "UniPCTrailing" } } }, flux1: { label: "FLUX.1", kind: "image", fallback: { params: { steps: 28, guidance_scale: 4.5, shift: 1, sampler: "EulerATrailing" } } }, flux2: { label: "FLUX.2", kind: "image", fallback: { params: { steps: 28, guidance_scale: 4.5, shift: 1, sampler: "DDIMTrailing" } } }, flux2_4b: { label: "FLUX.2 4B", kind: "image", fallback: { params: { steps: 30, guidance_scale: 4, shift: 3, sampler: "DDIMTrailing" } } }, flux2_9b: { label: "FLUX.2 9B", kind: "image", fallback: { params: { steps: 4, guidance_scale: 1, shift: 3, sampler: "DDIMTrailing" } } }, flux3_5b: { label: "FLUX.3 5B", kind: "image" }, hidream_i1: { label: "HiDream I1", kind: "image", fallback: { params: { steps: 28, guidance_scale: 1, shift: 3, sampler: "EulerATrailing" } } }, hunyuan_video: { label: "Hunyuan Video", kind: "video" }, ideogram_4: { label: "Ideogram 4", kind: "image" }, "kandinsky2.1": { label: "Kandinsky v2.1", kind: "image" }, krea_2: { label: "Krea 2", kind: "image" }, ltx2: { label: "LTX-2", kind: "video" }, "ltx2.3": { label: "LTX-2.3", kind: "video", fallback: { params: { steps: 30, guidance_scale: 5, shift: 5, sampler: "UniPCTrailing" } } }, minimax_h3: { label: "MiniMax H3", kind: "video" }, moss_image: { label: "MOSS Image", kind: "image" }, pixart: { label: "PixArt Sigma", kind: "image" }, qwen_image: { label: "Qwen Image", kind: "image", fallback: { params: { steps: 30, guidance_scale: 4, shift: 2, sampler: "UniPCTrailing" } } }, "qwen_image_2.1": { label: "Qwen Image 2.1", kind: "image" }, sd3: { label: "Stable Diffusion 3 Medium", kind: "image" }, sd3_large: { label: "Stable Diffusion 3 Large", kind: "image" }, "sdxl_base_v0.9": { label: "Stable Diffusion XL Base", kind: "image", fallback: { params: { steps: 16, guidance_scale: 5, shift: 1, sampler: "DPMPP2MAYS" } } }, "sdxl_refiner_v0.9": { label: "Stable Diffusion XL Refiner", kind: "image" }, seedvr2_3b: { label: "SeedVR2", kind: "upscaler" }, seedvr2_7b: { label: "SeedVR2", kind: "upscaler" }, ssd_1b: { label: "Segmind Stable Diffusion XL 1B", kind: "image" }, svd_i2v: { label: "Stable Video Diffusion", kind: "video" }, v1: { label: "Stable Diffusion v1", kind: "image", fallback: { params: { steps: 16, guidance_scale: 5, shift: 1, sampler: "DPMPP2MAYS" } } }, v2: { label: "Stable Diffusion v2", kind: "image" }, "wan_v2.1_1.3b": { label: "Wan v2.1 1.3B", kind: "video", fallback: { params: { steps: 30, guidance_scale: 5, shift: 5, sampler: "EulerATrailing" } } }, "wan_v2.1_14b": { label: "Wan v2.x 14B", kind: "video", fallback: { params: { steps: 30, guidance_scale: 5, shift: 5, sampler: "EulerATrailing" } } }, "wan_v2.2_5b": { label: "Wan v2.2 5B", kind: "video" }, "wurstchen_v3.0_stage_c": { label: "Stable Cascade (W\xFCrstchen v3.0)", kind: "image" }, z_image: { label: "Z Image", kind: "image", fallback: { params: { steps: 30, guidance_scale: 4, shift: 3, sampler: "UniPCTrailing" } } } }, files: ["fasth3_omni_i8x.ckpt", "fasth3_omni_i4x.ckpt", "fasth3_omni_q8p.ckpt", "minimax_h3_vae_f16.ckpt", "qwen_3_vl_32b_50_i8x.ckpt", "moss_image_sft_i8x.ckpt", "moss_image_sft_i4x.ckpt", "moss_image_sft_q8p.ckpt", "flux_2_vae_f16.ckpt", "qwen_3.5_9b_i5x.ckpt", "moss_image_base_i8x.ckpt", "moss_image_base_i4x.ckpt", "moss_image_base_q8p.ckpt", "flux_3_klein_i8x.ckpt", "flux_3_klein_i4x.ckpt", "flux_3_klein_q8p.ckpt", "qwen_3_vl_4b_instruct_i8x.ckpt", "flux_3_klein_base_i8x.ckpt", "flux_3_klein_base_i4x.ckpt", "flux_3_klein_base_q8p.ckpt", "flux_3_klein_f16.ckpt", "flux_3_klein_base_f16.ckpt", "qwen_image_2.1_turbo_i8x.ckpt", "qwen_image_2.1_turbo_i4x.ckpt", "qwen_image_2.1_turbo_q8p.ckpt", "qwen_image_2.1_turbo_q6p.ckpt", "qwen_3_vl_8b_instruct_i8x.ckpt", "qwen_image_2.1_vae_f16.ckpt", "qwen_image_2.1_turbo_f16.ckpt", "qwen_3_vl_8b_instruct_f16.ckpt", "qwen_image_2.1_f16.ckpt", "qwen_image_2.1_i8x.ckpt", "qwen_image_2.1_i4x.ckpt", "qwen_image_2.1_q8p.ckpt", "qwen_image_2.1_q6p.ckpt", "minimax_h3_fl2va_i8x.ckpt", "minimax_h3_fl2va_i4x.ckpt", "minimax_h3_fl2va_q8p.ckpt", "minimax_h3_fl2va_q6p.ckpt", "minimax_h3_ref2va_i8x.ckpt", "minimax_h3_ref2va_i4x.ckpt", "minimax_h3_ref2va_q8p.ckpt", "minimax_h3_ref2va_q6p.ckpt", "anima_aesthetic_1.1_f16.ckpt", "anima_aesthetic_1.1_i8x.ckpt", "anima_aesthetic_1.1_q8p.ckpt", "qwen_3_0.6b_q8p.ckpt", "qwen_image_vae_f16.ckpt", "anima_turbo_1.0_f16.ckpt", "anima_turbo_1.0_i8x.ckpt", "anima_turbo_1.0_q8p.ckpt", "anima_base_1.0_f16.ckpt", "anima_base_1.0_i8x.ckpt", "anima_base_1.0_q8p.ckpt", "krea_2_turbo_i8x.ckpt", "krea_2_turbo_i6x.ckpt", "krea_2_turbo_i4x.ckpt", "krea_2_turbo_q8p.ckpt", "krea_2_turbo_q6p.ckpt", "qwen_3_vl_4b_q8p.ckpt", "ideogram_4_i8x.ckpt", "ideogram_4_i6x.ckpt", "ideogram_4_q8p.ckpt", "ideogram_4_q6p.ckpt", "qwen_3_vl_8b_instruct_q8p.ckpt", "ideogram_4_instant_i8x.ckpt", "ideogram_4_instant_i6x.ckpt", "ideogram_4_instant_q8p.ckpt", "ideogram_4_instant_q6p.ckpt", "ideogram_4_fast_i8x.ckpt", "ideogram_4_fast_i6x.ckpt", "ideogram_4_fast_q8p.ckpt", "ideogram_4_fast_q6p.ckpt", "krea_2_raw_i8x.ckpt", "krea_2_raw_i4x.ckpt", "krea_2_raw_q8p.ckpt", "krea_2_raw_q6p.ckpt", "seedvr2_3b_i8x.ckpt", "seedvr2_3b_q8p.ckpt", "seedvr2_3b_q6p.ckpt", "seedvr2_vae_f16.ckpt", "seedvr2_7b_i8x.ckpt", "seedvr2_7b_q8p.ckpt", "seedvr2_7b_q6p.ckpt", "ltx_2.3_22b_distilled_1.1_i8x.ckpt", "ltx_2.3_22b_distilled_1.1_q8p.ckpt", "ltx_2.3_22b_distilled_1.1_q6p.ckpt", "gemma_3_12b_it_qat_q8p.ckpt", "ltx_2.3_audio_video_vae_f16.ckpt", "ernie_image_turbo_i8x.ckpt", "ernie_image_turbo_q8p.ckpt", "ernie_image_turbo_q6p.ckpt", "ministral_3_3b_q8p.ckpt", "ernie_image_i8x.ckpt", "ernie_image_q8p.ckpt", "ernie_image_q6p.ckpt", "ernie_image_turbo_f16.ckpt", "ministral_3_3b_f16.ckpt", "ernie_image_f16.ckpt", "ltx_2.3_22b_distilled_f16.ckpt", "gemma_3_12b_it_qat_f16.ckpt", "ltx_2.3_22b_dev_f16.ckpt", "flux_2_klein_9b_kv_i8x.ckpt", "flux_2_klein_9b_kv_q8p.ckpt", "flux_2_klein_9b_kv_q6p.ckpt", "qwen_3_8b_q8p.ckpt", "flux_2_klein_9b_kv_f16.ckpt", "qwen_3_8b_f16.ckpt", "ltx_2.3_22b_dev_i8x.ckpt", "ltx_2.3_22b_dev_q8p.ckpt", "ltx_2.3_22b_dev_q6p.ckpt", "ltx_2.3_22b_distilled_i8x.ckpt", "ltx_2.3_22b_distilled_q8p.ckpt", "ltx_2.3_22b_distilled_q6p.ckpt", "z_image_1.0_f16.ckpt", "flux_1_vae_f16.ckpt", "qwen_3_vl_4b_instruct_f16.ckpt", "z_image_1.0_i8x.ckpt", "z_image_1.0_q8p.ckpt", "z_image_1.0_q6p.ckpt", "qwen_3_vl_4b_instruct_q8p.ckpt", "ltx_2_19b_dev_q8p.ckpt", "ltx_2_19b_dev_q6p.ckpt", "ltx_2_audio_video_vae_f16.ckpt", "ltx_2_19b_distilled_q8p.ckpt", "ltx_2_19b_distilled_q6p.ckpt", "flux_2_klein_4b_i8x.ckpt", "flux_2_klein_4b_q8p.ckpt", "flux_2_klein_4b_q6p.ckpt", "qwen_3_4b_q8p.ckpt", "flux_2_klein_base_4b_i8x.ckpt", "flux_2_klein_base_4b_q8p.ckpt", "flux_2_klein_base_4b_q6p.ckpt", "flux_2_klein_base_9b_i8x.ckpt", "flux_2_klein_base_9b_q8p.ckpt", "flux_2_klein_base_9b_q6p.ckpt", "flux_2_klein_4b_f16.ckpt", "qwen_3_4b_f16.ckpt", "flux_2_klein_base_4b_f16.ckpt", "flux_2_klein_9b_f16.ckpt", "flux_2_klein_base_9b_f16.ckpt", "flux_2_klein_9b_i8x.ckpt", "flux_2_klein_9b_q8p.ckpt", "flux_2_klein_9b_q6p.ckpt", "qwen_image_2512_i8x.ckpt", "qwen_image_2512_bf16_q8p.ckpt", "qwen_image_2512_q8p.ckpt", "qwen_image_2512_q6p.ckpt", "qwen_2.5_vl_7b_q8p.ckpt", "qwen_image_2512_bf16_i8x.ckpt", "qwen_image_2512_bf16_q6p.ckpt", "qwen_image_2512_bf16.ckpt", "qwen_2.5_vl_7b_f16.ckpt", "qwen_image_edit_2511_i8x.ckpt", "qwen_image_edit_2511_bf16_q8p.ckpt", "qwen_image_edit_2511_q8p.ckpt", "qwen_image_edit_2511_q6p.ckpt", "qwen_2.5_vl_7b_vit_f16.ckpt", "qwen_image_edit_2511_bf16_i8x.ckpt", "qwen_image_edit_2511_bf16_q6p.ckpt", "qwen_image_layered_1.0_bf16_q8p.ckpt", "qwen_image_layered_vae_f16.ckpt", "qwen_image_layered_1.0_bf16_q6p.ckpt", "flux_2_dev_i8x.ckpt", "flux_2_dev_q8p.ckpt", "flux_2_dev_q6p.ckpt", "mistral_small_3.2_24b_instruct_2506_q8p.ckpt", "flux_2_dev_f16.ckpt", "mistral_small_3.2_24b_instruct_2506_f16.ckpt", "z_image_turbo_1.0_f16.ckpt", "z_image_turbo_1.0_i8x.ckpt", "z_image_turbo_1.0_q8p.ckpt", "z_image_turbo_1.0_q6p.ckpt", "anisora_v3.2_i2v_wan_2.2_a14b_hne_q8p.ckpt", "anisora_v3.2_i2v_wan_2.2_a14b_hne_q6p_svd.ckpt", "umt5_xxl_encoder_q8p.ckpt", "wan_v2.1_video_vae_f16.ckpt", "anisora_v3.2_i2v_wan_2.2_a14b_lne_q8p.ckpt", "anisora_v3.2_i2v_wan_2.2_a14b_lne_q6p_svd.ckpt", "chronoedit_14b_q8p.ckpt", "chronoedit_14b_q6p_svd.ckpt", "open_clip_xlm_roberta_large_vit_h14_f16.ckpt", "wan_v2.2_a14b_hne_t2v_lightning_250928_q8p.ckpt", "wan_v2.2_a14b_hne_t2v_lightning_250928_q6p_svd.ckpt", "qwen_image_edit_2509_bf16.ckpt", "qwen_image_edit_2509_f16.ckpt", "qwen_image_1.0_bf16_q6p.ckpt", "qwen_image_edit_2509_bf16_q6p.ckpt", "qwen_image_edit_2509_bf16_q8p.ckpt", "qwen_image_edit_2509_q8p.ckpt", "qwen_image_edit_2509_q6p.ckpt", "wan_v2.2_5b_ti2v_f16.ckpt", "wan_v2.2_5b_ti2v_q8p.ckpt", "wan_v2.2_video_vae_f16.ckpt", "qwen_image_edit_1.0_q8p.ckpt", "qwen_image_edit_1.0_q6p.ckpt", "qwen_image_1.0_bf16.ckpt", "qwen_image_1.0_f16.ckpt", "chroma_1_hd_r0.1_q8p.ckpt", "chroma_1_hd_r0.1_q5p.ckpt", "clip_vit_l14_f16.ckpt", "t5_xxl_encoder_q6p.ckpt", "qwen_image_1.0_bf16_q8p.ckpt", "qwen_image_1.0_q8p.ckpt", "qwen_image_1.0_q6p.ckpt", "flux_1_krea_dev_q8p.ckpt", "flux_1_krea_dev_q5p.ckpt", "wan_v2.2_a14b_hne_i2v_i8x.ckpt", "wan_v2.2_a14b_hne_i2v_q8p.ckpt", "wan_v2.2_a14b_hne_i2v_q6p_svd.ckpt", "wan_v2.2_a14b_lne_i2v_i8x.ckpt", "wan_v2.2_a14b_lne_i2v_q8p.ckpt", "wan_v2.2_a14b_lne_i2v_q6p_svd.ckpt", "chroma_v48_detail_calibrated_q8p.ckpt", "chroma_v48_detail_calibrated_q5p.ckpt", "wan_v2.2_a14b_hne_t2v_i8x.ckpt", "wan_v2.2_a14b_hne_t2v_q8p.ckpt", "wan_v2.2_a14b_hne_t2v_q6p_svd.ckpt", "wan_v2.2_a14b_lne_t2v_i8x.ckpt", "wan_v2.2_a14b_lne_t2v_q8p.ckpt", "wan_v2.2_a14b_lne_t2v_q6p_svd.ckpt", "chroma_v47_detail_calibrated_q8p.ckpt", "chroma_v47_detail_calibrated_q5p.ckpt", "hidream_e1_1_q8p.ckpt", "hidream_e1_1_q5p.ckpt", "llama_3.1_8b_instruct_q8p.ckpt", "long_clip_vit_l14_f16.ckpt", "hidream_e1_1_f16.ckpt", "llama_3.1_8b_instruct_f16.ckpt", "long_open_clip_vit_bigg14_f16.ckpt", "t5_xxl_encoder_f16.ckpt", "flux_1_kontext_dev_q8p.ckpt", "flux_1_kontext_dev_q5p.ckpt", "flux_1_kontext_dev_f16.ckpt", "wan_2.1_14b_t2v_fusionx_q8p.ckpt", "wan_2.1_14b_t2v_fusionx_q6p_svd.ckpt", "wan_2.1_14b_i2v_fusionx_q8p.ckpt", "wan_2.1_14b_i2v_fusionx_q6p_svd.ckpt", "rayflux_v3.0_aio_q8p.ckpt", "rayflux_v3.0_aio_q5p.ckpt", "pixelwave_flux_1_schnell_04_q8p.ckpt", "pixelwave_flux_1_schnell_04_q5p_svd.ckpt", "juggernaut_xl_ragnarok_f16.ckpt", "juggernaut_xl_ragnarok_q6p_q8p.ckpt", "juggernaut_xl_ragnarok_clip_vit_l14_f16.ckpt", "juggernaut_xl_ragnarok_open_clip_vit_bigg14_f16.ckpt", "sdxl_vae_v1.0_f16.ckpt", "hidream_e1_full_q8p.ckpt", "hidream_e1_full_q5p.ckpt", "wan_2.1_14b_v1.1_fun_inp_q8p.ckpt", "wan_2.1_14b_v1.1_fun_inp_q6p_svd.ckpt", "wan_2.1_1.3b_v1.1_fun_inp_f16.ckpt", "wan_2.1_1.3b_v1.1_fun_inp_q8p.ckpt", "skyreels_v2_i2v_14b_540p_q8p.ckpt", "skyreels_v2_i2v_14b_540p_q6p_svd.ckpt", "skyreels_v2_i2v_14b_720p_q8p.ckpt", "skyreels_v2_i2v_14b_720p_q6p_svd.ckpt", "skyreels_v2_t2v_14b_540p_q8p.ckpt", "skyreels_v2_t2v_14b_540p_q6p_svd.ckpt", "skyreels_v2_t2v_14b_720p_q8p.ckpt", "skyreels_v2_t2v_14b_720p_q6p_svd.ckpt", "hidream_i1_dev_f16.ckpt", "hidream_i1_full_f16.ckpt", "hidream_i1_fast_f16.ckpt", "skyreels_v2_i2v_1.3b_540p_f16.ckpt", "skyreels_v2_i2v_1.3b_540p_q8p.ckpt", "hidream_i1_fast_i8x.ckpt", "hidream_i1_fast_q8p.ckpt", "hidream_i1_fast_q5p.ckpt", "hidream_i1_full_i8x.ckpt", "hidream_i1_full_q8p.ckpt", "hidream_i1_full_q5p.ckpt", "hidream_i1_dev_i8x.ckpt", "hidream_i1_dev_q8p.ckpt", "hidream_i1_dev_q5p.ckpt", "wan_2.1_14b_fun_inp_q8p.ckpt", "wan_2.1_14b_fun_inp_q6p_svd.ckpt", "wan_2.1_1.3b_fun_inp_f16.ckpt", "wan_2.1_1.3b_fun_inp_q8p.ckpt", "wan_v2.1_14b_i2v_480p_q8p.ckpt", "wan_v2.1_14b_i2v_480p_q6p_svd.ckpt", "wan_v2.1_14b_i2v_720p_q8p.ckpt", "wan_v2.1_14b_i2v_720p_q6p_svd.ckpt", "wan_v2.1_14b_720p_q8p.ckpt", "wan_v2.1_14b_720p_q6p_svd.ckpt", "wan_v2.1_14b_720p_q5p_svd.ckpt", "wan_v2.1_1.3b_480p_f16.ckpt", "wan_v2.1_1.3b_480p_q8p.ckpt", "skyreels_v1_hunyuan_t2v_q8p.ckpt", "skyreels_v1_hunyuan_t2v_q5p_svd.ckpt", "hunyuan_video_vae_f16.ckpt", "llava_llama_3_8b_v1.1_q8p.ckpt", "skyreels_v1_hunyuan_i2v_q8p.ckpt", "skyreels_v1_hunyuan_i2v_q5p_svd.ckpt", "devmode_v0.3_turbo_q8p.ckpt", "devmode_v0.3_turbo_q5p_svd.ckpt", "shuttle_v3.1_aesthetic_q8p.ckpt", "shuttle_v3.1_aesthetic_q5p_svd.ckpt", "shuttle_jaguar_q8p.ckpt", "shuttle_jaguar_q5p_svd.ckpt", "schnellmode_v3.3_q8p.ckpt", "schnellmode_v3.3_q5p_svd.ckpt", "artsy_vibe_v1_q8p.ckpt", "artsy_vibe_v1_q5p_svd.ckpt", "hunyuan_video_t2v_720p_q8p.ckpt", "hunyuan_video_t2v_720p_q5p_svd.ckpt", "flux_1_canny_dev_q8p.ckpt", "flux_1_canny_dev_q5p.ckpt", "flux_1_dev_de_distill_q8p.ckpt", "flux_1_dev_de_distill_q5p.ckpt", "flux_1_fill_dev_q8p.ckpt", "flux_1_fill_dev_q5p.ckpt", "flux_1_depth_dev_q8p.ckpt", "flux_1_depth_dev_q5p.ckpt", "sd3_medium_3.5_f16.ckpt", "sd3_medium_3.5_q8p.ckpt", "open_clip_vit_bigg14_f16.ckpt", "sd3_vae_f16.ckpt", "sd3_large_turbo_3.5_q8p.ckpt", "sd3_large_turbo_3.5_q6p.ckpt", "sd3_large_3.5_q8p.ckpt", "sd3_large_3.5_q6p.ckpt", "sd3_large_3.5_f16.ckpt", "ootd_vton_upper_body_1.0_f16.ckpt", "vae_ft_mse_840000_f16.ckpt", "ootd_vton_full_body_1.0_f16.ckpt", "flux_1_dev_f16.ckpt", "flux_1_dev_q8p.ckpt", "flux_1_dev_q5p.ckpt", "flux_1_schnell_q8p.ckpt", "flux_1_schnell_q5p.ckpt", "auraflow_v0.2_q8p.ckpt", "auraflow_v0.2_q5p.ckpt", "pile_t5_xl_encoder_q8p.ckpt", "kwai_kolors_inpainting_1.0_f16.ckpt", "kwai_kolors_inpainting_1.0_q6p_q8p.ckpt", "chatglm3_6b_q6p_q8p.ckpt", "auraflow_v0.1_q8p.ckpt", "auraflow_v0.1_q5p.ckpt", "kwai_kolors_1.0_f16.ckpt", "kwai_kolors_1.0_q6p_q8p.ckpt", "pixart_sigma_xl_2_512_ms_f16.ckpt", "pixart_sigma_xl_2_512_ms_q8p.ckpt", "svd_i2v_xt_1.1_f16.ckpt", "svd_i2v_xt_1.1_q6p_q8p.ckpt", "open_clip_vit_h14_vision_model_f16.ckpt", "svd_i2v_1.0_f16.ckpt", "svd_i2v_1.0_q6p_q8p.ckpt", "pixart_sigma_xl_2_1024_ms_f16.ckpt", "pixart_sigma_xl_2_1024_ms_q8p.ckpt", "wurstchen_3.0_stage_b_f16.ckpt", "wurstchen_3.0_stage_c_f32_f16.ckpt", "wurstchen_3.0_stage_b_q6p_q8p.ckpt", "wurstchen_3.0_stage_c_f32_q6p_q8p.ckpt", "wurstchen_3.0_stage_a_hq_f16.ckpt", "sd3_medium_f16.ckpt", "sd3_medium_q8p.ckpt", "sd_xl_turbo_f16.ckpt", "sd_xl_turbo_q6p_q8p.ckpt", "colorfulxl_v6.0_f16.ckpt", "colorfulxl_v6.0_q6p_q8p.ckpt", "colorfulxl_v6.0_clip_vit_l14_f16.ckpt", "colorfulxl_v6.0_open_clip_vit_bigg14_f16.ckpt", "proteus_v0.3_f16.ckpt", "proteus_v0.3_q6p_q8p.ckpt", "proteus_v0.3_clip_vit_l14_f16.ckpt", "proteus_v0.3_open_clip_vit_bigg14_f16.ckpt", "icatcher_realistic_f16.ckpt", "icatcher_realistic_q6p_q8p.ckpt", "icatcher_realistic_clip_vit_l14_f16.ckpt", "icatcher_realistic_open_clip_vit_bigg14_f16.ckpt", "icatcher_cartoon_f16.ckpt", "icatcher_cartoon_q6p_q8p.ckpt", "icatcher_cartoon_clip_vit_l14_f16.ckpt", "icatcher_cartoon_open_clip_vit_bigg14_f16.ckpt", "realvisxl_v4.0_f16.ckpt", "realvisxl_v4.0_q6p_q8p.ckpt", "realvisxl_v4.0_clip_vit_l14_f16.ckpt", "realvisxl_v4.0_open_clip_vit_bigg14_f16.ckpt", "pixelwave_10_f16.ckpt", "pixelwave_10_q6p_q8p.ckpt", "pixelwave_10_clip_vit_l14_f16.ckpt", "pixelwave_10_open_clip_vit_bigg14_f16.ckpt", "juggernaut_xl_v9_f16.ckpt", "juggernaut_xl_v9_q6p_q8p.ckpt", "juggernaut_xl_v9_clip_vit_l14_f16.ckpt", "juggernaut_xl_v9_open_clip_vit_bigg14_f16.ckpt", "pixelwave_v9_f16.ckpt", "pixelwave_v9_q6p_q8p.ckpt", "pixelwave_v9_clip_vit_l14_f16.ckpt", "pixelwave_v9_open_clip_vit_bigg14_f16.ckpt", "juggernaut_xl_x_f16.ckpt", "juggernaut_xl_x_q6p_q8p.ckpt", "juggernaut_xl_x_clip_vit_l14_f16.ckpt", "juggernaut_xl_x_open_clip_vit_bigg14_f16.ckpt", "animatelcm_svd_xt_v1.1_f16.ckpt", "animatelcm_svd_xt_v1.1_q6p_q8p.ckpt", "open_clip_vit_h14_visual_proj_f16.ckpt", "dreamshaper_xl_v2.1_turbo_f16.ckpt", "dreamshaper_xl_v2.1_turbo_q6p_q8p.ckpt", "dreamshaper_xl_v2.1_turbo_clip_vit_l14_f16.ckpt", "dreamshaper_xl_v2.1_turbo_open_clip_vit_bigg14_f16.ckpt", "juggernaut_xl_v9_lightning_f16.ckpt", "juggernaut_xl_v9_lightning_q6p_q8p.ckpt", "juggernaut_xl_v9_lightning_clip_vit_l14_f16.ckpt", "juggernaut_xl_v9_lightning_open_clip_vit_bigg14_f16.ckpt", "rev_animated_v1.22_f16.ckpt", "rev_animated_v1.22_q6p_q8p.ckpt", "rev_animated_v1.22_clip_vit_l14_f16.ckpt", "realistic_vision_v5.1_f16.ckpt", "realistic_vision_v5.1_q6p_q8p.ckpt", "realistic_vision_v5.1_clip_vit_l14_f16.ckpt", "dreamshaper_v8_f16.ckpt", "dreamshaper_v8_q6p_q8p.ckpt", "dreamshaper_v8_clip_vit_l14_f16.ckpt", "counterfeit_v3.0_f16.ckpt", "counterfeit_v3.0_q6p_q8p.ckpt", "counterfeit_v3.0_clip_vit_l14_f16.ckpt", "majicmix_realistic_v7_f16.ckpt", "majicmix_realistic_v7_q6p_q8p.ckpt", "majicmix_realistic_v7_clip_vit_l14_f16.ckpt", "animagine_xl_v3.1_f16.ckpt", "animagine_xl_v3.1_q6p_q8p.ckpt", "animagine_xl_v3.1_clip_vit_l14_f16.ckpt", "animagine_xl_v3.1_open_clip_vit_bigg14_f16.ckpt", "juggernaut_reborn_f16.ckpt", "juggernaut_reborn_q6p_q8p.ckpt", "juggernaut_reborn_clip_vit_l14_f16.ckpt", "playground_v2_f16.ckpt", "playground_v2_q6p_q8p.ckpt", "playground_v2.5_f16.ckpt", "playground_v2.5_q6p_q8p.ckpt", "ssd_1b_f16.ckpt", "ssd_1b_q6p_q8p.ckpt", "disney_pixar_cartoon_type_b_q6p_q8p.ckpt", "disney_pixar_cartoon_type_b_clip_vit_l14_f16.ckpt", "wd_v1.3_f16.ckpt", "nitro_v1_f16.ckpt", "nitro_v1_clip_vit_l14_f16.ckpt", "cyberpunk_anime_f16.ckpt", "cyberpunk_anime_clip_vit_l14_f16.ckpt", "redshift_v1_f16.ckpt", "redshift_v1_clip_vit_l14_f16.ckpt", "redshift_768_v_f16.ckpt", "redshift_768_v_open_clip_vit_h14_f16.ckpt", "dnd_30000_f16.ckpt", "dnd_30000_clip_vit_l14_f16.ckpt", "trnlgcy_f16.ckpt", "trnlgcy_clip_vit_l14_f16.ckpt", "mdjrny_v4_f16.ckpt", "mdjrny_v4_clip_vit_l14_f16.ckpt", "anything_v3_f16.ckpt", "anything_v3_clip_vit_l14_f16.ckpt", "anything_v3_vae_f16.ckpt", "classicanim_v1_f16.ckpt", "classicanim_v1_clip_vit_l14_f16.ckpt", "modi_v1_f16.ckpt", "modi_v1_clip_vit_l14_f16.ckpt", "arcane_v3_f16.ckpt", "arcane_v3_clip_vit_l14_f16.ckpt", "hassanblend_v1.5.1.2_f16.ckpt", "hassanblend_v1.5.1.2_clip_vit_l14_f16.ckpt", "lvngvncnt_v2_f16.ckpt", "lvngvncnt_v2_clip_vit_l14_f16.ckpt", "spiderverse_v1_f16.ckpt", "spiderverse_v1_clip_vit_l14_f16.ckpt", "eldenring_v3_f16.ckpt", "eldenring_v3_clip_vit_l14_f16.ckpt", "papercut_v1_f16.ckpt", "papercut_v1_clip_vit_l14_f16.ckpt", "voxelart_v1_f16.ckpt", "voxelart_v1_clip_vit_l14_f16.ckpt", "balloonart_v1_f16.ckpt", "balloonart_v1_clip_vit_l14_f16.ckpt", "f222_f16.ckpt", "supermarionation_v2_f16.ckpt", "supermarionation_v2_clip_vit_l14_f16.ckpt", "inkpunk_v2_f16.ckpt", "inkpunk_v2_clip_vit_l14_f16.ckpt", "samdoesart_v3_f16.ckpt", "samdoesart_v3_clip_vit_l14_f16.ckpt", "ghibli_v1_f16.ckpt", "ghibli_v1_clip_vit_l14_f16.ckpt", "analog_v1_f16.ckpt", "analog_v1_clip_vit_l14_f16.ckpt", "dnd_classes_and_species_f16.ckpt", "dnd_classes_and_species_clip_vit_l14_f16.ckpt", "aloeveras_simpmaker_3k1_f16.ckpt", "hna_3dkx_1.1_f16.ckpt", "hna_3dkx_1.1_clip_vit_l14_f16.ckpt", "seek_art_mega_v1_f16.ckpt", "seek_art_mega_v1_clip_vit_l14_f16.ckpt", "deliberate_v2_q6p_q8p.ckpt", "deliberate_v2_clip_vit_l14_f16.ckpt", "sd_xl_base_1.0_f16.ckpt", "sd_xl_base_1.0_q6p_q8p.ckpt", "sd_xl_refiner_1.0_f16.ckpt", "sd_xl_refiner_1.0_q6p_q8p.ckpt", "sd_xl_base_0.9_f16.ckpt", "sdxl_vae_f16.ckpt", "sd_xl_refiner_0.9_f16.ckpt", "fooocus_inpaint_sd_xl_v2.6_f16.ckpt", "fooocus_inpaint_sd_xl_v2.6_q6p_q8p.ckpt", "sd_v1.4_f16.ckpt", "sd_v1.5_f16.ckpt", "sd_v1.5_inpainting_f16.ckpt", "sd_v2.0_f16.ckpt", "open_clip_vit_h14_f16.ckpt", "sd_v2.0_768_v_f16.ckpt", "sd_v2.0_inpainting_f16.ckpt", "sd_v2.0_depth_f16.ckpt", "sd_v2.1_f16.ckpt", "sd_v2.1_768_v_f16.ckpt", "kandinsky_f16.ckpt", "kandinsky_movq_f16.ckpt", "xlm_roberta_f16.ckpt", "svd_i2v_xt_1.0_f16.ckpt", "svd_i2v_xt_1.0_q6p_q8p.ckpt", "minisd_v1.4_f16.ckpt", "instruct_pix2pix_22000_f16.ckpt", "2dn_f16.ckpt", "2dn_clip_vit_l14_f16.ckpt", "2dn_open_clip_vit_bigg14_f16.ckpt", "1693152_8stepscrearthyperflux_creartultimate_q8p.ckpt", "862930_8stepscrearthyperflux_v24hyperdevfp8unet_q8p.ckpt", "930403_8stepscrearthyperflux_v26hyperdevfp8unet_f16.ckpt", "930403_8stepscrearthyperflux_v26hyperdevfp8unet_q8p.ckpt", "1187144_8stepscrearthyperflux_v30hyperdevfp8unet_q8p.ckpt", "1315145_8stepscrearthyperflux_v40hyperdevfp8unet_q8p.ckpt", "987485_acornisspinningflux_aisfluxdedistilled_q8p.ckpt", "1374658_acornisspinningflux_aisfluxv15_q8p.ckpt", "1450688_acornisspinningflux_aisfdedistilledv15_q8p.ckpt", "1298942_acornisspinningflux_aisfhyper8stepv15_q8p.ckpt", "1656743_acornisspinningflux_aisfv169_q8p.ckpt", "1052470_acornisspinningflux_aisf11h8stpchinfx_q8p.ckpt", "1095910_agfluxfillnsfwfp8_agfluxfillnsfwv17fp8_q8p.ckpt", "884843_agflux_schnellv10fp8_q8p.ckpt", "864441_agflux_v10fp8_q8p.ckpt", "1055211_agflux_v21fp8_q8p.ckpt", "1244250_agflux_v3fp8_q8p.ckpt", "agga_s_utopia__illustrious_sdxl_f16.ckpt", "agga_s_utopia__illustrious_sdxl_clip_vit_l14_f16.ckpt", "agga_s_utopia__illustrious_sdxl_open_clip_vit_bigg14_f16.ckpt", "amanatsu_illustrious_f16.ckpt", "amanatsu_illustrious_clip_vit_l14_f16.ckpt", "amanatsu_illustrious_open_clip_vit_bigg14_f16.ckpt", "anillustrious_f16.ckpt", "anillustrious_clip_vit_l14_f16.ckpt", "anillustrious_open_clip_vit_bigg14_f16.ckpt", "animij_f16.ckpt", "animij_clip_vit_l14_f16.ckpt", "animij_open_clip_vit_bigg14_f16.ckpt", "anisora_v2_i2v_wan_2.1_14b_q8p.ckpt", "anisora_v2_i2v_wan_2.1_14b_q6p_svd.ckpt", "anisora_v3.1_i2v_wan_2.1_14b_q8p.ckpt", "anisora_v3.1_i2v_wan_2.1_14b_q6p_svd.ckpt", "artofura_furry_mix_f16.ckpt", "artofura_furry_mix_clip_vit_l14_f16.ckpt", "artofura_furry_mix_open_clip_vit_bigg14_f16.ckpt", "974825_artsydream_v1fp16_q8p.ckpt", "974932_artsydream_v1fp8_q8p.ckpt", "1004320_artsydream_v2fp16_q8p.ckpt", "1004235_artsydream_v2fp8_q8p.ckpt", "1023964_artsydream_v3fp16_q8p.ckpt", "1023471_artsydream_v3fp8_q8p.ckpt", "1071391_artsydream_v4fp16_q8p.ckpt", "1070930_artsydream_v4fp8_q8p.ckpt", "1136806_artsydream_v5fp16_q8p.ckpt", "1136364_artsydream_v5fp8_q8p.ckpt", "1213649_artsydream_v6fp16_q8p.ckpt", "1213097_artsydream_v6fp8_q8p.ckpt", "1308807_artsyvibe_v1fp16_q8p.ckpt", "1308180_artsyvibe_v1fp8_q8p.ckpt", "1842885_artsyvibe_v2fp16_q8p.ckpt", "1840540_artsyvibe_v2fp8_q8p.ckpt", "asian_realism_by_stable_yogi_pony_f16.ckpt", "asian_realism_by_stable_yogi_pony_clip_vit_l14_f16.ckpt", "asian_realism_by_stable_yogi_pony_open_clip_vit_bigg14_f16.ckpt", "980131_atomixfluxunet_v10_q8p.ckpt", "aungir_aungir_t6a4_1405004_f16.ckpt", "aungir_aungir_t6a4_1405004_clip_vit_l14_f16.ckpt", "aungir_aungir_t6a4_1405004_open_clip_vit_bigg14_f16.ckpt", "aungir_aungir_t6ao4.5_1723632_f16.ckpt", "aungir_aungir_t6ao4.5_1723632_clip_vit_l14_f16.ckpt", "aungir_aungir_t6ao4.5_1723632_open_clip_vit_bigg14_f16.ckpt", "big_love_f16.ckpt", "big_love_clip_vit_l14_f16.ckpt", "big_love_open_clip_vit_bigg14_f16.ckpt", "bismuth_illustrious_mix_f16.ckpt", "bismuth_illustrious_mix_clip_vit_l14_f16.ckpt", "bismuth_illustrious_mix_open_clip_vit_bigg14_f16.ckpt", "blendermix_f16.ckpt", "blendermix_clip_vit_l14_f16.ckpt", "blendermix_open_clip_vit_bigg14_f16.ckpt", "808159_bluepencilflux1_v010_q8p.ckpt", "867256_bluepencilflux1_v021_q8p.ckpt", "boleromixillustrious_f16.ckpt", "boleromixillustrious_clip_vit_l14_f16.ckpt", "boleromixillustrious_open_clip_vit_bigg14_f16.ckpt", "978066_c4pacitor_av2alpha_q8p.ckpt", "1035832_c4pacitor_av2beta_q8p.ckpt", "845592_c4pacitor_dv1_q8p.ckpt", "949363_c4pacitor_dv11_q8p.ckpt", "1123235_c4pacitor_dv2_q8p.ckpt", "1700674_c4pacitor_dv3alpha_q8p.ckpt", "954181_c4pacitor_sv11_q8p.ckpt", "1086868_c4pacitor_sv2alpha_q8p.ckpt", "candied_anime_illustriousxl_f16.ckpt", "candied_anime_illustriousxl_clip_vit_l14_f16.ckpt", "candied_anime_illustriousxl_open_clip_vit_bigg14_f16.ckpt", "1178183_centerfoldflux_v35fp8e54steps_q8p.ckpt", "1845222_centerfoldflux_v40fp8e5m2_q8p.ckpt", "chroma_1_hd_annealed_q8p.ckpt", "chroma_1_hd_annealed_q5p.ckpt", "chroma_v38_detail_calibrated_q8p.ckpt", "chroma_v38_detail_calibrated_q5p.ckpt", "chroma_v39_detail_calibrated_q8p.ckpt", "chroma_v39_detail_calibrated_q5p.ckpt", "chroma_v40_detail_calibrated_q8p.ckpt", "chroma_v40_detail_calibrated_q5p.ckpt", "chroma_v41_detail_calibrated_q8p.ckpt", "chroma_v41_detail_calibrated_q5p.ckpt", "chroma_v42_detail_calibrated_q8p.ckpt", "chroma_v42_detail_calibrated_q5p.ckpt", "chroma_v43_detail_calibrated_q8p.ckpt", "chroma_v43_detail_calibrated_q5p.ckpt", "chroma_v44_detail_calibrated_q8p.ckpt", "chroma_v44_detail_calibrated_q5p.ckpt", "chroma_v45_detail_calibrated_q8p.ckpt", "chroma_v45_detail_calibrated_q5p.ckpt", "chroma_v46_detail_calibrated_q8p.ckpt", "chroma_v46_detail_calibrated_q5p.ckpt", "circusmix_f16.ckpt", "circusmix_clip_vit_l14_f16.ckpt", "circusmix_open_clip_vit_bigg14_f16.ckpt", "765642_colorfulasiangirlflux_beta_q8p.ckpt", "996001_colossusprojectflux_21dedistilledaioexp_q8p.ckpt", "1846322_colossusprojectflux_v10aiofp8_q8p.ckpt", "931988_colossusprojectflux_v10allinonefp8_q8p.ckpt", "1860608_colossusprojectflux_v10bfp8aiobobfp8_q8p.ckpt", "1851709_colossusprojectflux_v10behemothaiofp16_q8p.ckpt", "940696_colossusprojectflux_v10fp16unetonly_q8p.ckpt", "1855312_colossusprojectflux_v10unetonlyfp16_q8p.ckpt", "1848909_colossusprojectflux_v10unetonlyfp8_q8p.ckpt", "971579_colossusprojectflux_v20allinoneexp_q8p.ckpt", "1159932_colossusprojectflux_v42aio_q8p.ckpt", "1495910_colossusprojectflux_v44aio_q8p.ckpt", "1443922_colossusprojectflux_v50aio_q8p.ckpt", "1507835_colossusprojectflux_v50aiobehemoth_q8p.ckpt", "1462430_colossusprojectflux_v50fp8unet_q8p.ckpt", "1703060_colossusprojectflux_v90aio_q8p.ckpt", "1045901_copaxtimeless_fluxrealfast_q8p.ckpt", "894590_copaxtimeless_stylemix1fluxdevfp16_q8p.ckpt", "897535_copaxtimeless_stylemix1fp8_q8p.ckpt", "975743_copaxtimeless_stylemix2_q8p.ckpt", "1338565_copaxtimeless_xpluscartoon_q8p.ckpt", "954640_copaxtimeless_xplusmix1_q8p.ckpt", "962412_copaxtimeless_xplusmix1fp8_q8p.ckpt", "982160_copaxtimeless_xplusmix2_q8p.ckpt", "1134093_copaxtimeless_xplusmix3_q8p.ckpt", "1148473_copaxtimeless_xplusmix3dark_q8p.ckpt", "1217501_copaxtimeless_xplusmix4_q8p.ckpt", "801556_copaxtimeless_xplusposes_q8p.ckpt", "783956_copaxtimeless_xplusunrealfast_q8p.ckpt", "778112_copaxtimeless_xplus1_q8p.ckpt", "907183_copaxtimeless_xplus2_q8p.ckpt", "1085190_copaxtimeless_xplus2basetrain_q8p.ckpt", "copax_pony_xl_f16.ckpt", "copax_pony_xl_clip_vit_l14_f16.ckpt", "copax_pony_xl_open_clip_vit_bigg14_f16.ckpt", "crow___pony_qp_f16.ckpt", "crow___pony_qp_clip_vit_l14_f16.ckpt", "crow___pony_qp_open_clip_vit_bigg14_f16.ckpt", "cyberillustrious_cyberrealistic_f16.ckpt", "cyberillustrious_cyberrealistic_clip_vit_l14_f16.ckpt", "cyberillustrious_cyberrealistic_open_clip_vit_bigg14_f16.ckpt", "cyberrealistic_f16.ckpt", "cyberrealistic_clip_vit_l14_f16.ckpt", "cyberrealistic_pony_v8_1346181_f16.ckpt", "cyberrealistic_pony_v8_1346181_clip_vit_l14_f16.ckpt", "cyberrealistic_pony_v8_1346181_open_clip_vit_bigg14_f16.ckpt", "cyberrealistic_pony_v8.5_1478064_f16.ckpt", "cyberrealistic_pony_v8.5_1478064_clip_vit_l14_f16.ckpt", "cyberrealistic_pony_v8.5_1478064_open_clip_vit_bigg14_f16.ckpt", "cyberrealistic_pony_v9.0_alt_1_1691220_f16.ckpt", "cyberrealistic_pony_v9.0_alt_1_1691220_clip_vit_l14_f16.ckpt", "cyberrealistic_pony_v9.0_alt_1_1691220_open_clip_vit_bigg14_f16.ckpt", "cyberrealistic_flux_v2.5_f16.ckpt", "cyberrealistic_flux_v2.5_q8p.ckpt", "cyberrealistic_pony_catalyst_f16.ckpt", "cyberrealistic_pony_catalyst_clip_vit_l14_f16.ckpt", "cyberrealistic_pony_catalyst_open_clip_vit_bigg14_f16.ckpt", "cyberrealistic_pony_semi_realistic_f16.ckpt", "cyberrealistic_pony_semi_realistic_clip_vit_l14_f16.ckpt", "cyberrealistic_pony_semi_realistic_open_clip_vit_bigg14_f16.ckpt", "cyberrealistic_xl_f16.ckpt", "cyberrealistic_xl_clip_vit_l14_f16.ckpt", "cyberrealistic_xl_open_clip_vit_bigg14_f16.ckpt", "1048219_demoncoresfwnsfw_fluxv13_q8p.ckpt", "1357212_demoncoresfwnsfw_v25helheimprojectaio_q8p.ckpt", "dhxl_v1.0_f16.ckpt", "dhxl_v1.0_clip_vit_l14_f16.ckpt", "dhxl_v1.0_open_clip_vit_bigg14_f16.ckpt", "dixar_f16.ckpt", "dixar_clip_vit_l14_f16.ckpt", "dixar_open_clip_vit_bigg14_f16.ckpt", "dreamisoa_remix_f16.ckpt", "dreamisoa_remix_clip_vit_l14_f16.ckpt", "dreamisoa_remix_open_clip_vit_bigg14_f16.ckpt", "duchaiten_pony_xl_no_score_v5.2_706363_f16.ckpt", "duchaiten_pony_xl_no_score_v5.2_706363_clip_vit_l14_f16.ckpt", "duchaiten_pony_xl_no_score_v5.2_706363_open_clip_vit_bigg14_f16.ckpt", "duchaiten_pony_xl_no_score_v6.0_817261_f16.ckpt", "duchaiten_pony_xl_no_score_v6.0_817261_clip_vit_l14_f16.ckpt", "duchaiten_pony_xl_no_score_v6.0_817261_open_clip_vit_bigg14_f16.ckpt", "duchaiten_cool_age_f16.ckpt", "duchaiten_cool_age_clip_vit_l14_f16.ckpt", "duchaiten_cool_age_open_clip_vit_bigg14_f16.ckpt", "duchaiten_noobai_f16.ckpt", "duchaiten_noobai_clip_vit_l14_f16.ckpt", "duchaiten_noobai_open_clip_vit_bigg14_f16.ckpt", "duchaiten_noobai_cinematic_f16.ckpt", "duchaiten_noobai_cinematic_clip_vit_l14_f16.ckpt", "duchaiten_noobai_cinematic_open_clip_vit_bigg14_f16.ckpt", "duchaiten_pony_real_f16.ckpt", "duchaiten_pony_real_clip_vit_l14_f16.ckpt", "duchaiten_pony_real_open_clip_vit_bigg14_f16.ckpt", "1677057_edgeofreality_32beyondreality_q8p.ckpt", "1224657_edgeofreality_v30_q8p.ckpt", "editijon_k_pop_f16.ckpt", "editijon_k_pop_clip_vit_l14_f16.ckpt", "editijon_k_pop_open_clip_vit_bigg14_f16.ckpt", "epicrealism_xl_f16.ckpt", "epicrealism_xl_clip_vit_l14_f16.ckpt", "epicrealism_xl_open_clip_vit_bigg14_f16.ckpt", "eri_lumenveil_v1_illustrious_nai_f16.ckpt", "eri_lumenveil_v1_illustrious_nai_clip_vit_l14_f16.ckpt", "eri_lumenveil_v1_illustrious_nai_open_clip_vit_bigg14_f16.ckpt", "fantasm_pony_xl_f16.ckpt", "fantasm_pony_xl_clip_vit_l14_f16.ckpt", "fantasm_pony_xl_open_clip_vit_bigg14_f16.ckpt", "795206_fenrisxlflux_fenrisfluxv1fp8_q8p.ckpt", "five_stars_illustrious_1.0_1398525_f16.ckpt", "five_stars_illustrious_1.0_1398525_clip_vit_l14_f16.ckpt", "five_stars_illustrious_1.0_1398525_open_clip_vit_bigg14_f16.ckpt", "five_stars_illustrious_4.0_1657020_f16.ckpt", "five_stars_illustrious_4.0_1657020_clip_vit_l14_f16.ckpt", "five_stars_illustrious_4.0_1657020_open_clip_vit_bigg14_f16.ckpt", "959302_fluxrealistic_fluxrealisticsamayv2_q8p.ckpt", "1054490_flux1_v10fp8_q8p.ckpt", "1103485_flux1_v10fp8schnell_q8p.ckpt", "1219311_flux1_v20fp8_q8p.ckpt", "1319871_flux1_v30fp8_q8p.ckpt", "1442202_flux1_v30papfp8_q8p.ckpt", "752959_flux1devasian_v10fp16_q8p.ckpt", "1519790_flux1eastfp8_canny_q8p.ckpt", "1519801_flux1eastfp8_depth_q8p.ckpt", "1519030_flux1eastfp8_dev_q8p.ckpt", "1519446_flux1eastfp8_fill_q8p.ckpt", "947686_fluxedupfluxnsfw_10_q8p.ckpt", "1126942_fluxedupfluxnsfw_21_q8p.ckpt", "1182699_fluxedupfluxnsfw_22_q8p.ckpt", "1305680_fluxedupfluxnsfw_24_q8p.ckpt", "1466679_fluxedupfluxnsfw_25_q8p.ckpt", "1700814_fluxedupfluxnsfw_40devfp8_q8p.ckpt", "1823302_fluxedupfluxnsfw_41_q8p.ckpt", "1050076_fluxmania_i_q8p.ckpt", "1463804_fluxmania_iv_q8p.ckpt", "1769925_fluxmania_legacy_q8p.ckpt", "1539776_fluxmania_v_q8p.ckpt", "furrytoonmix_f16.ckpt", "furrytoonmix_clip_vit_l14_f16.ckpt", "furrytoonmix_open_clip_vit_bigg14_f16.ckpt", "1329004_genovaapex_1618experiment_q8p.ckpt", "1831456_genovaapex_genovav2_q8p.ckpt", "1209969_genovaapex_plus_q8p.ckpt", "1111281_genovaapex_real_q8p.ckpt", "1068773_genovaapex_s_q8p.ckpt", "getphat_flux_reality_nsfw_v11_softcore_q8p.ckpt", "1868950_gonzalomoxlfluxpony_v03fluxityfp8_q8p.ckpt", "1883195_gonzalomoxlfluxpony_v10fluxityfp8_q8p.ckpt", "homosimile_xl_pony__illustrious__noobai_f16.ckpt", "homosimile_xl_pony__illustrious__noobai_clip_vit_l14_f16.ckpt", "homosimile_xl_pony__illustrious__noobai_open_clip_vit_bigg14_f16.ckpt", "hoseki_lustrousmix_illustriousxl_f16.ckpt", "hoseki_lustrousmix_illustriousxl_clip_vit_l14_f16.ckpt", "hoseki_lustrousmix_illustriousxl_open_clip_vit_bigg14_f16.ckpt", "hoseki_lustrousmix_pony_xl_f16.ckpt", "hoseki_lustrousmix_pony_xl_clip_vit_l14_f16.ckpt", "hoseki_lustrousmix_pony_xl_open_clip_vit_bigg14_f16.ckpt", "hs_ultrahd_cg_f16.ckpt", "hs_ultrahd_cg_clip_vit_l14_f16.ckpt", "hs_ultrahd_cg_open_clip_vit_bigg14_f16.ckpt", "1254943_hyperfluxdedistilled_hyper16stepsfp8_q8p.ckpt", "1255083_hyperfluxdedistilled_hyper8stepsfp8_q8p.ckpt", "icedcoffeeil_f16.ckpt", "icedcoffeeil_clip_vit_l14_f16.ckpt", "icedcoffeeil_open_clip_vit_bigg14_f16.ckpt", "iffymix_xl_f16.ckpt", "iffymix_xl_clip_vit_l14_f16.ckpt", "iffymix_xl_open_clip_vit_bigg14_f16.ckpt", "illumiyume_xl_illustrious_f16.ckpt", "illumiyume_xl_illustrious_clip_vit_l14_f16.ckpt", "illumiyume_xl_illustrious_open_clip_vit_bigg14_f16.ckpt", "1108227_illustrationjuanerghibli_v10_q8p.ckpt", "1215918_illustrationjuanerghibli_v20_q8p.ckpt", "illustrij_f16.ckpt", "illustrij_clip_vit_l14_f16.ckpt", "illustrij_open_clip_vit_bigg14_f16.ckpt", "illustrij_genv1_f16.ckpt", "illustrij_genv1_q6p_q8p.ckpt", "illustrij_genv1_clip_vit_l14_f16.ckpt", "illustrij_genv1_open_clip_vit_bigg14_f16.ckpt", "illustrious_black_magic_illustrious_noob_more_f16.ckpt", "illustrious_black_magic_illustrious_noob_more_clip_vit_l14_f16.ckpt", "illustrious_black_magic_illustrious_noob_more_open_clip_vit_bigg14_f16.ckpt", "illustrious_gehenna_illustrious_checkpoint_f16.ckpt", "illustrious_gehenna_illustrious_checkpoint_clip_vit_l14_f16.ckpt", "illustrious_gehenna_illustrious_checkpoint_open_clip_vit_bigg14_f16.ckpt", "illustrious_realism_by_klaabu_f16.ckpt", "illustrious_realism_by_klaabu_clip_vit_l14_f16.ckpt", "illustrious_realism_by_klaabu_open_clip_vit_bigg14_f16.ckpt", "illustrious_xl_f16.ckpt", "illustrious_xl_clip_vit_l14_f16.ckpt", "illustrious_xl_open_clip_vit_bigg14_f16.ckpt", "illustrious_xl_personal_merge_noob_v_pred0.5_test_merge_updated_f16.ckpt", "illustrious_xl_personal_merge_noob_v_pred0.5_test_merge_updated_clip_vit_l14_f16.ckpt", "illustrious_xl_personal_merge_noob_v_pred0.5_test_merge_updated_open_clip_vit_bigg14_f16.ckpt", "inbetweij___no.04_f16.ckpt", "inbetweij___no.04_q6p_q8p.ckpt", "inbetweij___no.04_clip_vit_l14_f16.ckpt", "inbetweij___no.04_open_clip_vit_bigg14_f16.ckpt", "indigo_void_furry_fused_xl_furry_noobai_noobai_v1.7_1569147_f16.ckpt", "indigo_void_furry_fused_xl_furry_noobai_noobai_v1.7_1569147_clip_vit_l14_f16.ckpt", "indigo_void_furry_fused_xl_furry_noobai_noobai_v1.7_1569147_open_clip_vit_bigg14_f16.ckpt", "indigo_void_furry_fused_xl_furry_noobai_noobai_v1.8_1731573_f16.ckpt", "indigo_void_furry_fused_xl_furry_noobai_noobai_v1.8_1731573_clip_vit_l14_f16.ckpt", "indigo_void_furry_fused_xl_furry_noobai_noobai_v1.8_1731573_open_clip_vit_bigg14_f16.ckpt", "indigo_furry_mix_xl_f16.ckpt", "indigo_furry_mix_xl_clip_vit_l14_f16.ckpt", "indigo_furry_mix_xl_open_clip_vit_bigg14_f16.ckpt", "indigo_void_furry_vpred_furry_noobai_v_pred_f16.ckpt", "indigo_void_furry_vpred_furry_noobai_v_pred_clip_vit_l14_f16.ckpt", "indigo_void_furry_vpred_furry_noobai_v_pred_open_clip_vit_bigg14_f16.ckpt", "1006775_iniversemixsfwnsfw_f1drealguofengfp8v20_q8p.ckpt", "1031531_iniversemixsfwnsfw_f1drealnsfwguofengv2_q8p.ckpt", "973626_iniversemixsfwnsfw_flux1dnsfwfp16v12_q8p.ckpt", "966095_iniversemixsfwnsfw_flux1dnsfwfp8v10_q8p.ckpt", "ionsyx_f16.ckpt", "ionsyx_clip_vit_l14_f16.ckpt", "ionsyx_open_clip_vit_bigg14_f16.ckpt", "886474_isenganmixflux_vb_q8p.ckpt", "796103_jibmixflux_fp16v1_q8p.ckpt", "918242_jibmixflux_fp8v2electric_q8p.ckpt", "1001176_jibmixflux_fp8v4canvasgalore_q8p.ckpt", "1249737_jibmixflux_v72pixelheaven_q8p.ckpt", "1355240_jibmixflux_v78cleartextfocus_q8p.ckpt", "1193229_jibmixflux_v7pixelheavenbeta_q8p.ckpt", "1755367_jibmixflux_v85consisteight_q8p.ckpt", "1389019_jibmixflux_v8accentueightnow_q8p.ckpt", "jib_mix_pony_realistic_f16.ckpt", "jib_mix_pony_realistic_clip_vit_l14_f16.ckpt", "jib_mix_pony_realistic_open_clip_vit_bigg14_f16.ckpt", "jib_mix_realistic_xl_f16.ckpt", "jib_mix_realistic_xl_clip_vit_l14_f16.ckpt", "jib_mix_realistic_xl_open_clip_vit_bigg14_f16.ckpt", "jujumix_f16.ckpt", "jujumix_clip_vit_l14_f16.ckpt", "jujumix_open_clip_vit_bigg14_f16.ckpt", "kageillustrious_illustrious_xl_f16.ckpt", "kageillustrious_illustrious_xl_clip_vit_l14_f16.ckpt", "kageillustrious_illustrious_xl_open_clip_vit_bigg14_f16.ckpt", "kantanmix_xlillustrious_f16.ckpt", "kantanmix_xlillustrious_clip_vit_l14_f16.ckpt", "kantanmix_xlillustrious_open_clip_vit_bigg14_f16.ckpt", "kft_requiem_fur_a_dream_illustrious_semi_real_checkpoint_f16.ckpt", "kft_requiem_fur_a_dream_illustrious_semi_real_checkpoint_clip_vit_l14_f16.ckpt", "kft_requiem_fur_a_dream_illustrious_semi_real_checkpoint_open_clip_vit_bigg14_f16.ckpt", "konanmix_noobai_xl_illustriousxl_f16.ckpt", "konanmix_noobai_xl_illustriousxl_clip_vit_l14_f16.ckpt", "konanmix_noobai_xl_illustriousxl_open_clip_vit_bigg14_f16.ckpt", "koronemix_illustrious_f16.ckpt", "koronemix_illustrious_clip_vit_l14_f16.ckpt", "koronemix_illustrious_open_clip_vit_bigg14_f16.ckpt", "872820_lahmysteriousflux_fluxalpha_q8p.ckpt", "like_reality_pony_by_ethanar_f16.ckpt", "like_reality_pony_by_ethanar_clip_vit_l14_f16.ckpt", "like_reality_pony_by_ethanar_open_clip_vit_bigg14_f16.ckpt", "lox_s_souls_mix_prisma__f16.ckpt", "lox_s_souls_mix_prisma__clip_vit_l14_f16.ckpt", "lox_s_souls_mix_prisma__open_clip_vit_bigg14_f16.ckpt", "lunargrapemix_illustrious_f16.ckpt", "lunargrapemix_illustrious_clip_vit_l14_f16.ckpt", "lunargrapemix_illustrious_open_clip_vit_bigg14_f16.ckpt", "835744_lyhanimeflux_delete_q8p.ckpt", "madly_mix_ver_nightnoob_f16.ckpt", "madly_mix_ver_nightnoob_clip_vit_l14_f16.ckpt", "madly_mix_ver_nightnoob_open_clip_vit_bigg14_f16.ckpt", "1247362_majicflus_v10_q8p.ckpt", "meichidarkmix_reload_f16.ckpt", "meichidarkmix_reload_clip_vit_l14_f16.ckpt", "meichidarkmix_reload_open_clip_vit_bigg14_f16.ckpt", "miruku_f16.ckpt", "miruku_clip_vit_l14_f16.ckpt", "miruku_open_clip_vit_bigg14_f16.ckpt", "mistoon_anime_f16.ckpt", "mistoon_anime_clip_vit_l14_f16.ckpt", "mistoon_anime_open_clip_vit_bigg14_f16.ckpt", "mol_keun_mix_f16.ckpt", "mol_keun_mix_clip_vit_l14_f16.ckpt", "mol_keun_mix_open_clip_vit_bigg14_f16.ckpt", "molcajetemix_noobil_f16.ckpt", "molcajetemix_noobil_clip_vit_l14_f16.ckpt", "molcajetemix_noobil_open_clip_vit_bigg14_f16.ckpt", "905329_moxieflux1ds_flux1d8step_q8p.ckpt", "905879_moxieflux1ds_flux1s8step_q8p.ckpt", "883958_moxieflux1ds_v138step_q8p.ckpt", "986682_moxieflux1ds_v14_q8p.ckpt", "1453489_moxieflux1ds_v16d_q8p.ckpt", "1802008_moxieflux1ds_v17s_q8p.ckpt", "1718411_moxiefusionflux_17d_q8p.ckpt", "876813_moxiefusionflux_v1318step_q8p.ckpt", "874291_moxiefusionflux_v132_q8p.ckpt", "873546_moxiefusionflux_v1328step_q8p.ckpt", "913024_moxiefusionflux_v1338step_q8p.ckpt", "943051_moxiefusionflux_v134_q8p.ckpt", "932231_moxiefusionflux_v1348step_q8p.ckpt", "985269_moxiefusionflux_v135_q8p.ckpt", "1255371_moxiefusionflux_v141d_q8p.ckpt", "1249359_moxiefusionflux_v141s_q8p.ckpt", "1292596_moxiefusionflux_v15s_q8p.ckpt", "1473409_moxiefusionflux_v16s_q8p.ckpt", "1742386_moxiefusionflux_v17s_q8p.ckpt", "1505959_msfluxsfwnsfwv3_v3_q8p.ckpt", "866874_myhumanflux_12train_q8p.ckpt", "885693_myhumanflux_myh11_q8p.ckpt", "989443_myhumanflux_myh13_q8p.ckpt", "991687_myhumanflux_myh13fp8_q8p.ckpt", "1288366_nepotism_xdit_q8p.ckpt", "1326315_nepotism_xidit_q8p.ckpt", "nevolution_sdxl_v2_anim_1733673_f16.ckpt", "nevolution_sdxl_v2_anim_1733673_clip_vit_l14_f16.ckpt", "nevolution_sdxl_v2_anim_1733673_open_clip_vit_bigg14_f16.ckpt", "nevolution_sdxl_v2_base_1645671_f16.ckpt", "nevolution_sdxl_v2_base_1645671_clip_vit_l14_f16.ckpt", "nevolution_sdxl_v2_base_1645671_open_clip_vit_bigg14_f16.ckpt", "noobai_xl_nai_xl_f16.ckpt", "noobai_xl_nai_xl_clip_vit_l14_f16.ckpt", "noobai_xl_nai_xl_open_clip_vit_bigg14_f16.ckpt", "nostramix_f16.ckpt", "nostramix_clip_vit_l14_f16.ckpt", "nostramix_open_clip_vit_bigg14_f16.ckpt", "nova_animal_xl_illustrious_v3.0_1634769_f16.ckpt", "nova_animal_xl_illustrious_v3.0_1634769_clip_vit_l14_f16.ckpt", "nova_animal_xl_illustrious_v3.0_1634769_open_clip_vit_bigg14_f16.ckpt", "nova_animal_xl_v4.0_1028888_f16.ckpt", "nova_animal_xl_v4.0_1028888_clip_vit_l14_f16.ckpt", "nova_animal_xl_v4.0_1028888_open_clip_vit_bigg14_f16.ckpt", "nova_furry_xl_illustrious_v6a_1625975_f16.ckpt", "nova_furry_xl_illustrious_v6a_1625975_clip_vit_l14_f16.ckpt", "nova_furry_xl_illustrious_v6a_1625975_open_clip_vit_bigg14_f16.ckpt", "nova_furry_xl_illustrious_v6b_1626156_f16.ckpt", "nova_furry_xl_illustrious_v6b_1626156_clip_vit_l14_f16.ckpt", "nova_furry_xl_illustrious_v6b_1626156_open_clip_vit_bigg14_f16.ckpt", "nova_furry_xl_illustrious_v7a_1759909_f16.ckpt", "nova_furry_xl_illustrious_v7a_1759909_clip_vit_l14_f16.ckpt", "nova_furry_xl_illustrious_v7a_1759909_open_clip_vit_bigg14_f16.ckpt", "nova_furry_xl_illustrious_v7b_1760102_f16.ckpt", "nova_furry_xl_illustrious_v7b_1760102_clip_vit_l14_f16.ckpt", "nova_furry_xl_illustrious_v7b_1760102_open_clip_vit_bigg14_f16.ckpt", "nova_orange_xl_v7.0_1525944_f16.ckpt", "nova_orange_xl_v7.0_1525944_clip_vit_l14_f16.ckpt", "nova_orange_xl_v7.0_1525944_open_clip_vit_bigg14_f16.ckpt", "nova_orange_xl_v9.0_1701002_f16.ckpt", "nova_orange_xl_v9.0_1701002_clip_vit_l14_f16.ckpt", "nova_orange_xl_v9.0_1701002_open_clip_vit_bigg14_f16.ckpt", "nova_3dcg_xl_f16.ckpt", "nova_3dcg_xl_clip_vit_l14_f16.ckpt", "nova_3dcg_xl_open_clip_vit_bigg14_f16.ckpt", "nova_anime_xl_f16.ckpt", "nova_anime_xl_clip_vit_l14_f16.ckpt", "nova_anime_xl_open_clip_vit_bigg14_f16.ckpt", "nova_anime3d_xl_f16.ckpt", "nova_anime3d_xl_clip_vit_l14_f16.ckpt", "nova_anime3d_xl_open_clip_vit_bigg14_f16.ckpt", "nova_asian_xl_f16.ckpt", "nova_asian_xl_clip_vit_l14_f16.ckpt", "nova_asian_xl_open_clip_vit_bigg14_f16.ckpt", "nova_cross_xl_f16.ckpt", "nova_cross_xl_clip_vit_l14_f16.ckpt", "nova_cross_xl_open_clip_vit_bigg14_f16.ckpt", "nova_flat_xl_f16.ckpt", "nova_flat_xl_clip_vit_l14_f16.ckpt", "nova_flat_xl_open_clip_vit_bigg14_f16.ckpt", "nova_reality_xl_f16.ckpt", "nova_reality_xl_clip_vit_l14_f16.ckpt", "nova_reality_xl_open_clip_vit_bigg14_f16.ckpt", "nova_unreal_xl_f16.ckpt", "nova_unreal_xl_clip_vit_l14_f16.ckpt", "nova_unreal_xl_open_clip_vit_bigg14_f16.ckpt", "one_for_all_pony_fantasy_dpovae_f16.ckpt", "one_for_all_pony_fantasy_dpovae_clip_vit_l14_f16.ckpt", "one_for_all_pony_fantasy_dpovae_open_clip_vit_bigg14_f16.ckpt", "oops_all_toons_illustrious_v1.0_f16.ckpt", "oops_all_toons_illustrious_v1.0_clip_vit_l14_f16.ckpt", "oops_all_toons_illustrious_v1.0_open_clip_vit_bigg14_f16.ckpt", "oops_all_vpred_noobai_western_2d_furry_toon_f16.ckpt", "oops_all_vpred_noobai_western_2d_furry_toon_clip_vit_l14_f16.ckpt", "oops_all_vpred_noobai_western_2d_furry_toon_open_clip_vit_bigg14_f16.ckpt", "1308101_originbyn0utis_fluxfp8v1_q8p.ckpt", "photonic_fusion_sdxl_f16.ckpt", "photonic_fusion_sdxl_clip_vit_l14_f16.ckpt", "photonic_fusion_sdxl_open_clip_vit_bigg14_f16.ckpt", "pikon_realism_v2_alt_f16.ckpt", "pikon_realism_v2_alt_q6p_q8p.ckpt", "pikon_realism_v2_alt_clip_vit_l14_f16.ckpt", "pikon_realism_v2_alt_open_clip_vit_bigg14_f16.ckpt", "826571_pixelwave_flux1dev02_q8p.ckpt", "992642_pixelwave_flux1dev03_q8p.ckpt", "1002647_pixelwave_flux1schnell03_q8p.ckpt", "plant_milk_model_suite_flax_1331188_f16.ckpt", "plant_milk_model_suite_flax_1331188_clip_vit_l14_f16.ckpt", "plant_milk_model_suite_flax_1331188_open_clip_vit_bigg14_f16.ckpt", "plant_milk_model_suite_hemp_ii_1714314_f16.ckpt", "plant_milk_model_suite_hemp_ii_1714314_clip_vit_l14_f16.ckpt", "plant_milk_model_suite_hemp_ii_1714314_open_clip_vit_bigg14_f16.ckpt", "pony_realism_v2.1_534642_f16.ckpt", "pony_realism_v2.1_534642_clip_vit_l14_f16.ckpt", "pony_realism_v2.1_534642_open_clip_vit_bigg14_f16.ckpt", "pony_realism_v2.2_914390_f16.ckpt", "pony_realism_v2.2_914390_clip_vit_l14_f16.ckpt", "pony_realism_v2.2_914390_open_clip_vit_bigg14_f16.ckpt", "praeclarus_illustriousxl_f16.ckpt", "praeclarus_illustriousxl_clip_vit_l14_f16.ckpt", "praeclarus_illustriousxl_open_clip_vit_bigg14_f16.ckpt", "prefect_illustrious_xl_v1.0_1379960_f16.ckpt", "prefect_illustrious_xl_v1.0_1379960_clip_vit_l14_f16.ckpt", "prefect_illustrious_xl_v1.0_1379960_open_clip_vit_bigg14_f16.ckpt", "prefect_illustrious_xl_v1.5_1731647_f16.ckpt", "prefect_illustrious_xl_v1.5_1731647_clip_vit_l14_f16.ckpt", "prefect_illustrious_xl_v1.5_1731647_open_clip_vit_bigg14_f16.ckpt", "prefect_pony_xl_f16.ckpt", "prefect_pony_xl_clip_vit_l14_f16.ckpt", "prefect_pony_xl_open_clip_vit_bigg14_f16.ckpt", "806846_projectgaiaflux1d_v10unet_q8p.ckpt", "1451754_project0_real1smfp16_q8p.ckpt", "1591370_project0_real1smv2fp16_q8p.ckpt", "1596255_project0_real1smv2fp8_q8p.ckpt", "1875661_project0_real1smv3fp16_q8p.ckpt", "1878051_project0_real1smv3fp8aio_q8p.ckpt", "1181877_project0_v10fp8unetonly_q8p.ckpt", "1249092_project0_v20fp16_q8p.ckpt", "1249496_project0_v20fp8_q8p.ckpt", "1320268_project0_v30artfp8_q8p.ckpt", "793143_ratatoskranimalcreature_v29_q8p.ckpt", "835047_ratatoskranimalcreature_v40fp8_q8p.ckpt", "873136_ratatoskranimalcreature_v41_q8p.ckpt", "1024165_ratatoskranimalcreature_v594fp8dev1hybrid_q8p.ckpt", "1637227_ratatoskranimalcreature_v667fp16_q8p.ckpt", "1637484_ratatoskranimalcreature_v667fp8_q8p.ckpt", "ratatoskr_animal__creature_and_furry__f16.ckpt", "ratatoskr_animal__creature_and_furry__clip_vit_l14_f16.ckpt", "ratatoskr_animal__creature_and_furry__open_clip_vit_bigg14_f16.ckpt", "1186008_rayflux_v10_q8p.ckpt", "1785042_rayflux_v30aio_q8p.ckpt", "1703341_realdream_flux1v1_q8p.ckpt", "realcartoon_xl_f16.ckpt", "realcartoon_xl_clip_vit_l14_f16.ckpt", "realcartoon_xl_open_clip_vit_bigg14_f16.ckpt", "881836_realflux10b_10bcompactschnell_q8p.ckpt", "882554_realflux10b_10btransformer_q8p.ckpt", "915279_realflux10b_10btransformerdev_q8p.ckpt", "realism_by_stable_yogi_pony_v3_vae_992946_f16.ckpt", "realism_by_stable_yogi_pony_v3_vae_992946_clip_vit_l14_f16.ckpt", "realism_by_stable_yogi_pony_v3_vae_992946_open_clip_vit_bigg14_f16.ckpt", "realism_by_stable_yogi_v4.0_fp16_1422871_f16.ckpt", "realism_by_stable_yogi_v4.0_fp16_1422871_clip_vit_l14_f16.ckpt", "realism_by_stable_yogi_v4.0_fp16_1422871_open_clip_vit_bigg14_f16.ckpt", "realism_sdxl_by_stable_yogi_f16.ckpt", "realism_sdxl_by_stable_yogi_clip_vit_l14_f16.ckpt", "realism_sdxl_by_stable_yogi_open_clip_vit_bigg14_f16.ckpt", "realistic_blend_xl_f16.ckpt", "realistic_blend_xl_clip_vit_l14_f16.ckpt", "realistic_blend_xl_open_clip_vit_bigg14_f16.ckpt", "1138590_redbluefantasy_fluxv10_q8p.ckpt", "1445047_redcraftcadsupdatedjun1_f1fillnsfw_q8p.ckpt", "1315432_redcraftcadsupdatedjun1_newreveal_q8p.ckpt", "1093373_redcraftcadsupdatedjun1_rasch1forge_q8p.ckpt", "1115605_redcraftcadsupdatedjun1_rasch2_q8p.ckpt", "1344905_redcraftcadsupdatedjun1_rasch3rushreveal_q8p.ckpt", "1550408_redcraftcadsupdatedjun1_realreveal5_q8p.ckpt", "1745151_redcraftcadsupdatedjun1_redediticedit11_q8p.ckpt", "1849802_redcraftcadsupdatedjun1_redomniflux1dreamo_q8p.ckpt", "1087807_redcraftcadsupdatedjun1_revealnsfw_q8p.ckpt", "1171942_redcraftcadsupdatedjun1_revealultrav35_q8p.ckpt", "1576605_redcraftcadsupdatedjun1_reveal5sfwultra_q8p.ckpt", "1201074_redcraftcadsupdatedjun1_turborevealhotfix21_q8p.ckpt", "redcraft___cads_updated_may4_commercial___advertising_design_system_f16.ckpt", "redcraft___cads_updated_may4_commercial___advertising_design_system_clip_vit_l14_f16.ckpt", "redcraft___cads_updated_may4_commercial___advertising_design_system_open_clip_vit_bigg14_f16.ckpt", "richyrichmixixl_f16.ckpt", "richyrichmixixl_clip_vit_l14_f16.ckpt", "richyrichmixixl_open_clip_vit_bigg14_f16.ckpt", "rillusm___realistic_il_f16.ckpt", "rillusm___realistic_il_clip_vit_l14_f16.ckpt", "rillusm___realistic_il_open_clip_vit_bigg14_f16.ckpt", "878315_sdvn11ghibliflux_fp8hyper_q8p.ckpt", "silvermoonmix_illustrious_evolved_f16.ckpt", "silvermoonmix_illustrious_evolved_clip_vit_l14_f16.ckpt", "silvermoonmix_illustrious_evolved_open_clip_vit_bigg14_f16.ckpt", "singlo_illustrious_f16.ckpt", "singlo_illustrious_clip_vit_l14_f16.ckpt", "singlo_illustrious_open_clip_vit_bigg14_f16.ckpt", "skibidimix_f16.ckpt", "skibidimix_clip_vit_l14_f16.ckpt", "skibidimix_open_clip_vit_bigg14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_illustrious_v.2_1401686_f16.ckpt", "smooth_mix_noobai_illustrious_pony_illustrious_v.2_1401686_clip_vit_l14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_illustrious_v.2_1401686_open_clip_vit_bigg14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_illustrious_v.3_1470541_f16.ckpt", "smooth_mix_noobai_illustrious_pony_illustrious_v.3_1470541_clip_vit_l14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_illustrious_v.3_1470541_open_clip_vit_bigg14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_noobai_v2.0_1629718_f16.ckpt", "smooth_mix_noobai_illustrious_pony_noobai_v2.0_1629718_clip_vit_l14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_noobai_v2.0_1629718_open_clip_vit_bigg14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_pony_v.3_997031_f16.ckpt", "smooth_mix_noobai_illustrious_pony_pony_v.3_997031_clip_vit_l14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_pony_v.3_997031_open_clip_vit_bigg14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_realism_1675843_f16.ckpt", "smooth_mix_noobai_illustrious_pony_realism_1675843_clip_vit_l14_f16.ckpt", "smooth_mix_noobai_illustrious_pony_realism_1675843_open_clip_vit_bigg14_f16.ckpt", "snowpony_f16.ckpt", "snowpony_clip_vit_l14_f16.ckpt", "snowpony_open_clip_vit_bigg14_f16.ckpt", "steinillustrious_f16.ckpt", "steinillustrious_clip_vit_l14_f16.ckpt", "steinillustrious_open_clip_vit_bigg14_f16.ckpt", "869391_stoiqonewrealityfluxsd35_f1dalpha_q8p.ckpt", "979329_stoiqonewrealityfluxsd35_f1dalphatwo_q8p.ckpt", "897489_stoiqoafroditefluxxl_f1dalpha_q8p.ckpt", "742904_thearamintaexperiment_flux1a1_q8p.ckpt", "throwing_pasta_mix_spaghetti_f16.ckpt", "throwing_pasta_mix_spaghetti_clip_vit_l14_f16.ckpt", "throwing_pasta_mix_spaghetti_open_clip_vit_bigg14_f16.ckpt", "toonify_toonify_illustrious_1495132_f16.ckpt", "toonify_toonify_illustrious_1495132_clip_vit_l14_f16.ckpt", "toonify_toonify_illustrious_1495132_open_clip_vit_bigg14_f16.ckpt", "toonify_toonify_ponydiffusionxl_410539_f16.ckpt", "toonify_toonify_ponydiffusionxl_410539_clip_vit_l14_f16.ckpt", "toonify_toonify_ponydiffusionxl_410539_open_clip_vit_bigg14_f16.ckpt", "tt_animerge_f16.ckpt", "tt_animerge_clip_vit_l14_f16.ckpt", "ultra_realistic_by_stable_yogi_pony_f16.ckpt", "ultra_realistic_by_stable_yogi_pony_clip_vit_l14_f16.ckpt", "ultra_realistic_by_stable_yogi_pony_open_clip_vit_bigg14_f16.ckpt", "1454015_ultrarealfinetune_v1_q8p.ckpt", "1095703_ultrarealfinetune_v10_q8p.ckpt", "1164498_ultrarealfinetune_v20_q8p.ckpt", "1413133_ultrarealfinetune_v4_q8p.ckpt", "umbroxponyxl_f16.ckpt", "umbroxponyxl_clip_vit_l14_f16.ckpt", "umbroxponyxl_open_clip_vit_bigg14_f16.ckpt", "uncanny_valley_f16.ckpt", "uncanny_valley_clip_vit_l14_f16.ckpt", "uncanny_valley_open_clip_vit_bigg14_f16.ckpt", "untitled_pony_f16.ckpt", "untitled_pony_clip_vit_l14_f16.ckpt", "untitled_pony_open_clip_vit_bigg14_f16.ckpt", "988886_verusvision10b_10btransformer_q8p.ckpt", "virtual_diffusion_pony_xl_2025_f16.ckpt", "virtual_diffusion_pony_xl_2025_clip_vit_l14_f16.ckpt", "virtual_diffusion_pony_xl_2025_open_clip_vit_bigg14_f16.ckpt", "vixon_s_dream_weave_f16.ckpt", "vixons_dream_weave_f16.ckpt", "vixon_s_dream_weave_clip_vit_l14_f16.ckpt", "vixon_s_dream_weave_open_clip_vit_bigg14_f16.ckpt", "wai_shuffle_noob_f16.ckpt", "wai_shuffle_noob_clip_vit_l14_f16.ckpt", "wai_shuffle_noob_open_clip_vit_bigg14_f16.ckpt", "862533_whiteflux1_v10_q8p.ckpt", "791130_xehentaianimeflux_03_q8p.ckpt", "807911_xehentaianimeflux_04_q8p.ckpt", "951641_xueronecyantencolor_fluxv10_q8p.ckpt", "zavychromaxl_f16.ckpt", "zavychromaxl_clip_vit_l14_f16.ckpt", "zavychromaxl_open_clip_vit_bigg14_f16.ckpt", "zep9_f16.ckpt", "zep9_clip_vit_l14_f16.ckpt", "zep9_open_clip_vit_bigg14_f16.ckpt"], models: [{ id: "fasth3-omni", rubric: "community", name: "FastH3 Omni", family: "minimax_h3", since: "2026-10-22", flavor: ["ref2va"], modifier: "ref2va", files: [[0, 10], [1, 7], [2, 5]], requires: [3, 4], modes: ["text2video", "image2video"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 512, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: true, decoding_tile_width: 256, decoding_tile_height: 256, decoding_tile_overlap: 64, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, resolution_dependent_shift: false, shift: 12, shift_for_audio: 3, preserve_original_after_inpaint: true, width: 832, steps: 8, num_frames: 124, fps: 24, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, compression_artifacts: "disabled" } } }, { id: "moss_image_sft", rubric: "official", name: "MOSS Image SFT", family: "moss_image", since: "2026-10-20", files: [[5, 10], [6, 7], [7, 5]], requires: [8, 9], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 3, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3, resolution_dependent_shift: false }, negative_prompt: "nsfw, worst quality, bad anatomy, watermark, jpeg artifact" } }, { id: "moss_image_base", rubric: "official", name: "MOSS Image Base", family: "moss_image", since: "2026-10-20", variant: "base", files: [[10, 10], [11, 7], [12, 5]], requires: [8, 9], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 3, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3, resolution_dependent_shift: false }, negative_prompt: "nsfw, worst quality, bad anatomy, watermark, jpeg artifact" } }, { id: "flux-3-klein", rubric: "community", name: "FLUX.3 [klein] 5.6B", family: "flux3_5b", since: "2026-10-20", modifier: "kontext", files: [[13, 10], [14, 7], [15, 5]], requires: [8, 16], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 16, preserve_original_after_inpaint: true, steps: 16, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3, resolution_dependent_shift: false } } }, { id: "flux-3-klein-base", rubric: "community", name: "FLUX.3 [klein] 5.6B Base", family: "flux3_5b", since: "2026-10-20", variant: "base", modifier: "kontext", files: [[17, 10], [18, 7], [19, 5]], requires: [8, 16], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 16, preserve_original_after_inpaint: true, steps: 50, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3, resolution_dependent_shift: false } } }, { id: "flux-3-klein-exact", rubric: "community", name: "FLUX.3 [klein] 5.6B (Exact)", family: "flux3_5b", since: "2026-10-20", modifier: "kontext", files: [[20, 11]], requires: [8, 16], modes: ["text2image", "edit"], recommended: { source: "note", params: { steps: 16, guidance_scale: 1, shift: 16 } } }, { id: "flux-3-klein-base-exact", rubric: "community", name: "FLUX.3 [klein] 5.6B Base (Exact)", family: "flux3_5b", since: "2026-10-20", variant: "base", modifier: "kontext", files: [[21, 11]], requires: [8, 16], modes: ["text2image", "edit"], recommended: { source: "note", params: { steps: 50, guidance_scale: 4, shift: 16 } } }, { id: "qwen-image-2.1-turbo", rubric: "community", name: "Qwen Image 2.1 Turbo", family: "qwen_image_2.1", since: "2026-10-09", variant: "turbo", modifier: "kontext", files: [[22, 10], [23, 7], [24, 5], [25, 4]], requires: [26, 27], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 6.5, preserve_original_after_inpaint: true, steps: 8, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3, resolution_dependent_shift: false } } }, { id: "qwen-image-2.1-turbo-exact", rubric: "community", name: "Qwen Image 2.1 Turbo (Exact)", family: "qwen_image_2.1", since: "2026-10-09", variant: "turbo", modifier: "kontext", files: [[28, 11]], requires: [29, 27], modes: ["text2image", "edit"], recommended: { source: "note", params: { guidance_scale: 1, shift: 6.5 } } }, { id: "qwen-image-2.1-exact", rubric: "community", name: "Qwen Image 2.1 (Exact)", family: "qwen_image_2.1", since: "2026-09-22", modifier: "kontext", files: [[30, 11]], requires: [29, 27], modes: ["text2image", "edit"], recommended: { source: "note", params: { guidance_scale: 1, shift: 1 } } }, { id: "qwen-image-2.1", rubric: "community", name: "Qwen Image 2.1", family: "qwen_image_2.1", since: "2026-09-21", modifier: "kontext", files: [[31, 10], [32, 7], [33, 5], [34, 4]], requires: [26, 27], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 1, preserve_original_after_inpaint: true, steps: 40, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3, resolution_dependent_shift: true } } }, { id: "minimax-h3-fl2va", rubric: "community", name: "MiniMax H3", family: "minimax_h3", since: "2026-09-09", flavor: ["fl2va"], modifier: "fl2va", files: [[35, 10], [36, 7], [37, 5], [38, 4]], requires: [3, 4], modes: ["text2video", "image2video"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 512, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: true, decoding_tile_width: 256, decoding_tile_height: 256, decoding_tile_overlap: 64, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, resolution_dependent_shift: false, shift: 12, shift_for_audio: 3, preserve_original_after_inpaint: true, width: 832, steps: 50, num_frames: 124, fps: 24, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, compression_artifacts: "disabled" } } }, { id: "minimax-h3-ref2va", rubric: "community", name: "MiniMax H3 [ref2va]", family: "minimax_h3", since: "2026-09-09", flavor: ["ref2va"], modifier: "ref2va", files: [[39, 10], [40, 7], [41, 5], [42, 4]], requires: [3, 4], modes: ["text2video", "image2video"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 512, sampler: "DDIMTrailing", strength: 1, sharpness: 0, tiled_decoding: true, decoding_tile_width: 256, decoding_tile_height: 256, decoding_tile_overlap: 64, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, resolution_dependent_shift: false, shift: 12, shift_for_audio: 3, preserve_original_after_inpaint: true, width: 832, steps: 50, num_frames: 124, fps: 24, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, compression_artifacts: "disabled" } } }, { id: "anima-aesthetic-1.1", rubric: "community", name: "Anima Aesthetic 1.1", family: "cosmos2.5_2b", since: "2026-07-16", files: [[43, 11], [44, 10], [45, 5]], requires: [46, 47], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 4, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: true, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, steps: 30, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: "worst quality, low quality, score_1, score_2, score_3, artist name" } }, { id: "anima-turbo-1.0", rubric: "community", name: "Anima Turbo 1.0", family: "cosmos2.5_2b", since: "2026-07-16", variant: "turbo", files: [[48, 11], [49, 10], [50, 5]], requires: [46, 47], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 1, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: true, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, steps: 8, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: "worst quality, low quality, score_1, score_2, score_3, artist name" } }, { id: "anima-base-1.0", rubric: "community", name: "Anima Base 1.0", family: "cosmos2.5_2b", since: "2026-07-16", variant: "base", files: [[51, 11], [52, 10], [53, 5]], requires: [46, 47], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 4, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: true, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, steps: 30, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: "worst quality, low quality, score_1, score_2, score_3, artist name" } }, { id: "krea-2-turbo", rubric: "community", name: "Krea 2 Turbo", family: "krea_2", since: "2026-07-13", variant: "turbo", files: [[54, 10], [55, 9], [56, 7], [57, 5], [58, 4]], requires: [59, 47], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 3, resolution_dependent_shift: false, preserve_original_after_inpaint: true, steps: 8, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "ideogram-4", rubric: "community", name: "Ideogram 4", family: "ideogram_4", since: "2026-07-13", files: [[60, 10], [61, 9], [62, 5], [63, 4]], requires: [8, 64], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 7, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 1, resolution_dependent_shift: false, zero_negative_prompt: true, expand_prompt_to_json: true, preserve_original_after_inpaint: true, steps: 48, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "ideogram-4-instant", rubric: "community", name: "Ideogram 4 Instant", family: "ideogram_4", since: "2026-07-13", variant: "turbo", files: [[65, 10], [66, 9], [67, 5], [68, 4]], requires: [8, 64], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 1, resolution_dependent_shift: false, zero_negative_prompt: true, expand_prompt_to_json: true, preserve_original_after_inpaint: true, steps: 8, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "ideogram-4-fast", rubric: "community", name: "Ideogram 4 Fast", family: "ideogram_4", since: "2026-07-13", variant: "turbo", files: [[69, 10], [70, 9], [71, 5], [72, 4]], requires: [8, 64], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 1, resolution_dependent_shift: false, zero_negative_prompt: true, expand_prompt_to_json: true, preserve_original_after_inpaint: true, steps: 20, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "krea-2-raw", rubric: "community", name: "Krea 2 Raw", family: "krea_2", since: "2026-07-13", variant: "base", files: [[73, 10], [74, 7], [75, 5], [76, 4]], requires: [59, 47], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 3.5, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, resolution_dependent_shift: true, preserve_original_after_inpaint: true, steps: 52, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "seedvr2_3b", rubric: "official", name: "SeedVR2 3B", family: "seedvr2_3b", since: "2026-04-29", modifier: "inpainting", files: [[77, 10], [78, 5], [79, 4]], requires: [80], modes: ["upscale"] }, { id: "seedvr2_7b", rubric: "official", name: "SeedVR2 7B", family: "seedvr2_7b", since: "2026-04-29", modifier: "inpainting", files: [[81, 10], [82, 5], [83, 4]], requires: [80], modes: ["upscale"] }, { id: "ltx_2.3_22b_distilled_1.1", rubric: "official", name: "LTX-2.3 22B [distilled] 1.1", family: "ltx2.3", since: "2026-04-18", variant: "turbo", modifier: "kontext", files: [[84, 10], [85, 5], [86, 4]], requires: [87, 88], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "ernie_image_turbo", rubric: "official", name: "ERNIE Image Turbo 1.0", family: "ernie_image", since: "2026-04-18", variant: "turbo", files: [[89, 10], [90, 5], [91, 4]], requires: [8, 92], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 4, resolution_dependent_shift: false, preserve_original_after_inpaint: true, steps: 8, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: " " } }, { id: "ernie_image", rubric: "official", name: "ERNIE Image Base 1.0", family: "ernie_image", since: "2026-04-18", files: [[93, 10], [94, 5], [95, 4]], requires: [8, 92], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, resolution_dependent_shift: true, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "ernie-image-turbo-1.0-exact", rubric: "community", name: "ERNIE Image Turbo 1.0 (Exact)", family: "ernie_image", since: "2026-04-17", variant: "turbo", files: [[96, 11]], requires: [8, 97], modes: ["text2image"], recommended: { source: "note", params: { guidance_scale: 1 } } }, { id: "ernie-image-1.0-exact", rubric: "community", name: "ERNIE Image Base 1.0 (Exact)", family: "ernie_image", since: "2026-04-17", files: [[98, 11]], requires: [8, 97], modes: ["text2image"] }, { id: "ltx-2.3-22b-distilled-exact", rubric: "community", name: "LTX-2.3 22B [distilled] (Exact)", family: "ltx2.3", since: "2026-03-17", variant: "turbo", modifier: "kontext", files: [[99, 11]], requires: [100, 88], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "ltx-2.3-22b-dev-exact", rubric: "community", name: "LTX-2.3 22B [dev] (Exact)", family: "ltx2.3", since: "2026-03-17", variant: "dev", modifier: "kontext", files: [[101, 11]], requires: [100, 88], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "flux-2-klein-9b-kv", rubric: "community", name: "FLUX.2 [klein] 9B KV", family: "flux2_9b", since: "2026-03-14", flavor: ["kv"], modifier: "kontext_kv", files: [[102, 10], [103, 5], [104, 4]], requires: [8, 105], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 1, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 3, speed_up_with_guidance_embed: true, steps: 4, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "flux-2-klein-9b-kv-exact", rubric: "community", name: "FLUX.2 [klein] 9B KV (Exact)", family: "flux2_9b", since: "2026-03-14", flavor: ["kv"], modifier: "kontext_kv", files: [[106, 11]], requires: [8, 107], modes: ["text2image", "edit"] }, { id: "ltx_2.3_22b_dev", rubric: "official", name: "LTX-2.3 22B [dev]", family: "ltx2.3", since: "2026-03-11", variant: "dev", modifier: "kontext", files: [[108, 10], [109, 5], [110, 4]], requires: [87, 88], modes: ["text2video", "image2video"], modesUncertain: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 768, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 5, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, width: 1280, steps: 30, num_frames: 121, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: true, tea_cache: false, causal_inference: 0, hires_fix_strength: 0.7, hires_fix_height: 384, hires_fix_width: 640, compression_artifacts_quality: 43.1, compression_artifacts: "disabled" }, negative_prompt: "worst quality, inconsistent motion, blurry, jittery, distorted" } }, { id: "ltx_2.3_22b_distilled", rubric: "official", name: "LTX-2.3 22B [distilled]", family: "ltx2.3", since: "2026-03-10", variant: "turbo", modifier: "kontext", files: [[111, 10], [112, 5], [113, 4]], requires: [87, 88], modes: ["text2video", "image2video"], modesUncertain: true, deprecated: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 768, sampler: "TCDTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, width: 1280, steps: 8, num_frames: 121, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: true, tea_cache: false, causal_inference: 0, hires_fix_strength: 0.7, hires_fix_height: 384, hires_fix_width: 640, compression_artifacts_quality: 43.1, compression_artifacts: "disabled" } } }, { id: "z-image-1.0-exact", rubric: "community", name: "Z Image Base 1.0 (Exact)", family: "z_image", since: "2026-02-12", files: [[114, 11]], requires: [115, 116], modes: ["text2image"] }, { id: "z_image_1.0", rubric: "official", name: "Z Image Base 1.0", family: "z_image", since: "2026-01-28", files: [[117, 10], [118, 5], [119, 4]], requires: [115, 120], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, resolution_dependent_shift: true, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "ltx_2_19b_dev", rubric: "official", name: "LTX-2 19B [dev]", family: "ltx2", since: "2026-01-26", variant: "dev", modifier: "kontext", files: [[121, 5], [122, 4]], requires: [87, 123], modes: ["text2video", "image2video"], modesUncertain: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 768, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 5, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, width: 1280, steps: 30, num_frames: 121, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, compression_artifacts_quality: 43.1, compression_artifacts: "h264" }, negative_prompt: "worst quality, inconsistent motion, blurry, jittery, distorted" } }, { id: "ltx_2_19b_distilled", rubric: "official", name: "LTX-2 19B [distilled]", family: "ltx2", since: "2026-01-21", variant: "turbo", modifier: "kontext", files: [[124, 5], [125, 4]], requires: [87, 123], modes: ["text2video", "image2video"], modesUncertain: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 768, sampler: "TCDTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, width: 1280, steps: 8, num_frames: 121, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, compression_artifacts_quality: 43.1, compression_artifacts: "h264" } } }, { id: "flux_2_klein_4b", rubric: "official", name: "FLUX.2 [klein] 4B", family: "flux2_4b", since: "2026-01-17", modifier: "kontext", files: [[126, 10], [127, 5], [128, 4]], requires: [8, 129], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 1, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 3, speed_up_with_guidance_embed: true, steps: 4, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "flux_2_klein_base_4b", rubric: "official", name: "FLUX.2 [klein] 4B Base", family: "flux2_4b", since: "2026-01-17", variant: "base", modifier: "kontext", files: [[130, 10], [131, 5], [132, 4]], requires: [8, 129], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 4, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: true, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, steps: 30, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "flux-2-klein-base-9b", rubric: "community", name: "FLUX.2 [klein] 9B Base", family: "flux2_9b", since: "2026-01-17", variant: "base", modifier: "kontext", files: [[133, 10], [134, 5], [135, 4]], requires: [8, 105], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 4, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: true, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, steps: 30, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "flux-2-klein-4b-exact", rubric: "community", name: "FLUX.2 [klein] 4B (Exact)", family: "flux2_4b", since: "2026-01-17", modifier: "kontext", files: [[136, 11]], requires: [8, 137], modes: ["text2image", "edit"] }, { id: "flux-2-klein-base-4b-exact", rubric: "community", name: "FLUX.2 [klein] 4B Base (Exact)", family: "flux2_4b", since: "2026-01-17", variant: "base", modifier: "kontext", files: [[138, 11]], requires: [8, 137], modes: ["text2image", "edit"] }, { id: "flux-2-klein-9b-exact", rubric: "community", name: "FLUX.2 [klein] 9B (Exact)", family: "flux2_9b", since: "2026-01-17", modifier: "kontext", files: [[139, 11]], requires: [8, 107], modes: ["text2image", "edit"] }, { id: "flux-2-klein-base-9b-exact", rubric: "community", name: "FLUX.2 [klein] 9B Base (Exact)", family: "flux2_9b", since: "2026-01-17", variant: "base", modifier: "kontext", files: [[140, 11]], requires: [8, 107], modes: ["text2image", "edit"] }, { id: "flux-2-klein-9b", rubric: "community", name: "FLUX.2 [klein] 9B", family: "flux2_9b", since: "2026-01-16", modifier: "kontext", files: [[141, 10], [142, 5], [143, 4]], requires: [8, 105], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 1, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 3, speed_up_with_guidance_embed: true, steps: 4, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "qwen_image_2512", rubric: "official", name: "Qwen Image 2512", family: "qwen_image", since: "2025-12-31", files: [[144, 10], [145, 5], [146, 5], [147, 4]], requires: [148, 47], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 2, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: "\u4F4E\u5206\u8FA8\u7387\uFF0C\u4F4E\u753B\u8D28\uFF0C\u80A2\u4F53\u7578\u5F62\uFF0C\u624B\u6307\u7578\u5F62\uFF0C\u753B\u9762\u8FC7\u9971\u548C\uFF0C\u8721\u50CF\u611F\uFF0C\u4EBA\u8138\u65E0\u7EC6\u8282\uFF0C\u8FC7\u5EA6\u5149\u6ED1\uFF0C\u753B\u9762\u5177\u6709AI\u611F\u3002\u6784\u56FE\u6DF7\u4E71\u3002\u6587\u5B57\u6A21\u7CCA\uFF0C\u626D\u66F2\u3002" } }, { id: "qwen_image_2512_bf16", rubric: "official", name: "Qwen Image 2512 (BF16, 8-bit S)", family: "qwen_image", since: "2025-12-31", files: [[149, 10], [150, 4]], requires: [148, 47], modes: ["text2image"] }, { id: "qwen-image-2512-bf-exact", rubric: "community", name: "Qwen Image 2512 (BF16, Exact)", family: "qwen_image", since: "2025-12-31", files: [[151, 11]], requires: [152, 47], modes: ["text2image"] }, { id: "qwen_image_edit_2511", rubric: "official", name: "Qwen Image Edit 2511", family: "qwen_image", since: "2025-12-23", modifier: "qwenimage_edit_2511", files: [[153, 10], [154, 5], [155, 5], [156, 4]], requires: [148, 157, 47], modes: ["edit"], modesUncertain: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 2, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: " " } }, { id: "qwen_image_edit_2511_bf16", rubric: "official", name: "Qwen Image Edit 2511 (BF16, 8-bit S)", family: "qwen_image", since: "2025-12-23", modifier: "qwenimage_edit_2511", files: [[158, 10], [159, 4]], requires: [148, 157, 47], modes: ["edit"], modesUncertain: true }, { id: "qwen_image_layered_1.0", rubric: "official", name: "Qwen Image Layered 1.0 (BF16)", family: "qwen_image", since: "2025-12-20", modifier: "qwenimage_layered", files: [[160, 5]], requires: [148, 161], modes: ["edit"], modesUncertain: true }, { id: "qwen_image_layered_1.0_bf16", rubric: "official", name: "Qwen Image Layered 1.0 (BF16, 6-bit)", family: "qwen_image", since: "2025-12-20", modifier: "qwenimage_layered", files: [[162, 4]], requires: [148, 161], modes: ["edit"], modesUncertain: true }, { id: "flux-2-dev", rubric: "community", name: "FLUX.2 [dev]", family: "flux2", since: "2025-12-17", variant: "dev", modifier: "kontext", files: [[163, 10], [164, 5], [165, 4]], requires: [8, 166], modes: ["text2image", "edit"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_embed: 4.5, guidance_scale: 4.5, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: true, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 1, speed_up_with_guidance_embed: true, steps: 28, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "flux-2-dev-exact", rubric: "community", name: "FLUX.2 [dev] (Exact)", family: "flux2", since: "2025-12-17", variant: "dev", modifier: "kontext", files: [[167, 11]], requires: [8, 168], modes: ["text2image", "edit"] }, { id: "z-image-turbo-1.0-exact", rubric: "community", name: "Z Image Turbo 1.0 (Exact)", family: "z_image", since: "2025-12-05", variant: "turbo", files: [[169, 11]], requires: [115, 116], modes: ["text2image"] }, { id: "z_image_turbo_1.0", rubric: "official", name: "Z Image Turbo 1.0", family: "z_image", since: "2025-12-03", variant: "turbo", files: [[170, 10], [171, 5], [172, 4]], requires: [115, 120], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 1, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 3, resolution_dependent_shift: false, preserve_original_after_inpaint: true, steps: 8, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: " " } }, { id: "anisora-v3.2-i2v-wan-2.2-a14b-hne", rubric: "community", name: "AniSora v3.2 I2V Wan 2.2 A14B High Noise Expert", family: "wan_v2.1_14b", since: "2025-11-19", modifier: "inpainting", files: [[173, 5], [174, 4]], requires: [175, 176], modes: ["image2video"] }, { id: "anisora-v3.2-i2v-wan-2.2-a14b-lne", rubric: "community", name: "AniSora v3.2 I2V Wan 2.2 A14B Low Noise Expert", family: "wan_v2.1_14b", since: "2025-11-19", modifier: "inpainting", files: [[177, 5], [178, 4]], requires: [175, 176], modes: ["image2video"] }, { id: "chronoedit-14b", rubric: "community", name: "ChronoEdit 14B", family: "wan_v2.1_14b", since: "2025-11-19", modifier: "inpainting", files: [[179, 5], [180, 4]], requires: [181, 175, 176], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "wan-v2.2-a14b-hne-t2v-lightning-250928", rubric: "community", name: "Wan v2.2 High Noise Expert T2V A14B Lightning 250928", family: "wan_v2.1_14b", since: "2025-10-06", variant: "turbo", files: [[182, 5], [183, 4]], requires: [175, 176], modes: ["text2video"], recommended: { source: "note", params: { steps: 4, guidance_scale: 1 } } }, { id: "qwen-image-edit-2509-bf-exact", rubric: "community", name: "Qwen Image Edit 2509 (BF16, Exact)", family: "qwen_image", since: "2025-10-02", modifier: "qwenimage_edit_plus", files: [[184, 11]], requires: [152, 157, 47], modes: ["edit"], modesUncertain: true }, { id: "qwen-image-edit-2509-exact", rubric: "community", name: "Qwen Image Edit 2509 (Exact)", family: "qwen_image", since: "2025-10-02", modifier: "qwenimage_edit_plus", files: [[185, 11]], requires: [152, 157, 47], modes: ["edit"], modesUncertain: true }, { id: "qwen_image_1.0_bf16", rubric: "official", name: "Qwen Image 1.0 (BF16, 6-bit)", family: "qwen_image", since: "2025-09-30", files: [[186, 4]], requires: [148, 47], modes: ["text2image"] }, { id: "qwen_image_edit_2509_bf16", rubric: "official", name: "Qwen Image Edit 2509 (BF16, 6-bit)", family: "qwen_image", since: "2025-09-30", modifier: "qwenimage_edit_plus", files: [[187, 4]], requires: [148, 157, 47], modes: ["edit"], modesUncertain: true }, { id: "qwen_image_edit_2509", rubric: "official", name: "Qwen Image Edit 2509", family: "qwen_image", since: "2025-09-25", modifier: "qwenimage_edit_plus", files: [[188, 5], [189, 5], [190, 4]], requires: [148, 157, 47], modes: ["edit"], modesUncertain: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 2, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: " " } }, { id: "wan_v2.2_5b_ti2v", rubric: "official", name: "Wan 2.2 TI2V 5B", family: "wan_v2.2_5b", since: "2025-09-23", files: [[191, 11], [192, 5]], requires: [175, 193], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "qwen_image_edit_1.0", rubric: "official", name: "Qwen Image Edit 1.0", family: "qwen_image", since: "2025-08-20", modifier: "kontext", files: [[194, 5], [195, 4]], requires: [148, 157, 47], modes: ["edit"], modesUncertain: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 2, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: " " } }, { id: "qwen-image-1.0-bf-exact", rubric: "community", name: "Qwen Image 1.0 (BF16, Exact)", family: "qwen_image", since: "2025-08-13", files: [[196, 11]], requires: [152, 47], modes: ["text2image"] }, { id: "qwen-image-1.0-exact", rubric: "community", name: "Qwen Image 1.0 (Exact)", family: "qwen_image", since: "2025-08-13", files: [[197, 11]], requires: [152, 47], modes: ["text2image"] }, { id: "chroma-1-hd", rubric: "community", name: "Chroma1 HD", family: "flux1", since: "2025-08-13", files: [[198, 5], [199, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "qwen_image_1.0", rubric: "official", name: "Qwen Image 1.0", family: "qwen_image", since: "2025-08-11", files: [[202, 5], [203, 5], [204, 4]], requires: [148, 47], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 2, preserve_original_after_inpaint: true, steps: 30, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: " " } }, { id: "flux-1-krea-dev", rubric: "community", name: "FLUX.1 Krea [dev]", family: "flux1", since: "2025-07-31", variant: "dev", files: [[205, 5], [206, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "wan_v2.2_a14b_hne_i2v", rubric: "official", name: "Wan 2.2 High Noise Expert I2V A14B", family: "wan_v2.1_14b", since: "2025-07-30", modifier: "inpainting", files: [[207, 10], [208, 5], [209, 4]], requires: [175, 176], modes: ["image2video"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 448, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 3.5, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, width: 832, refiner_model: "wan_v2.2_a14b_lne_i2v_q6p_svd.ckpt", refiner_start: 0.1, steps: 30, num_frames: 81, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: "\u8272\u8C03\u8273\u4E3D\uFF0C\u8FC7\u66DD\uFF0C\u9759\u6001\uFF0C\u7EC6\u8282\u6A21\u7CCA\u4E0D\u6E05\uFF0C\u5B57\u5E55\uFF0C\u98CE\u683C\uFF0C\u4F5C\u54C1\uFF0C\u753B\u4F5C\uFF0C\u753B\u9762\uFF0C\u9759\u6B62\uFF0C\u6574\u4F53\u53D1\u7070\uFF0C\u6700\u5DEE\u8D28\u91CF\uFF0C\u4F4E\u8D28\u91CF\uFF0CJPEG\u538B\u7F29\u6B8B\u7559\uFF0C\u4E11\u964B\u7684\uFF0C\u6B8B\u7F3A\u7684\uFF0C\u591A\u4F59\u7684\u624B\u6307\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u624B\u90E8\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u8138\u90E8\uFF0C\u7578\u5F62\u7684\uFF0C\u6BC1\u5BB9\u7684\uFF0C\u5F62\u6001\u7578\u5F62\u7684\u80A2\u4F53\uFF0C\u624B\u6307\u878D\u5408\uFF0C\u9759\u6B62\u4E0D\u52A8\u7684\u753B\u9762\uFF0C\u6742\u4E71\u7684\u80CC\u666F\uFF0C\u4E09\u6761\u817F\uFF0C\u80CC\u666F\u4EBA\u5F88\u591A\uFF0C\u5012\u7740\u8D70" } }, { id: "wan_v2.2_a14b_lne_i2v", rubric: "official", name: "Wan 2.2 Low Noise Expert I2V A14B", family: "wan_v2.1_14b", since: "2025-07-30", modifier: "inpainting", files: [[210, 10], [211, 5], [212, 4]], requires: [175, 176], modes: ["image2video"] }, { id: "chroma-v48-detail-calibrated", rubric: "community", name: "Chroma v48 Detail Calibrated", family: "flux1", since: "2025-07-30", files: [[213, 5], [214, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "wan_v2.2_a14b_hne_t2v", rubric: "official", name: "Wan 2.2 High Noise Expert T2V A14B", family: "wan_v2.1_14b", since: "2025-07-29", files: [[215, 10], [216, 5], [217, 4]], requires: [175, 176], modes: ["text2video"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 448, sampler: "UniPCTrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 4, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 8, preserve_original_after_inpaint: true, width: 832, refiner_model: "wan_v2.2_a14b_lne_t2v_q6p_svd.ckpt", refiner_start: 0.125, steps: 30, num_frames: 81, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: "\u8272\u8C03\u8273\u4E3D\uFF0C\u8FC7\u66DD\uFF0C\u9759\u6001\uFF0C\u7EC6\u8282\u6A21\u7CCA\u4E0D\u6E05\uFF0C\u5B57\u5E55\uFF0C\u98CE\u683C\uFF0C\u4F5C\u54C1\uFF0C\u753B\u4F5C\uFF0C\u753B\u9762\uFF0C\u9759\u6B62\uFF0C\u6574\u4F53\u53D1\u7070\uFF0C\u6700\u5DEE\u8D28\u91CF\uFF0C\u4F4E\u8D28\u91CF\uFF0CJPEG\u538B\u7F29\u6B8B\u7559\uFF0C\u4E11\u964B\u7684\uFF0C\u6B8B\u7F3A\u7684\uFF0C\u591A\u4F59\u7684\u624B\u6307\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u624B\u90E8\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u8138\u90E8\uFF0C\u7578\u5F62\u7684\uFF0C\u6BC1\u5BB9\u7684\uFF0C\u5F62\u6001\u7578\u5F62\u7684\u80A2\u4F53\uFF0C\u624B\u6307\u878D\u5408\uFF0C\u9759\u6B62\u4E0D\u52A8\u7684\u753B\u9762\uFF0C\u6742\u4E71\u7684\u80CC\u666F\uFF0C\u4E09\u6761\u817F\uFF0C\u80CC\u666F\u4EBA\u5F88\u591A\uFF0C\u5012\u7740\u8D70" } }, { id: "wan_v2.2_a14b_lne_t2v", rubric: "official", name: "Wan 2.2 Low Noise Expert T2V A14B", family: "wan_v2.1_14b", since: "2025-07-29", files: [[218, 10], [219, 5], [220, 4]], requires: [175, 176], modes: ["text2video"] }, { id: "chroma-v47-detail-calibrated", rubric: "community", name: "Chroma v47 Detail Calibrated", family: "flux1", since: "2025-07-25", files: [[221, 5], [222, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "hidream_e1_1", rubric: "official", name: "HiDream E1-1", family: "hidream_i1", since: "2025-07-17", modifier: "editing", files: [[223, 5], [224, 3]], requires: [115, 225, 226, 201], modes: ["edit"], modesUncertain: true }, { id: "hidream-e1-1-exact", rubric: "community", name: "HiDream E1-1 (Exact)", family: "hidream_i1", since: "2025-07-17", modifier: "editing", files: [[227, 11]], requires: [115, 228, 226, 229, 230], modes: ["edit"], modesUncertain: true }, { id: "flux-1-kontext-dev", rubric: "community", name: "FLUX.1 Kontext [dev]", family: "flux1", since: "2025-06-26", variant: "dev", modifier: "kontext", files: [[231, 5], [232, 3]], requires: [200, 115, 201], modes: ["edit"], modesUncertain: true }, { id: "flux-1-kontext-dev-exact", rubric: "community", name: "FLUX.1 Kontext [dev] (Exact)", family: "flux1", since: "2025-06-26", variant: "dev", modifier: "kontext", files: [[233, 11]], requires: [200, 115, 230], modes: ["edit"], modesUncertain: true }, { id: "wan-2.1-14b-t2v-fusionx", rubric: "community", name: "Wan 2.1 14B T2V FusionX", family: "wan_v2.1_14b", since: "2025-06-22", files: [[234, 5], [235, 4]], requires: [175, 176], modes: ["text2video"] }, { id: "wan-2.1-14b-i2v-fusionx", rubric: "community", name: "Wan 2.1 14B I2V FusionX", family: "wan_v2.1_14b", since: "2025-06-22", modifier: "inpainting", files: [[236, 5], [237, 4]], requires: [181, 175, 176], modes: ["image2video"] }, { id: "rayflux-v3.0", rubric: "community", name: "RayFLUX v3.0", family: "flux1", since: "2025-06-19", files: [[238, 5], [239, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "pixelwave-flux-1-schnell-04", rubric: "community", name: "PixelWave FLUX.1 Schnell 04", family: "flux1", since: "2025-05-13", variant: "turbo", files: [[240, 5], [241, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "juggernaut-xl-ragnarok", rubric: "community", name: "Juggernaut XL Ragnarok", family: "sdxl_base_v0.9", since: "2025-05-13", files: [[242, 11], [243, 5]], requires: [244, 245, 246], modes: ["text2image"] }, { id: "hidream_e1_full", rubric: "official", name: "HiDream E1 [full]", family: "hidream_i1", since: "2025-04-28", modifier: "editing", files: [[247, 5], [248, 3]], requires: [115, 225, 226, 201], modes: ["edit"], modesUncertain: true }, { id: "wan-2.1-14b-v1.1-fun-inp", rubric: "community", name: "Wan 2.1 14B v1.1 Fun InP", family: "wan_v2.1_14b", since: "2025-04-26", modifier: "inpainting", files: [[249, 5], [250, 4]], requires: [181, 175, 176], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "wan-2.1-1.3b-v1.1-fun-inp", rubric: "community", name: "Wan 2.1 1.3B v1.1 Fun InP", family: "wan_v2.1_1.3b", since: "2025-04-26", modifier: "inpainting", files: [[251, 11], [252, 5]], requires: [181, 175, 176], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "skyreels-v2-14b-i2v-540p", rubric: "community", name: "SkyReels v2 I2V 14B 540p", family: "wan_v2.1_14b", since: "2025-04-25", modifier: "inpainting", files: [[253, 5], [254, 4]], requires: [181, 175, 176], modes: ["image2video"] }, { id: "skyreels-v2-14b-i2v-720p", rubric: "community", name: "SkyReels v2 I2V 14B 720p", family: "wan_v2.1_14b", since: "2025-04-25", modifier: "inpainting", files: [[255, 5], [256, 4]], requires: [181, 175, 176], modes: ["image2video"] }, { id: "skyreels-v2-14b-t2v-540p", rubric: "community", name: "SkyReels v2 T2V 14B 540p", family: "wan_v2.1_14b", since: "2025-04-25", files: [[181, 11], [257, 5], [258, 4]], requires: [181, 175, 176], modes: ["text2video"] }, { id: "skyreels-v2-14b-t2v-720p", rubric: "community", name: "SkyReels v2 T2V 14B 720p", family: "wan_v2.1_14b", since: "2025-04-25", files: [[181, 11], [259, 5], [260, 4]], requires: [181, 175, 176], modes: ["text2video"] }, { id: "hidream-i1-dev-exact", rubric: "community", name: "HiDream I1 [dev] (Exact)", family: "hidream_i1", since: "2025-04-24", variant: "dev", files: [[261, 11]], requires: [115, 228, 226, 229, 230], modes: ["text2image"] }, { id: "hidream-i1-full-exact", rubric: "community", name: "HiDream I1 [full] (Exact)", family: "hidream_i1", since: "2025-04-24", files: [[262, 11]], requires: [115, 228, 226, 229, 230], modes: ["text2image"] }, { id: "hidream-i1-fast-exact", rubric: "community", name: "HiDream I1 [fast] (Exact)", family: "hidream_i1", since: "2025-04-24", variant: "turbo", files: [[263, 11]], requires: [115, 228, 226, 229, 230], modes: ["text2image"] }, { id: "skyreels-v2-1.3b-i2v-540p", rubric: "community", name: "SkyReels v2 I2V 1.3B 540p", family: "wan_v2.1_1.3b", since: "2025-04-24", modifier: "inpainting", files: [[264, 11], [265, 5]], requires: [181, 175, 176], modes: ["image2video"] }, { id: "hidream_i1_fast", rubric: "official", name: "HiDream I1 [fast]", family: "hidream_i1", since: "2025-04-22", variant: "turbo", files: [[266, 10], [267, 5], [268, 3]], requires: [115, 225, 226, 201], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 1, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "EulerATrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, separate_t5: false, sharpness: 0, shift: 3, steps: 16, strength: 1, tea_cache: false, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024 } } }, { id: "hidream_i1_full", rubric: "official", name: "HiDream I1 [full]", family: "hidream_i1", since: "2025-04-22", files: [[269, 10], [270, 5], [271, 3]], requires: [115, 225, 226, 201], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 5, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "EulerATrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, separate_t5: false, sharpness: 0, shift: 3, steps: 40, strength: 1, tea_cache: false, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.25, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "hidream_i1_dev", rubric: "official", name: "HiDream I1 [dev]", family: "hidream_i1", since: "2025-04-21", variant: "dev", files: [[272, 10], [273, 5], [274, 3]], requires: [115, 225, 226, 201], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 1, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "EulerATrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, separate_t5: false, sharpness: 0, shift: 6, steps: 28, strength: 1, tea_cache: false, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024 } } }, { id: "wan-2.1-14b-fun-inp", rubric: "community", name: "Wan 2.1 14B Fun InP", family: "wan_v2.1_14b", since: "2025-03-28", modifier: "inpainting", files: [[275, 5], [276, 4]], requires: [181, 175, 176], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "wan-2.1-1.3b-fun-inp", rubric: "community", name: "Wan 2.1 1.3B Fun InP", family: "wan_v2.1_1.3b", since: "2025-03-27", modifier: "inpainting", files: [[277, 11], [278, 5]], requires: [181, 175, 176], modes: ["text2video", "image2video"], modesUncertain: true }, { id: "wan_v2.1_14b_i2v_480p", rubric: "official", name: "Wan 2.1 I2V 14B 480p", family: "wan_v2.1_14b", since: "2025-03-20", modifier: "inpainting", files: [[279, 5], [280, 4]], requires: [181, 175, 176], modes: ["image2video"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 448, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 5, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 3, preserve_original_after_inpaint: true, width: 832, steps: 30, num_frames: 81, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0 }, negative_prompt: "\u8272\u8C03\u8273\u4E3D\uFF0C\u8FC7\u66DD\uFF0C\u9759\u6001\uFF0C\u7EC6\u8282\u6A21\u7CCA\u4E0D\u6E05\uFF0C\u5B57\u5E55\uFF0C\u98CE\u683C\uFF0C\u4F5C\u54C1\uFF0C\u753B\u4F5C\uFF0C\u753B\u9762\uFF0C\u9759\u6B62\uFF0C\u6574\u4F53\u53D1\u7070\uFF0C\u6700\u5DEE\u8D28\u91CF\uFF0C\u4F4E\u8D28\u91CF\uFF0CJPEG\u538B\u7F29\u6B8B\u7559\uFF0C\u4E11\u964B\u7684\uFF0C\u6B8B\u7F3A\u7684\uFF0C\u591A\u4F59\u7684\u624B\u6307\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u624B\u90E8\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u8138\u90E8\uFF0C\u7578\u5F62\u7684\uFF0C\u6BC1\u5BB9\u7684\uFF0C\u5F62\u6001\u7578\u5F62\u7684\u80A2\u4F53\uFF0C\u624B\u6307\u878D\u5408\uFF0C\u9759\u6B62\u4E0D\u52A8\u7684\u753B\u9762\uFF0C\u6742\u4E71\u7684\u80CC\u666F\uFF0C\u4E09\u6761\u817F\uFF0C\u80CC\u666F\u4EBA\u5F88\u591A\uFF0C\u5012\u7740\u8D70" } }, { id: "wan_v2.1_14b_i2v_720p", rubric: "official", name: "Wan 2.1 I2V 14B 720p", family: "wan_v2.1_14b", since: "2025-03-20", modifier: "inpainting", files: [[281, 5], [282, 4]], requires: [181, 175, 176], modes: ["image2video"], recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 768, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 5, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, width: 1280, steps: 30, num_frames: 81, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0 }, negative_prompt: "\u8272\u8C03\u8273\u4E3D\uFF0C\u8FC7\u66DD\uFF0C\u9759\u6001\uFF0C\u7EC6\u8282\u6A21\u7CCA\u4E0D\u6E05\uFF0C\u5B57\u5E55\uFF0C\u98CE\u683C\uFF0C\u4F5C\u54C1\uFF0C\u753B\u4F5C\uFF0C\u753B\u9762\uFF0C\u9759\u6B62\uFF0C\u6574\u4F53\u53D1\u7070\uFF0C\u6700\u5DEE\u8D28\u91CF\uFF0C\u4F4E\u8D28\u91CF\uFF0CJPEG\u538B\u7F29\u6B8B\u7559\uFF0C\u4E11\u964B\u7684\uFF0C\u6B8B\u7F3A\u7684\uFF0C\u591A\u4F59\u7684\u624B\u6307\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u624B\u90E8\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u8138\u90E8\uFF0C\u7578\u5F62\u7684\uFF0C\u6BC1\u5BB9\u7684\uFF0C\u5F62\u6001\u7578\u5F62\u7684\u80A2\u4F53\uFF0C\u624B\u6307\u878D\u5408\uFF0C\u9759\u6B62\u4E0D\u52A8\u7684\u753B\u9762\uFF0C\u6742\u4E71\u7684\u80CC\u666F\uFF0C\u4E09\u6761\u817F\uFF0C\u80CC\u666F\u4EBA\u5F88\u591A\uFF0C\u5012\u7740\u8D70" } }, { id: "wan_v2.1_14b_720p", rubric: "official", name: "Wan 2.1 T2V 14B", family: "wan_v2.1_14b", since: "2025-03-12", files: [[283, 5], [284, 4], [285, 3]], requires: [175, 176], modes: ["text2video", "image2video"], modesUncertain: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 448, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 5, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, width: 832, steps: 30, num_frames: 81, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.2, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: "\u8272\u8C03\u8273\u4E3D\uFF0C\u8FC7\u66DD\uFF0C\u9759\u6001\uFF0C\u7EC6\u8282\u6A21\u7CCA\u4E0D\u6E05\uFF0C\u5B57\u5E55\uFF0C\u98CE\u683C\uFF0C\u4F5C\u54C1\uFF0C\u753B\u4F5C\uFF0C\u753B\u9762\uFF0C\u9759\u6B62\uFF0C\u6574\u4F53\u53D1\u7070\uFF0C\u6700\u5DEE\u8D28\u91CF\uFF0C\u4F4E\u8D28\u91CF\uFF0CJPEG\u538B\u7F29\u6B8B\u7559\uFF0C\u4E11\u964B\u7684\uFF0C\u6B8B\u7F3A\u7684\uFF0C\u591A\u4F59\u7684\u624B\u6307\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u624B\u90E8\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u8138\u90E8\uFF0C\u7578\u5F62\u7684\uFF0C\u6BC1\u5BB9\u7684\uFF0C\u5F62\u6001\u7578\u5F62\u7684\u80A2\u4F53\uFF0C\u624B\u6307\u878D\u5408\uFF0C\u9759\u6B62\u4E0D\u52A8\u7684\u753B\u9762\uFF0C\u6742\u4E71\u7684\u80CC\u666F\uFF0C\u4E09\u6761\u817F\uFF0C\u80CC\u666F\u4EBA\u5F88\u591A\uFF0C\u5012\u7740\u8D70" } }, { id: "wan_v2.1_1.3b_480p", rubric: "official", name: "Wan 2.1 T2V 1.3B", family: "wan_v2.1_1.3b", since: "2025-03-11", files: [[286, 11], [287, 5]], requires: [175, 176], modes: ["text2video", "image2video"], modesUncertain: true, recommended: { source: "config", params: { batch_count: 1, seed_mode: 2, height: 448, sampler: "EulerATrailing", strength: 1, sharpness: 0, tiled_decoding: false, batch_size: 1, tiled_diffusion: false, guidance_scale: 5, loras: [], controls: [], clip_skip: 1, mask_blur: 1.5, shift: 5, preserve_original_after_inpaint: true, width: 832, steps: 30, num_frames: 81, upscaler_scale_factor: 0, mask_blur_outset: 0, hires_fix: false, tea_cache: false, causal_inference: 0, tea_cache_threshold: 0.15, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 }, negative_prompt: "\u8272\u8C03\u8273\u4E3D\uFF0C\u8FC7\u66DD\uFF0C\u9759\u6001\uFF0C\u7EC6\u8282\u6A21\u7CCA\u4E0D\u6E05\uFF0C\u5B57\u5E55\uFF0C\u98CE\u683C\uFF0C\u4F5C\u54C1\uFF0C\u753B\u4F5C\uFF0C\u753B\u9762\uFF0C\u9759\u6B62\uFF0C\u6574\u4F53\u53D1\u7070\uFF0C\u6700\u5DEE\u8D28\u91CF\uFF0C\u4F4E\u8D28\u91CF\uFF0CJPEG\u538B\u7F29\u6B8B\u7559\uFF0C\u4E11\u964B\u7684\uFF0C\u6B8B\u7F3A\u7684\uFF0C\u591A\u4F59\u7684\u624B\u6307\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u624B\u90E8\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u8138\u90E8\uFF0C\u7578\u5F62\u7684\uFF0C\u6BC1\u5BB9\u7684\uFF0C\u5F62\u6001\u7578\u5F62\u7684\u80A2\u4F53\uFF0C\u624B\u6307\u878D\u5408\uFF0C\u9759\u6B62\u4E0D\u52A8\u7684\u753B\u9762\uFF0C\u6742\u4E71\u7684\u80CC\u666F\uFF0C\u4E09\u6761\u817F\uFF0C\u80CC\u666F\u4EBA\u5F88\u591A\uFF0C\u5012\u7740\u8D70" } }, { id: "skyreels-v1-hunyuan-t2v-544p", rubric: "community", name: "SkyReels v1 Hunyuan T2V 544p", family: "hunyuan_video", since: "2025-02-22", files: [[288, 5], [289, 3]], requires: [200, 290, 291], modes: ["text2video"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_embed: 1, guidance_scale: 6, height: 512, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 7, speed_up_with_guidance_embed: false, steps: 30, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 960, num_frames: 97 }, negative_prompt: "Aerial view, aerial view, overexposed, low quality, deformation, a poor composition, bad hands, bad teeth, bad eyes, bad limbs, distortion" } }, { id: "skyreels-v1-hunyuan-i2v-544p", rubric: "community", name: "SkyReels v1 Hunyuan I2V 544p", family: "hunyuan_video", since: "2025-02-22", modifier: "inpainting", files: [[292, 5], [293, 3]], requires: [200, 290, 291], modes: ["image2video"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_embed: 1, guidance_scale: 6, height: 960, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 7, speed_up_with_guidance_embed: false, steps: 30, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 512, num_frames: 97 }, negative_prompt: "Aerial view, aerial view, overexposed, low quality, deformation, a poor composition, bad hands, bad teeth, bad eyes, bad limbs, distortion" } }, { id: "devmode-v0.3-turbo", rubric: "community", name: "devMODE v0.3 Turbo", family: "flux1", since: "2025-02-12", variant: "turbo", files: [[294, 5], [295, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "shuttle-v3.1-aesthetic", rubric: "community", name: "Shuttle v3.1 Aesthetic", family: "flux1", since: "2025-02-11", files: [[296, 5], [297, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "shuttle-jaguar", rubric: "community", name: "Shuttle Jaguar", family: "flux1", since: "2025-02-11", files: [[298, 5], [299, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "schnellmode-v3.3", rubric: "community", name: "schnellMODE v3.3", family: "flux1", since: "2025-02-11", files: [[300, 5], [301, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "artsy-vibe-v1", rubric: "community", name: "Artsy Vibe v1", family: "flux1", since: "2025-02-11", files: [[302, 5], [303, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "hunyuan-video-t2v-720p", rubric: "community", name: "Hunyuan Video T2V 720p", family: "hunyuan_video", since: "2025-01-30", files: [[304, 5], [305, 3]], requires: [200, 290, 291], modes: ["text2video"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_embed: 6, guidance_scale: 6, height: 512, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "DDIMTrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 7, speed_up_with_guidance_embed: true, steps: 30, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 960, num_frames: 129, tea_cache_threshold: 0.15, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "flux-1-canny-dev", rubric: "community", name: "FLUX.1 Canny [dev]", family: "flux1", since: "2024-11-22", variant: "dev", modifier: "canny", files: [[306, 5], [307, 3]], requires: [200, 115, 201], modes: ["control-model"] }, { id: "flux-1-dev-de-distill", rubric: "community", name: "FLUX.1 [dev] De-distill", family: "flux1", since: "2024-11-22", variant: "dev", files: [[308, 5], [309, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "flux-1-fill-dev", rubric: "community", name: "FLUX.1 Fill [dev]", family: "flux1", since: "2024-11-21", variant: "dev", modifier: "inpainting", files: [[310, 5], [311, 3]], requires: [200, 115, 201], modes: ["inpaint-model"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_embed: 50, guidance_scale: 50, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: true, sampler: "EulerATrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 1, speed_up_with_guidance_embed: true, steps: 28, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024 } } }, { id: "flux-1-depth-dev", rubric: "community", name: "FLUX.1 Depth [dev]", family: "flux1", since: "2024-11-21", variant: "dev", modifier: "depth", files: [[312, 5], [313, 3]], requires: [200, 115, 201], modes: ["control-model"] }, { id: "sd3-medium-3.5", rubric: "community", name: "SD3 Medium 3.5", family: "sd3", since: "2024-11-10", files: [[314, 11], [315, 5]], requires: [200, 316, 317, 201], modes: ["text2image"] }, { id: "sd3-large-turbo-3.5", rubric: "community", name: "SD3 Large Turbo 3.5", family: "sd3_large", since: "2024-10-22", variant: "turbo", files: [[318, 5], [319, 4]], requires: [200, 316, 317, 201], modes: ["text2image"] }, { id: "sd3-large-3.5", rubric: "community", name: "SD3 Large 3.5", family: "sd3_large", since: "2024-10-22", files: [[320, 5], [321, 4]], requires: [200, 316, 317, 201], modes: ["text2image"] }, { id: "sd3-large-3.5-exact", rubric: "community", name: "SD3 Large 3.5 (Exact)", family: "sd3_large", since: "2024-10-22", files: [[322, 11]], requires: [200, 316, 317, 201], modes: ["text2image"] }, { id: "ootd-vton-upper-body-v1", rubric: "community", name: "Outfitting Fusion Virtual Try-on (Upper-Body)", family: "v1", since: "2024-08-26", modifier: "double", files: [[323, 11]], requires: [200, 324], modes: ["edit"], modesUncertain: true }, { id: "ootd-vton-full-body-v1", rubric: "community", name: "Outfitting Fusion Virtual Try-on (Full-Body)", family: "v1", since: "2024-08-26", modifier: "double", files: [[325, 11]], requires: [200, 324], modes: ["edit"], modesUncertain: true }, { id: "flux-1-dev-exact", rubric: "community", name: "FLUX.1 [dev] (Exact)", family: "flux1", since: "2024-08-17", variant: "dev", files: [[326, 11]], requires: [200, 115, 230], modes: ["text2image"] }, { id: "flux-1-dev", rubric: "community", name: "FLUX.1 [dev]", family: "flux1", since: "2024-08-05", variant: "dev", files: [[327, 5], [328, 3]], requires: [200, 115, 201], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_embed: 4.5, guidance_scale: 4.5, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: true, sampler: "EulerATrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 1, speed_up_with_guidance_embed: true, steps: 28, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, tea_cache_threshold: 0.3, tea_cache_start: 5, tea_cache_end: -1, tea_cache_max_skip_steps: 3 } } }, { id: "flux_1_schnell", rubric: "official", name: "FLUX.1 [schnell]", family: "flux1", since: "2024-08-02", variant: "turbo", files: [[329, 5], [330, 3]], requires: [200, 115, 201], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_embed: 3.5, guidance_scale: 4.5, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "EulerATrailing", seed_mode: 2, separate_clip_l: false, separate_open_clip_g: false, sharpness: 0, shift: 1, speed_up_with_guidance_embed: true, steps: 4, strength: 1, tea_cache: false, t5_text_encoder: true, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024 } } }, { id: "auraflow_v0.2", rubric: "official", name: "AuraFlow v0.2", family: "auraflow", since: "2024-07-29", files: [[331, 5], [332, 3]], requires: [333, 246], modes: ["text2image"] }, { id: "kwai-kolors-inpainting-1.0", rubric: "community", name: "Kwai Kolors Inpainting 1.0", family: "sdxl_base_v0.9", since: "2024-07-26", modifier: "inpainting", files: [[334, 11], [335, 5]], requires: [336, 246], modes: ["inpaint-model"] }, { id: "auraflow_v0.1", rubric: "official", name: "AuraFlow v0.1", family: "auraflow", since: "2024-07-20", files: [[337, 5], [338, 3]], requires: [333, 246], modes: ["text2image"], deprecated: true }, { id: "kwai-kolors-1.0", rubric: "community", name: "Kwai Kolors 1.0", family: "sdxl_base_v0.9", since: "2024-07-15", files: [[339, 11], [340, 5]], requires: [336, 246], modes: ["text2image"] }, { id: "pixart_sigma_xl_2_512_ms", rubric: "official", name: "PixArt Sigma XL 512", family: "pixart", since: "2024-06-29", files: [[341, 11], [342, 5]], requires: [246, 201], modes: ["text2image"] }, { id: "svd-xt-v1.1", rubric: "community", name: "Stable Video Diffusion I2V XT v1.1", family: "svd_i2v", since: "2024-06-29", files: [[343, 11], [344, 5]], requires: [345], modes: ["image2video"] }, { id: "svd-v1.0", rubric: "community", name: "Stable Video Diffusion I2V v1.0", family: "svd_i2v", since: "2024-06-29", files: [[346, 11], [347, 5]], requires: [345], modes: ["image2video"] }, { id: "pixart_sigma_xl_2_1024_ms", rubric: "official", name: "PixArt Sigma XL 1K", family: "pixart", since: "2024-06-27", files: [[348, 11], [349, 5]], requires: [246, 201], modes: ["text2image"] }, { id: "stable-cascade", rubric: "community", name: "Stable Cascade (W\xFCrstchen v3.0)", family: "wurstchen_v3.0_stage_c", since: "2024-06-21", files: [[350, 11], [351, 11], [352, 5], [353, 5]], requires: [316, 354, 350, 352], modes: ["text2image"] }, { id: "sd3-medium", rubric: "community", name: "SD3 Medium", family: "sd3", since: "2024-06-21", files: [[355, 11], [356, 5]], requires: [200, 316, 317, 201], modes: ["text2image"] }, { id: "sdxl-turbo", rubric: "community", name: "SDXL Turbo", family: "sdxl_base_v0.9", since: "2024-06-21", variant: "turbo", files: [[357, 11], [358, 5]], requires: [200, 316, 246], modes: ["text2image"] }, { id: "colorfulxl-v6.0", rubric: "community", name: "ColorfulXL v6.0", family: "sdxl_base_v0.9", since: "2024-06-21", files: [[359, 11], [360, 5]], requires: [361, 362, 246], modes: ["text2image"] }, { id: "proteus-v0.3", rubric: "community", name: "Proteus v0.3", family: "sdxl_base_v0.9", since: "2024-06-21", files: [[363, 11], [364, 5]], requires: [365, 366, 246], modes: ["text2image"] }, { id: "icatcher-realistic", rubric: "community", name: "iCatcher Realistic", family: "sdxl_base_v0.9", since: "2024-06-17", files: [[367, 11], [368, 5]], requires: [369, 370, 246], modes: ["text2image"] }, { id: "icatcher-cartoon", rubric: "community", name: "iCatcher Cartoon", family: "sdxl_base_v0.9", since: "2024-06-17", files: [[371, 11], [372, 5]], requires: [373, 374, 246], modes: ["text2image"] }, { id: "realvisxl-v4.0", rubric: "community", name: "RealVisXL v4.0", family: "sdxl_base_v0.9", since: "2024-06-14", files: [[375, 11], [376, 5]], requires: [377, 378, 246], modes: ["text2image"] }, { id: "pixelwave-v10", rubric: "community", name: "PixelWave 10", family: "sdxl_base_v0.9", since: "2024-06-02", files: [[379, 11], [380, 5]], requires: [381, 382, 246], modes: ["text2image"] }, { id: "juggernaut-xl-v9", rubric: "community", name: "Juggernaut XL v9", family: "sdxl_base_v0.9", since: "2024-04-20", files: [[383, 11], [384, 5]], requires: [385, 386, 246], modes: ["text2image"] }, { id: "pixelwave-v9", rubric: "community", name: "PixelWave v9", family: "sdxl_base_v0.9", since: "2024-04-20", files: [[387, 11], [388, 5]], requires: [389, 390, 246], modes: ["text2image"] }, { id: "juggernaut-xl-x", rubric: "community", name: "Juggernaut XL X", family: "sdxl_base_v0.9", since: "2024-04-20", files: [[391, 11], [392, 5]], requires: [393, 394, 246], modes: ["text2image"] }, { id: "animatelcm-svd-xt-v1.1", rubric: "community", name: "AnimateLCM SVD XT v1.1", family: "svd_i2v", since: "2024-04-01", files: [[395, 11], [396, 5]], requires: [345, 397], modes: ["image2video"] }, { id: "dreamshaper-xl-v2.1-turbo", rubric: "community", name: "DreamShaper XL v2.1 Turbo", family: "sdxl_base_v0.9", since: "2024-03-31", variant: "turbo", files: [[398, 11], [399, 5]], requires: [400, 401, 246], modes: ["text2image"] }, { id: "juggernaut-xl-v9-lightning", rubric: "community", name: "Juggernaut XL v9 Lightning", family: "sdxl_base_v0.9", since: "2024-03-31", variant: "turbo", files: [[402, 11], [403, 5]], requires: [404, 405, 246], modes: ["text2image"] }, { id: "rev-animated-v1.22", rubric: "community", name: "Rev Animated v1.22", family: "v1", since: "2024-03-31", files: [[406, 11], [407, 5]], requires: [408], modes: ["text2image"] }, { id: "realistic-vision-v5.1", rubric: "community", name: "Realistic Vision v5.1", family: "v1", since: "2024-03-30", files: [[409, 11], [410, 5]], requires: [411], modes: ["text2image"] }, { id: "dreamshaper-v8", rubric: "community", name: "DreamShaper v8", family: "v1", since: "2024-03-30", files: [[412, 11], [413, 5]], requires: [414], modes: ["text2image"] }, { id: "counterfeit-v3.0", rubric: "community", name: "Counterfeit v3.0", family: "v1", since: "2024-03-30", files: [[415, 11], [416, 5]], requires: [417], modes: ["text2image"] }, { id: "majicmix-realistic-v7", rubric: "community", name: "MajicMIX Realistic v7", family: "v1", since: "2024-03-30", files: [[418, 11], [419, 5]], requires: [420], modes: ["text2image"] }, { id: "animagine-xl", rubric: "community", name: "Animagine XL v3.1", family: "sdxl_base_v0.9", since: "2024-03-29", files: [[421, 11], [422, 5]], requires: [423, 424, 246], modes: ["text2image"] }, { id: "juggernaut-reborn", rubric: "community", name: "Juggernaut Reborn", family: "v1", since: "2024-03-29", files: [[425, 11], [426, 5]], requires: [427], modes: ["text2image"] }, { id: "playground-v2", rubric: "community", name: "Playground v2", family: "sdxl_base_v0.9", since: "2024-03-28", files: [[428, 11], [429, 5]], requires: [200, 316, 246], modes: ["text2image"] }, { id: "playground-v2.5", rubric: "community", name: "Playground v2.5", family: "sdxl_base_v0.9", since: "2024-03-26", files: [[430, 11], [431, 5]], requires: [200, 316, 246], modes: ["text2image"] }, { id: "ssd-1b", rubric: "community", name: "SSD 1B (Segmind SDXL)", family: "ssd_1b", since: "2024-03-26", files: [[432, 11], [433, 5]], requires: [200, 316, 246], modes: ["text2image"] }, { id: "disney-pixar-cartoon-type-b", rubric: "community", name: "Disney Pixar Cartoon Type B (8-bit)", family: "v1", since: "2024-03-26", files: [[434, 5]], requires: [435], modes: ["text2image"] }, { id: "waifu-diffusion-v1.3", rubric: "community", name: "Anime (Waifu Diffusion v1.3)", family: "v1", since: "2024-03-26", files: [[436, 11]], modes: ["text2image"] }, { id: "multi-style-nitro-diffusion-v1", rubric: "community", name: "Multi-Style (Nitro Diffusion v1)", family: "v1", since: "2024-03-26", files: [[437, 11]], requires: [438], modes: ["text2image"] }, { id: "cyberpunk-anime", rubric: "community", name: "Cyberpunk Anime", family: "v1", since: "2024-03-26", files: [[439, 11]], requires: [440], modes: ["text2image"] }, { id: "redshift-v1", rubric: "community", name: "3D Model (Redshift v1)", family: "v1", since: "2024-03-26", files: [[441, 11]], requires: [442], modes: ["text2image"] }, { id: "readshift-768", rubric: "community", name: "3D Model 768 (Redshift 768)", family: "v2", since: "2024-03-26", files: [[443, 11]], requires: [444], modes: ["text2image"] }, { id: "dungeons-and-diffusion-30000", rubric: "community", name: "Dungeons and Diffusion (30000)", family: "v1", since: "2024-03-26", files: [[445, 11]], requires: [446], modes: ["text2image"] }, { id: "tron-legacy", rubric: "community", name: "Tron Legacy", family: "v1", since: "2024-03-26", files: [[447, 11]], requires: [448], modes: ["text2image"] }, { id: "openjourney", rubric: "community", name: "Openjourney", family: "v1", since: "2024-03-26", files: [[449, 11]], requires: [450], modes: ["text2image"] }, { id: "anything-v3", rubric: "community", name: "Anime (Anything v3)", family: "v1", since: "2024-03-26", files: [[451, 11]], requires: [452, 453], modes: ["text2image"] }, { id: "classic-animation-v1", rubric: "community", name: "Classic Animation (v1)", family: "v1", since: "2024-03-26", files: [[454, 11]], requires: [455], modes: ["text2image"] }, { id: "modern-disney-v1", rubric: "community", name: "Modern Disney (v1)", family: "v1", since: "2024-03-26", files: [[456, 11]], requires: [457], modes: ["text2image"] }, { id: "arcane-v3", rubric: "community", name: "Arcane (v3)", family: "v1", since: "2024-03-26", files: [[458, 11]], requires: [459], modes: ["text2image"] }, { id: "hassanblend-v1.5.1.2", rubric: "community", name: "Hassanblend (v1.5.1.2)", family: "v1", since: "2024-03-26", files: [[460, 11]], requires: [461], modes: ["text2image"] }, { id: "van-gogh-style-lvngvncnt-v2", rubric: "community", name: "Van Gogh Style (Lvngvncnt v2)", family: "v1", since: "2024-03-26", files: [[462, 11]], requires: [463], modes: ["text2image"] }, { id: "spider-verse-v1", rubric: "community", name: "Spider-Verse (v1)", family: "v1", since: "2024-03-26", files: [[464, 11]], requires: [465], modes: ["text2image"] }, { id: "elden-ring-v3", rubric: "community", name: "Elden Ring (v3)", family: "v1", since: "2024-03-26", files: [[466, 11]], requires: [467], modes: ["text2image"] }, { id: "paper-cut-v1", rubric: "community", name: "Paper Cut (v1)", family: "v1", since: "2024-03-26", files: [[468, 11]], requires: [469], modes: ["text2image"] }, { id: "voxelart-v1", rubric: "community", name: "VoxelArt (v1)", family: "v1", since: "2024-03-26", files: [[470, 11]], requires: [471], modes: ["text2image"] }, { id: "balloon-art-v1", rubric: "community", name: "Balloon Art (v1)", family: "v1", since: "2024-03-26", files: [[472, 11]], requires: [473], modes: ["text2image"] }, { id: "f222", rubric: "community", name: "F222", family: "v1", since: "2024-03-26", files: [[474, 11]], modes: ["text2image"] }, { id: "super-mario-nation-v2", rubric: "community", name: "Super Mario Nation (v2)", family: "v1", since: "2024-03-26", files: [[475, 11]], requires: [476], modes: ["text2image"] }, { id: "inkpunk-v2", rubric: "community", name: "Inkpunk (v2)", family: "v1", since: "2024-03-26", files: [[477, 11]], requires: [478], modes: ["text2image"] }, { id: "samdoesart-v3", rubric: "community", name: "SamDoesArt (v3)", family: "v1", since: "2024-03-26", files: [[479, 11]], requires: [480], modes: ["text2image"] }, { id: "ghibli-v1", rubric: "community", name: "Ghibli (v1)", family: "v1", since: "2024-03-26", files: [[481, 11]], requires: [482], modes: ["text2image"] }, { id: "analog-v1", rubric: "community", name: "Analog (v1)", family: "v1", since: "2024-03-26", files: [[483, 11]], requires: [484], modes: ["text2image"] }, { id: "dnd-classes-and-species", rubric: "community", name: "DnD Classes and Species", family: "v1", since: "2024-03-26", files: [[485, 11]], requires: [486], modes: ["text2image"] }, { id: "aloeveras-simpmaker-3k1", rubric: "community", name: "AloeVera's SimpMaker 3K1", family: "v1", since: "2024-03-26", files: [[487, 11]], modes: ["text2image"] }, { id: "ha-3dkx-1.1", rubric: "community", name: "H&A's 3DKX 1.1", family: "v1", since: "2024-03-26", files: [[488, 11]], requires: [489], modes: ["text2image"] }, { id: "seek.art-mega-v1", rubric: "community", name: "seek.art MEGA (v1)", family: "v1", since: "2024-03-26", files: [[490, 11]], requires: [491], modes: ["text2image"] }, { id: "deliberate-v2.0", rubric: "community", name: "Deliberate v2.0 (8-bit)", family: "v1", since: "2024-03-26", files: [[492, 5]], requires: [493], modes: ["text2image"] }, { id: "sd_xl_base_1.0", rubric: "official", name: "SDXL Base (v1.0)", family: "sdxl_base_v0.9", since: "2024-03-24", variant: "base", files: [[494, 11]], requires: [200, 316, 246], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 2, controls: [], guidance_scale: 5, height: 1024, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "DPMPP2MAYS", seed_mode: 2, sharpness: 0, shift: 1, steps: 16, strength: 1, tea_cache: false, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 1024, aesthetic_score: 6, target_image_width: 1024, crop_left: 0, crop_top: 0, negative_original_image_height: 512, target_image_height: 1024, original_image_height: 1024, negative_aesthetic_score: 2.5, original_image_width: 1024, zero_negative_prompt: true, negative_original_image_width: 512 } } }, { id: "sd_xl_base_1.0_q6p", rubric: "official", name: "SDXL Base v1.0 (8-bit)", family: "sdxl_base_v0.9", since: "2024-03-24", variant: "base", files: [[495, 5]], requires: [200, 316, 246], modes: ["text2image"] }, { id: "sd_xl_refiner_1.0", rubric: "official", name: "SDXL Refiner (v1.0)", family: "sdxl_refiner_v0.9", since: "2024-03-24", files: [[496, 11]], requires: [200, 316, 246], modes: ["text2image"] }, { id: "sd_xl_refiner_1.0_q6p", rubric: "official", name: "SDXL Refiner v1.0 (8-bit)", family: "sdxl_refiner_v0.9", since: "2024-03-24", files: [[497, 5]], requires: [200, 316, 246], modes: ["text2image"] }, { id: "sd_xl_base_0.9", rubric: "official", name: "SDXL Base (v0.9)", family: "sdxl_base_v0.9", since: "2024-03-24", variant: "base", files: [[498, 11]], requires: [200, 316, 499], modes: ["text2image"], deprecated: true }, { id: "sd_xl_refiner_0.9", rubric: "official", name: "SDXL Refiner (v0.9)", family: "sdxl_refiner_v0.9", since: "2024-03-24", files: [[500, 11]], requires: [200, 316, 499], modes: ["text2image"], deprecated: true }, { id: "fooocus_inpaint_sd_xl_v2.6", rubric: "official", name: "Fooocus Inpaint SDXL v2.6", family: "sdxl_base_v0.9", since: "2024-03-24", modifier: "inpainting", files: [[501, 11]], requires: [200, 316, 246], modes: ["inpaint-model"] }, { id: "fooocus_inpaint_sd_xl_v2.6_q6p", rubric: "official", name: "Fooocus Inpaint SDXL v2.6 (8-bit)", family: "sdxl_base_v0.9", since: "2024-03-24", modifier: "inpainting", files: [[502, 5]], requires: [200, 316, 246], modes: ["inpaint-model"] }, { id: "sd_v1.4", rubric: "official", name: "Stable Diffusion v1.4", family: "v1", since: "2024-03-24", files: [[503, 11]], modes: ["text2image"], deprecated: true }, { id: "sd_v1.5", rubric: "official", name: "Stable Diffusion v1.5", family: "v1", since: "2024-03-24", files: [[504, 11]], modes: ["text2image"], recommended: { source: "config", params: { batch_count: 1, batch_size: 1, clip_skip: 1, controls: [], guidance_scale: 5, height: 512, hires_fix: false, loras: [], mask_blur: 2.5, mask_blur_outset: 0, resolution_dependent_shift: false, sampler: "DPMPP2MAYS", seed_mode: 2, sharpness: 0, shift: 1, steps: 16, strength: 1, tea_cache: false, tiled_decoding: false, tiled_diffusion: false, upscaler_scale_factor: 0, width: 512 } } }, { id: "sd_v1.5_inpainting", rubric: "official", name: "Stable Diffusion v1.5 Inpainting", family: "v1", since: "2024-03-24", modifier: "inpainting", files: [[505, 11]], modes: ["inpaint-model"] }, { id: "sd_v2.0", rubric: "official", name: "Stable Diffusion v2.0", family: "v2", since: "2024-03-24", files: [[506, 11]], requires: [507], modes: ["text2image"], deprecated: true }, { id: "sd_v2.0_768_v", rubric: "official", name: "Stable Diffusion v2.0 768-v", family: "v2", since: "2024-03-24", files: [[508, 11]], requires: [507], modes: ["text2image"], deprecated: true }, { id: "sd_v2.0_inpainting", rubric: "official", name: "Stable Diffusion v2.0 Inpainting", family: "v2", since: "2024-03-24", modifier: "inpainting", files: [[509, 11]], requires: [507], modes: ["inpaint-model"] }, { id: "sd_v2.0_depth", rubric: "official", name: "Stable Diffusion v2.0 Depth", family: "v2", since: "2024-03-24", modifier: "depth", files: [[510, 11]], requires: [507], modes: ["control-model"] }, { id: "sd_v2.1", rubric: "official", name: "Stable Diffusion v2.1", family: "v2", since: "2024-03-24", files: [[511, 11]], requires: [507], modes: ["text2image"] }, { id: "sd_v2.1_768_v", rubric: "official", name: "Stable Diffusion v2.1 768-v", family: "v2", since: "2024-03-24", files: [[512, 11]], requires: [507], modes: ["text2image"] }, { id: "kandinsky", rubric: "official", name: "Kandinsky v2.1", family: "kandinsky2.1", since: "2024-03-24", files: [[513, 11]], requires: [200, 514, 515], modes: ["text2image"], deprecated: true }, { id: "svd_i2v_xt_1.0", rubric: "official", name: "Stable Video Diffusion I2V XT v1.0", family: "svd_i2v", since: "2024-03-24", files: [[516, 11]], requires: [345], modes: ["image2video"], deprecated: true }, { id: "svd_i2v_xt_1.0_q6p", rubric: "official", name: "Stable Video Diffusion I2V XT 1.0 (8-bit)", family: "svd_i2v", since: "2024-03-24", files: [[517, 5]], requires: [345], modes: ["image2video"], deprecated: true }, { id: "minisd_v1.4", rubric: "official", name: "MiniSD v1.4", family: "v1", since: "2024-03-24", files: [[518, 11]], modes: ["text2image"], deprecated: true }, { id: "instruct_pix2pix_22000", rubric: "official", name: "Instruct Pix2Pix", family: "v1", since: "2024-03-24", modifier: "editing", files: [[519, 11]], modes: ["edit"], modesUncertain: true, deprecated: true }, { id: "2DN", rubric: "uncurated", name: "2DN", family: "sdxl_base_v0.9", files: [[520, 11]], requires: [521, 522, 246], modes: ["text2image"] }, { id: "8Steps_Creart_Hyper_Flux_creart_Ultimate", rubric: "uncurated", name: "8Steps_Creart_Hyper_Flux_creart_Ultimate", family: "flux1", files: [[523, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "8Steps_Creart_Hyper_Flux_v24Hyper_Dev_Fp8Unet", rubric: "uncurated", name: "8Steps_Creart_Hyper_Flux_v24Hyper_Dev_Fp8Unet", family: "flux1", variant: "dev", files: [[524, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "8Steps_Creart_Hyper_Flux_v26Hyper_Dev_Fp8Unet", rubric: "uncurated", name: "8Steps_Creart_Hyper_Flux_v26Hyper_Dev_Fp8Unet", family: "flux1", variant: "dev", files: [[525, 11], [526, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "8Steps_Creart_Hyper_Flux_v30Hyper_Dev_Fp8Unet", rubric: "uncurated", name: "8Steps_Creart_Hyper_Flux_v30Hyper_Dev_Fp8Unet", family: "flux1", variant: "dev", files: [[527, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "8Steps_Creart_Hyper_Flux_v40Hyper_Dev_Fp8Unet", rubric: "uncurated", name: "8Steps_Creart_Hyper_Flux_v40Hyper_Dev_Fp8Unet", family: "flux1", variant: "dev", files: [[528, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Acorn_Is_Spinning_FLUX_ais_Flux_De_Distilled", rubric: "uncurated", name: "Acorn_Is_Spinning_FLUX_ais_Flux_De_Distilled", family: "flux1", variant: "turbo", files: [[529, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Acorn_Is_Spinning_FLUX_ais_Flux_V15", rubric: "uncurated", name: "Acorn_Is_Spinning_FLUX_ais_Flux_V15", family: "flux1", files: [[530, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Acorn_Is_Spinning_FLUX_aisf_De_Distilled_V15", rubric: "uncurated", name: "Acorn_Is_Spinning_FLUX_aisf_De_Distilled_V15", family: "flux1", variant: "turbo", files: [[531, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Acorn_Is_Spinning_FLUX_aisf_Hyper8Step_V15", rubric: "uncurated", name: "Acorn_Is_Spinning_FLUX_aisf_Hyper8Step_V15", family: "flux1", files: [[532, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Acorn_Is_Spinning_FLUX_aisf_V169", rubric: "uncurated", name: "Acorn_Is_Spinning_FLUX_aisf_V169", family: "flux1", files: [[533, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Acorn_Is_Spinning_FLUX_aisf11H8stp_Chinfx", rubric: "uncurated", name: "Acorn_Is_Spinning_FLUX_aisf11H8stp_Chinfx", family: "flux1", files: [[534, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Agflux_Fill_NSFWFp8", rubric: "uncurated", name: "Agflux_Fill_NSFWFp8_agflux_Fill_NSFWV17Fp8", family: "flux1", modifier: "inpainting", files: [[535, 5]], requires: [200, 115, 201], modes: ["inpaint-model"] }, { id: "Agflux_Schnell_V10Fp8", rubric: "uncurated", name: "Agflux_Schnell_V10Fp8", family: "flux1", variant: "turbo", files: [[536, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Agflux_V10Fp8", rubric: "uncurated", name: "Agflux_V10Fp8", family: "flux1", files: [[537, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Agflux_V21Fp8", rubric: "uncurated", name: "Agflux_V21Fp8", family: "flux1", files: [[538, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Agflux_V3Fp8", rubric: "uncurated", name: "Agflux_V3Fp8", family: "flux1", files: [[539, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "AGGAs-Utopia-_illustrious-SDXL", rubric: "uncurated", name: "AGGAs-Utopia-_illustrious-SDXL", family: "sdxl_base_v0.9", files: [[540, 11]], requires: [541, 542, 246], modes: ["text2image"] }, { id: "Amanatsu-Illustrious", rubric: "uncurated", name: "Amanatsu-Illustrious", family: "sdxl_base_v0.9", files: [[543, 11]], requires: [544, 545, 246], modes: ["text2image"] }, { id: "Anillustrious", rubric: "uncurated", name: "Anillustrious", family: "sdxl_base_v0.9", files: [[546, 11]], requires: [547, 548, 246], modes: ["text2image"] }, { id: "Animij", rubric: "uncurated", name: "Animij", family: "sdxl_base_v0.9", files: [[549, 11]], requires: [550, 551, 246], modes: ["text2image"] }, { id: "anisora-v2-i2v-wan-2.1-14b", rubric: "uncurated", name: "AniSora v2 I2V Wan 2.1 14B", family: "wan_v2.1_14b", modifier: "inpainting", files: [[552, 5], [553, 4]], requires: [181, 175, 176], modes: ["image2video"] }, { id: "anisora-v3.1-i2v-wan-2.1-14b", rubric: "uncurated", name: "AniSora v3.1 I2V Wan 2.1 14B", family: "wan_v2.1_14b", modifier: "inpainting", files: [[554, 5], [555, 4]], requires: [181, 175, 176], modes: ["image2video"] }, { id: "Artofura-Furry-mix", rubric: "uncurated", name: "Artofura-Furry-mix", family: "sdxl_base_v0.9", files: [[556, 11]], requires: [557, 558, 246], modes: ["text2image"] }, { id: "Artsy_Dream_v1FP16", rubric: "uncurated", name: "Artsy_Dream_v1FP16", family: "flux1", files: [[559, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v1FP8", rubric: "uncurated", name: "Artsy_Dream_v1FP8", family: "flux1", files: [[560, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v2FP16", rubric: "uncurated", name: "Artsy_Dream_v2FP16", family: "flux1", files: [[561, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v2FP8", rubric: "uncurated", name: "Artsy_Dream_v2FP8", family: "flux1", files: [[562, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v3FP16", rubric: "uncurated", name: "Artsy_Dream_v3FP16", family: "flux1", files: [[563, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v3FP8", rubric: "uncurated", name: "Artsy_Dream_v3FP8", family: "flux1", files: [[564, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v4FP16", rubric: "uncurated", name: "Artsy_Dream_v4FP16", family: "flux1", files: [[565, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v4FP8", rubric: "uncurated", name: "Artsy_Dream_v4FP8", family: "flux1", files: [[566, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v5FP16", rubric: "uncurated", name: "Artsy_Dream_v5FP16", family: "flux1", files: [[567, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v5FP8", rubric: "uncurated", name: "Artsy_Dream_v5FP8", family: "flux1", files: [[568, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v6FP16", rubric: "uncurated", name: "Artsy_Dream_v6FP16", family: "flux1", files: [[569, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Dream_v6FP8", rubric: "uncurated", name: "Artsy_Dream_v6FP8", family: "flux1", files: [[570, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Vibe_v1FP16", rubric: "uncurated", name: "Artsy_Vibe_v1FP16", family: "flux1", files: [[571, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Vibe_v1FP8", rubric: "uncurated", name: "Artsy_Vibe_v1FP8", family: "flux1", files: [[572, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Vibe_v2FP16", rubric: "uncurated", name: "Artsy_Vibe_v2FP16", family: "flux1", files: [[573, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Artsy_Vibe_v2FP8", rubric: "uncurated", name: "Artsy_Vibe_v2FP8", family: "flux1", files: [[574, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Asian-Realism-By-Stable-Yogi-PONY", rubric: "uncurated", name: "Asian-Realism-By-Stable-Yogi-PONY", family: "sdxl_base_v0.9", files: [[575, 11]], requires: [576, 577, 246], modes: ["text2image"] }, { id: "Atomix_FLUXUnet_v10", rubric: "uncurated", name: "Atomix_FLUXUnet_v10", family: "flux1", files: [[578, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Aungir_Aungir_T6A4_1405004", rubric: "uncurated", name: "Aungir_Aungir_T6A4_1405004", family: "sdxl_base_v0.9", files: [[579, 11]], requires: [580, 581, 246], modes: ["text2image"] }, { id: "Aungir_Aungir_T6AO4.5_1723632", rubric: "uncurated", name: "Aungir_Aungir_T6AO4.5_1723632", family: "sdxl_base_v0.9", files: [[582, 11]], requires: [583, 584, 246], modes: ["text2image"] }, { id: "Big-Love", rubric: "uncurated", name: "Big-Love", family: "sdxl_base_v0.9", files: [[585, 11]], requires: [586, 587, 246], modes: ["text2image"] }, { id: "Bismuth-Illustrious-Mix", rubric: "uncurated", name: "Bismuth-Illustrious-Mix", family: "sdxl_base_v0.9", files: [[588, 11]], requires: [589, 590, 246], modes: ["text2image"] }, { id: "BlenderMix", rubric: "uncurated", name: "BlenderMix", family: "sdxl_base_v0.9", files: [[591, 11]], requires: [592, 593, 246], modes: ["text2image"] }, { id: "Blue_Pencil_Flux1_v010", rubric: "uncurated", name: "Blue_Pencil_Flux1_v010", family: "flux1", files: [[594, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Blue_Pencil_Flux1_v021", rubric: "uncurated", name: "Blue_Pencil_Flux1_v021", family: "flux1", files: [[595, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "boleromixillustrious", rubric: "uncurated", name: "boleromixillustrious", family: "sdxl_base_v0.9", files: [[596, 11]], requires: [597, 598, 246], modes: ["text2image"] }, { id: "C4pacitor_a_V2Alpha", rubric: "uncurated", name: "C4pacitor_a_V2Alpha", family: "flux1", files: [[599, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "C4pacitor_a_V2Beta", rubric: "uncurated", name: "C4pacitor_a_V2Beta", family: "flux1", files: [[600, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "C4pacitor_d_V1", rubric: "uncurated", name: "C4pacitor_d_V1", family: "flux1", files: [[601, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "C4pacitor_d_V11", rubric: "uncurated", name: "C4pacitor_d_V11", family: "flux1", files: [[602, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "C4pacitor_d_V2", rubric: "uncurated", name: "C4pacitor_d_V2", family: "flux1", files: [[603, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "C4pacitor_d_V3Alpha", rubric: "uncurated", name: "C4pacitor_d_V3Alpha", family: "flux1", files: [[604, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "C4pacitor_s_V11", rubric: "uncurated", name: "C4pacitor_s_V11", family: "flux1", files: [[605, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "C4pacitor_s_V2Alpha", rubric: "uncurated", name: "C4pacitor_s_V2Alpha", family: "flux1", files: [[606, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Candied-Anime-IllustriousXL", rubric: "uncurated", name: "Candied-Anime-IllustriousXL", family: "sdxl_base_v0.9", files: [[607, 11]], requires: [608, 609, 246], modes: ["text2image"] }, { id: "Centerfold_Flux_v35FP8E54Steps", rubric: "uncurated", name: "Centerfold_Flux_v35FP8E54Steps", family: "flux1", files: [[610, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Centerfold_Flux_v40Fp8E5m2", rubric: "uncurated", name: "Centerfold_Flux_v40Fp8E5m2", family: "flux1", files: [[611, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-1-hd-annealed", rubric: "uncurated", name: "Chroma1 HD Annealed", family: "flux1", files: [[612, 5], [613, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v38-detail-calibrated", rubric: "uncurated", name: "Chroma v38 Detail Calibrated", family: "flux1", files: [[614, 5], [615, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v39-detail-calibrated", rubric: "uncurated", name: "Chroma v39 Detail Calibrated", family: "flux1", files: [[616, 5], [617, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v40-detail-calibrated", rubric: "uncurated", name: "Chroma v40 Detail Calibrated", family: "flux1", files: [[618, 5], [619, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v41-detail-calibrated", rubric: "uncurated", name: "Chroma v41 Detail Calibrated", family: "flux1", files: [[620, 5], [621, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v42-detail-calibrated", rubric: "uncurated", name: "Chroma v42 Detail Calibrated", family: "flux1", files: [[622, 5], [623, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v43-detail-calibrated", rubric: "uncurated", name: "Chroma v43 Detail Calibrated", family: "flux1", files: [[624, 5], [625, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v44-detail-calibrated", rubric: "uncurated", name: "Chroma v44 Detail Calibrated", family: "flux1", files: [[626, 5], [627, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v45-detail-calibrated", rubric: "uncurated", name: "Chroma v45 Detail Calibrated", family: "flux1", files: [[628, 5], [629, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "chroma-v46-detail-calibrated", rubric: "uncurated", name: "Chroma v46 Detail Calibrated", family: "flux1", files: [[630, 5], [631, 3]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "CircusMix", rubric: "uncurated", name: "CircusMix", family: "sdxl_base_v0.9", files: [[632, 11]], requires: [633, 634, 246], modes: ["text2image"] }, { id: "Colorfulasiangirl_Flux_beta", rubric: "uncurated", name: "Colorfulasiangirl_Flux_beta", family: "flux1", files: [[635, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_21De_Distilled_AIOExp", rubric: "uncurated", name: "Colossus_Project_Flux_21De_Distilled_AIOExp", family: "flux1", variant: "turbo", files: [[636, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v10AIOFP8", rubric: "uncurated", name: "Colossus_Project_Flux_v10AIOFP8", family: "flux1", files: [[637, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v10All_In_One_Fp8", rubric: "uncurated", name: "Colossus_Project_Flux_v10All_In_One_Fp8", family: "flux1", files: [[638, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v10b_FP8AIOBOBFP8", rubric: "uncurated", name: "Colossus_Project_Flux_v10b_FP8AIOBOBFP8", family: "flux1", files: [[639, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v10Behemoth_AIOFP16", rubric: "uncurated", name: "Colossus_Project_Flux_v10Behemoth_AIOFP16", family: "flux1", files: [[640, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v10FP16UNETONLY", rubric: "uncurated", name: "Colossus_Project_Flux_v10FP16UNETONLY", family: "flux1", files: [[641, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v10UNETOnly_FP16", rubric: "uncurated", name: "Colossus_Project_Flux_v10UNETOnly_FP16", family: "flux1", files: [[642, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v10UNETOnly_FP8", rubric: "uncurated", name: "Colossus_Project_Flux_v10UNETOnly_FP8", family: "flux1", files: [[643, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v20All_In_One_Exp", rubric: "uncurated", name: "Colossus_Project_Flux_v20All_In_One_Exp", family: "flux1", files: [[644, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v42AIO", rubric: "uncurated", name: "Colossus_Project_Flux_v42AIO", family: "flux1", files: [[645, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v44AIO", rubric: "uncurated", name: "Colossus_Project_Flux_v44AIO", family: "flux1", files: [[646, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v50AIO", rubric: "uncurated", name: "Colossus_Project_Flux_v50AIO", family: "flux1", files: [[647, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v50AIOBehemoth", rubric: "uncurated", name: "Colossus_Project_Flux_v50AIOBehemoth", family: "flux1", files: [[648, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v50FP8UNET", rubric: "uncurated", name: "Colossus_Project_Flux_v50FP8UNET", family: "flux1", files: [[649, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Colossus_Project_Flux_v90AIO", rubric: "uncurated", name: "Colossus_Project_Flux_v90AIO", family: "flux1", files: [[650, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_fluxreal_Fast", rubric: "uncurated", name: "Copax_Timeless_fluxreal_Fast", family: "flux1", variant: "turbo", files: [[651, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_stylemix1Flux_Dev_FP16", rubric: "uncurated", name: "Copax_Timeless_stylemix1Flux_Dev_FP16", family: "flux1", variant: "dev", files: [[652, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_stylemix1Fp8", rubric: "uncurated", name: "Copax_Timeless_stylemix1Fp8", family: "flux1", files: [[653, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_stylemix2", rubric: "uncurated", name: "Copax_Timeless_stylemix2", family: "flux1", files: [[654, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_Cartoon", rubric: "uncurated", name: "Copax_Timeless_xplus_Cartoon", family: "flux1", files: [[655, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_MIX1", rubric: "uncurated", name: "Copax_Timeless_xplus_MIX1", family: "flux1", files: [[656, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_MIX1FP8", rubric: "uncurated", name: "Copax_Timeless_xplus_MIX1FP8", family: "flux1", files: [[657, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_MIX2", rubric: "uncurated", name: "Copax_Timeless_xplus_MIX2", family: "flux1", files: [[658, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_MIX3", rubric: "uncurated", name: "Copax_Timeless_xplus_MIX3", family: "flux1", files: [[659, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_MIX3Dark", rubric: "uncurated", name: "Copax_Timeless_xplus_MIX3Dark", family: "flux1", files: [[660, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_MIX4", rubric: "uncurated", name: "Copax_Timeless_xplus_MIX4", family: "flux1", files: [[661, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_Poses", rubric: "uncurated", name: "Copax_Timeless_xplus_Poses", family: "flux1", files: [[662, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus_Unreal_Fast", rubric: "uncurated", name: "Copax_Timeless_xplus_Unreal_Fast", family: "flux1", variant: "turbo", files: [[663, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus1", rubric: "uncurated", name: "Copax_Timeless_xplus1", family: "flux1", files: [[664, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus2", rubric: "uncurated", name: "Copax_Timeless_xplus2", family: "flux1", files: [[665, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax_Timeless_xplus2Base_Train", rubric: "uncurated", name: "Copax_Timeless_xplus2Base_Train", family: "flux1", files: [[666, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Copax-Pony-XL", rubric: "uncurated", name: "Copax-Pony-XL", family: "sdxl_base_v0.9", files: [[667, 11]], requires: [668, 669, 246], modes: ["text2image"] }, { id: "Crow-Pony-qp", rubric: "uncurated", name: "Crow-Pony-qp", family: "sdxl_base_v0.9", files: [[670, 11]], requires: [671, 672, 246], modes: ["text2image"] }, { id: "CyberIllustrious-CyberRealistic", rubric: "uncurated", name: "CyberIllustrious-CyberRealistic", family: "sdxl_base_v0.9", files: [[673, 11]], requires: [674, 675, 246], modes: ["text2image"] }, { id: "CyberRealistic", rubric: "uncurated", name: "CyberRealistic", family: "v1", files: [[676, 11]], requires: [677], modes: ["text2image"] }, { id: "CyberRealistic_Pony_v8_1346181", rubric: "uncurated", name: "CyberRealistic_Pony_v8_1346181", family: "sdxl_base_v0.9", files: [[678, 11]], requires: [679, 680, 246], modes: ["text2image"] }, { id: "CyberRealistic_Pony_v8.5_1478064", rubric: "uncurated", name: "CyberRealistic_Pony_v8.5_1478064", family: "sdxl_base_v0.9", files: [[681, 11]], requires: [682, 683, 246], modes: ["text2image"] }, { id: "CyberRealistic_Pony_v9.0_Alt_1_1691220", rubric: "uncurated", name: "CyberRealistic_Pony_v9.0_Alt_1_1691220", family: "sdxl_base_v0.9", files: [[684, 11]], requires: [685, 686, 246], modes: ["text2image"] }, { id: "cyberrealistic-flux-v2-5", rubric: "uncurated", name: "CyberRealistic Flux v2.5", family: "flux1", files: [[687, 11], [688, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "CyberRealistic-Pony-Catalyst", rubric: "uncurated", name: "CyberRealistic-Pony-Catalyst", family: "sdxl_base_v0.9", files: [[689, 11]], requires: [690, 691, 246], modes: ["text2image"] }, { id: "CyberRealistic-Pony-Semi-Realistic", rubric: "uncurated", name: "CyberRealistic-Pony-Semi-Realistic", family: "sdxl_base_v0.9", files: [[692, 11]], requires: [693, 694, 246], modes: ["text2image"] }, { id: "CyberRealistic-XL", rubric: "uncurated", name: "CyberRealistic-XL", family: "sdxl_base_v0.9", files: [[695, 11]], requires: [696, 697, 246], modes: ["text2image"] }, { id: "Demon_CORESFWNSFW_flux_V13", rubric: "uncurated", name: "Demon_CORESFWNSFW_flux_V13", family: "flux1", files: [[698, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Demon_CORESFWNSFW_v25Helheim_Project_AIO", rubric: "uncurated", name: "Demon_CORESFWNSFW_v25Helheim_Project_AIO", family: "flux1", files: [[699, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "DHXL-v1.0", rubric: "uncurated", name: "DHXL-v1.0", family: "sdxl_base_v0.9", files: [[700, 11]], requires: [701, 702, 246], modes: ["text2image"] }, { id: "Dixar", rubric: "uncurated", name: "Dixar", family: "sdxl_base_v0.9", files: [[703, 11]], requires: [704, 705, 246], modes: ["text2image"] }, { id: "Dreamisoa-remix", rubric: "uncurated", name: "Dreamisoa-remix", family: "sdxl_base_v0.9", files: [[706, 11]], requires: [707, 708, 246], modes: ["text2image"] }, { id: "DucHaiten_Pony_XL_no_score_v5.2_706363", rubric: "uncurated", name: "DucHaiten_Pony_XL_no_score_v5.2_706363", family: "sdxl_base_v0.9", files: [[709, 11]], requires: [710, 711, 246], modes: ["text2image"] }, { id: "DucHaiten_Pony_XL_no_score_v6.0_817261", rubric: "uncurated", name: "DucHaiten_Pony_XL_no_score_v6.0_817261", family: "sdxl_base_v0.9", files: [[712, 11]], requires: [713, 714, 246], modes: ["text2image"] }, { id: "DucHaiten-Cool-Age", rubric: "uncurated", name: "DucHaiten-Cool-Age", family: "sdxl_base_v0.9", files: [[715, 11]], requires: [716, 717, 246], modes: ["text2image"] }, { id: "DucHaiten-NoobAI", rubric: "uncurated", name: "DucHaiten-NoobAI", family: "sdxl_base_v0.9", files: [[718, 11]], requires: [719, 720, 246], modes: ["text2image"] }, { id: "DucHaiten-NoobAI-Cinematic", rubric: "uncurated", name: "DucHaiten-NoobAI-Cinematic", family: "sdxl_base_v0.9", files: [[721, 11]], requires: [722, 723, 246], modes: ["text2image"] }, { id: "DucHaiten-Pony-Real", rubric: "uncurated", name: "DucHaiten-Pony-Real", family: "sdxl_base_v0.9", files: [[724, 11]], requires: [725, 726, 246], modes: ["text2image"] }, { id: "Edge_Of_Reality_32Beyond_Reality", rubric: "uncurated", name: "Edge_Of_Reality_32Beyond_Reality", family: "flux1", files: [[727, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Edge_Of_Reality_v30", rubric: "uncurated", name: "Edge_Of_Reality_v30", family: "flux1", files: [[728, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Editijon-K-POP", rubric: "uncurated", name: "Editijon-K-POP", family: "sdxl_base_v0.9", files: [[729, 11]], requires: [730, 731, 246], modes: ["text2image"] }, { id: "epiCRealism-XL", rubric: "uncurated", name: "epiCRealism-XL", family: "sdxl_base_v0.9", files: [[732, 11]], requires: [733, 734, 246], modes: ["text2image"] }, { id: "Eri-LumenVeil-V1-Illustrious-NAI", rubric: "uncurated", name: "Eri-LumenVeil-V1-Illustrious-NAI", family: "sdxl_base_v0.9", files: [[735, 11]], requires: [736, 737, 246], modes: ["text2image"] }, { id: "Fantasm-Pony-XL", rubric: "uncurated", name: "Fantasm-Pony-XL", family: "sdxl_base_v0.9", files: [[738, 11]], requires: [739, 740, 246], modes: ["text2image"] }, { id: "Fenrisxl_Flux_fenris_Flux_V1FP8", rubric: "uncurated", name: "Fenrisxl_Flux_fenris_Flux_V1FP8", family: "flux1", files: [[741, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Five_Stars_Illustrious_1.0_1398525", rubric: "uncurated", name: "Five_Stars_Illustrious_1.0_1398525", family: "sdxl_base_v0.9", files: [[742, 11]], requires: [743, 744, 246], modes: ["text2image"] }, { id: "Five_Stars_Illustrious_4.0_1657020", rubric: "uncurated", name: "Five_Stars_Illustrious_4.0_1657020", family: "sdxl_base_v0.9", files: [[745, 11]], requires: [746, 747, 246], modes: ["text2image"] }, { id: "Flux_Realistic_flux_Realistic_Samay_V2", rubric: "uncurated", name: "Flux_Realistic_flux_Realistic_Samay_V2", family: "flux1", files: [[748, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Flux1_v10Fp8", rubric: "uncurated", name: "Flux1_v10Fp8", family: "flux1", files: [[749, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Flux1_v10Fp8Schnell", rubric: "uncurated", name: "Flux1_v10Fp8Schnell", family: "flux1", files: [[750, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Flux1_v20Fp8", rubric: "uncurated", name: "Flux1_v20Fp8", family: "flux1", files: [[751, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Flux1_v30Fp8", rubric: "uncurated", name: "Flux1_v30Fp8", family: "flux1", files: [[752, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Flux1_v30PAPFp8", rubric: "uncurated", name: "Flux1_v30PAPFp8", family: "flux1", files: [[753, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Flux1Dev_Asian_v10FP16", rubric: "uncurated", name: "Flux1Dev_Asian_v10FP16", family: "flux1", files: [[754, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Flux1east_Fp8_canny", rubric: "uncurated", name: "Flux1east_Fp8_canny", family: "flux1", modifier: "depth", files: [[755, 5]], requires: [200, 115, 201], modes: ["control-model"] }, { id: "Flux1east_Fp8_depth", rubric: "uncurated", name: "Flux1east_Fp8_depth", family: "flux1", modifier: "depth", files: [[756, 5]], requires: [200, 115, 201], modes: ["control-model"] }, { id: "Flux1east_Fp8_dev", rubric: "uncurated", name: "Flux1east_Fp8_dev", family: "flux1", variant: "dev", files: [[757, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Flux1east_Fp8_fill", rubric: "uncurated", name: "Flux1east_Fp8_fill", family: "flux1", modifier: "inpainting", files: [[758, 5]], requires: [200, 115, 201], modes: ["inpaint-model"] }, { id: "Fluxed_Up_Flux_NSFW_10", rubric: "uncurated", name: "Fluxed_Up_Flux_NSFW_10", family: "flux1", files: [[759, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxed_Up_Flux_NSFW_21", rubric: "uncurated", name: "Fluxed_Up_Flux_NSFW_21", family: "flux1", files: [[760, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxed_Up_Flux_NSFW_22", rubric: "uncurated", name: "Fluxed_Up_Flux_NSFW_22", family: "flux1", files: [[761, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxed_Up_Flux_NSFW_24", rubric: "uncurated", name: "Fluxed_Up_Flux_NSFW_24", family: "flux1", files: [[762, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxed_Up_Flux_NSFW_25", rubric: "uncurated", name: "Fluxed_Up_Flux_NSFW_25", family: "flux1", files: [[763, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxed_Up_Flux_NSFW_40Dev_Fp8", rubric: "uncurated", name: "Fluxed_Up_Flux_NSFW_40Dev_Fp8", family: "flux1", files: [[764, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxed_Up_Flux_NSFW_41", rubric: "uncurated", name: "Fluxed_Up_Flux_NSFW_41", family: "flux1", files: [[765, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxmania_i", rubric: "uncurated", name: "Fluxmania_i", family: "flux1", files: [[766, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxmania_iv", rubric: "uncurated", name: "Fluxmania_iv", family: "flux1", files: [[767, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxmania_legacy", rubric: "uncurated", name: "Fluxmania_legacy", family: "flux1", files: [[768, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Fluxmania_v", rubric: "uncurated", name: "Fluxmania_v", family: "flux1", files: [[769, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "FurryToonMix", rubric: "uncurated", name: "FurryToonMix", family: "sdxl_base_v0.9", files: [[770, 11]], requires: [771, 772, 246], modes: ["text2image"] }, { id: "Genova_APEX_1618Experiment", rubric: "uncurated", name: "Genova_APEX_1618Experiment", family: "flux1", files: [[773, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Genova_APEX_genova_V2", rubric: "uncurated", name: "Genova_APEX_genova_V2", family: "flux1", files: [[774, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Genova_APEX_plus", rubric: "uncurated", name: "Genova_APEX_plus", family: "flux1", files: [[775, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Genova_APEX_real", rubric: "uncurated", name: "Genova_APEX_real", family: "flux1", files: [[776, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Genova_APEX_s", rubric: "uncurated", name: "Genova_APEX_s", family: "flux1", files: [[777, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "getphat-flux-reality-nsfw", rubric: "uncurated", name: "getphat FLUX Reality NSFW v11 Softcore", family: "flux1", files: [[778, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Gonzalomo_XLFlux_Pony_v03Fluxity_Fp8", rubric: "uncurated", name: "Gonzalomo_XLFlux_Pony_v03Fluxity_Fp8", family: "flux1", files: [[779, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Gonzalomo_XLFlux_Pony_v10Fluxity_Fp8", rubric: "uncurated", name: "Gonzalomo_XLFlux_Pony_v10Fluxity_Fp8", family: "flux1", files: [[780, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "HomoSimile-XL-Pony_-Illustrious_-NoobAI", rubric: "uncurated", name: "HomoSimile-XL-Pony_-Illustrious_-NoobAI", family: "sdxl_base_v0.9", files: [[781, 11]], requires: [782, 783, 246], modes: ["text2image"] }, { id: "Hoseki-LustrousMix-IllustriousXL", rubric: "uncurated", name: "Hoseki-LustrousMix-IllustriousXL", family: "sdxl_base_v0.9", files: [[784, 11]], requires: [785, 786, 246], modes: ["text2image"] }, { id: "Hoseki-LustrousMix-Pony-XL", rubric: "uncurated", name: "Hoseki-LustrousMix-Pony-XL", family: "sdxl_base_v0.9", files: [[787, 11]], requires: [788, 789, 246], modes: ["text2image"] }, { id: "Hs-UltraHD-CG", rubric: "uncurated", name: "Hs-UltraHD-CG", family: "sdxl_base_v0.9", files: [[790, 11]], requires: [791, 792, 246], modes: ["text2image"] }, { id: "Hyper_Flux_Dedistilled_hyper16Steps_FP8", rubric: "uncurated", name: "Hyper_Flux_Dedistilled_hyper16Steps_FP8", family: "flux1", files: [[793, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Hyper_Flux_Dedistilled_hyper8Steps_FP8", rubric: "uncurated", name: "Hyper_Flux_Dedistilled_hyper8Steps_FP8", family: "flux1", files: [[794, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "IcedCoffeeIL", rubric: "uncurated", name: "IcedCoffeeIL", family: "sdxl_base_v0.9", files: [[795, 11]], requires: [796, 797, 246], modes: ["text2image"] }, { id: "IffyMix-XL", rubric: "uncurated", name: "IffyMix-XL", family: "sdxl_base_v0.9", files: [[798, 11]], requires: [799, 800, 246], modes: ["text2image"] }, { id: "IllumiYume-XL-Illustrious", rubric: "uncurated", name: "IllumiYume-XL-Illustrious", family: "sdxl_base_v0.9", files: [[801, 11]], requires: [802, 803, 246], modes: ["text2image"] }, { id: "Illustration_Juaner_Ghibli_v10", rubric: "uncurated", name: "Illustration_Juaner_Ghibli_v10", family: "flux1", files: [[804, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Illustration_Juaner_Ghibli_v20", rubric: "uncurated", name: "Illustration_Juaner_Ghibli_v20", family: "flux1", files: [[805, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Illustrij", rubric: "uncurated", name: "Illustrij", family: "sdxl_base_v0.9", files: [[806, 11]], requires: [807, 808, 246], modes: ["text2image"] }, { id: "illustrij-gen-v1", rubric: "uncurated", name: "Illustrij-GENv1", family: "sdxl_base_v0.9", files: [[809, 11], [810, 5]], requires: [811, 812, 246], modes: ["text2image"] }, { id: "Illustrious-Black-Magic-Illustrious-Noob-More", rubric: "uncurated", name: "Illustrious-Black-Magic-Illustrious-Noob-More", family: "sdxl_base_v0.9", files: [[813, 11]], requires: [814, 815, 246], modes: ["text2image"] }, { id: "Illustrious-Gehenna-Illustrious-Checkpoint", rubric: "uncurated", name: "Illustrious-Gehenna-Illustrious-Checkpoint", family: "sdxl_base_v0.9", files: [[816, 11]], requires: [817, 818, 246], modes: ["text2image"] }, { id: "Illustrious-Realism-by-klaabu", rubric: "uncurated", name: "Illustrious-Realism-by-klaabu", family: "sdxl_base_v0.9", files: [[819, 11]], requires: [820, 821, 246], modes: ["text2image"] }, { id: "Illustrious-XL", rubric: "uncurated", name: "Illustrious-XL", family: "sdxl_base_v0.9", files: [[822, 11]], requires: [823, 824, 246], modes: ["text2image"] }, { id: "Illustrious-XL-personal-merge-noob-v-pred0.5-test-merge-updated", rubric: "uncurated", name: "Illustrious-XL-personal-merge-noob-v-pred0.5-test-merge-updated", family: "sdxl_base_v0.9", files: [[825, 11]], requires: [826, 827, 246], modes: ["text2image"] }, { id: "inbetweij-no04", rubric: "uncurated", name: "Inbetweij \u2014 No.04", family: "sdxl_base_v0.9", files: [[828, 11], [829, 5]], requires: [830, 831, 246], modes: ["text2image"] }, { id: "Indigo_Void_Furry_Fused_XL_Furry_NoobAI_NoobAI_v1.7_1569147", rubric: "uncurated", name: "Indigo_Void_Furry_Fused_XL_Furry_NoobAI_NoobAI_v1.7_1569147", family: "sdxl_base_v0.9", files: [[832, 11]], requires: [833, 834, 246], modes: ["text2image"] }, { id: "Indigo_Void_Furry_Fused_XL_Furry_NoobAI_NoobAI_v1.8_1731573", rubric: "uncurated", name: "Indigo_Void_Furry_Fused_XL_Furry_NoobAI_NoobAI_v1.8_1731573", family: "sdxl_base_v0.9", files: [[835, 11]], requires: [836, 837, 246], modes: ["text2image"] }, { id: "Indigo-Furry-Mix-XL", rubric: "uncurated", name: "Indigo-Furry-Mix-XL", family: "sdxl_base_v0.9", files: [[838, 11]], requires: [839, 840, 246], modes: ["text2image"] }, { id: "Indigo-Void-Furry-Vpred-Furry-NoobAI-V-pred", rubric: "uncurated", name: "Indigo-Void-Furry-Vpred-Furry-NoobAI-V-pred", family: "sdxl_base_v0.9", files: [[841, 11]], requires: [842, 843, 246], modes: ["text2image"] }, { id: "Iniverse_Mix_SFWNSFW_f1d_Real_Guofeng_Fp8V20", rubric: "uncurated", name: "Iniverse_Mix_SFWNSFW_f1d_Real_Guofeng_Fp8V20", family: "flux1", files: [[844, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Iniverse_Mix_SFWNSFW_f1d_Realnsfw_Guofeng_V2", rubric: "uncurated", name: "Iniverse_Mix_SFWNSFW_f1d_Realnsfw_Guofeng_V2", family: "flux1", files: [[845, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Iniverse_Mix_SFWNSFW_flux1DNsfw_Fp16V12", rubric: "uncurated", name: "Iniverse_Mix_SFWNSFW_flux1DNsfw_Fp16V12", family: "flux1", files: [[846, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Iniverse_Mix_SFWNSFW_flux1DNsfw_Fp8V10", rubric: "uncurated", name: "Iniverse_Mix_SFWNSFW_flux1DNsfw_Fp8V10", family: "flux1", files: [[847, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ionsyx", rubric: "uncurated", name: "Ionsyx", family: "sdxl_base_v0.9", files: [[848, 11]], requires: [849, 850, 246], modes: ["text2image"] }, { id: "Isenganmix_Flux_v_B", rubric: "uncurated", name: "Isenganmix_Flux_v_B", family: "flux1", files: [[851, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib_Mix_Flux_fp16V1", rubric: "uncurated", name: "Jib_Mix_Flux_fp16V1", family: "flux1", files: [[852, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib_Mix_Flux_fp8V2Electric", rubric: "uncurated", name: "Jib_Mix_Flux_fp8V2Electric", family: "flux1", files: [[853, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib_Mix_Flux_fp8V4Canvas_Galore", rubric: "uncurated", name: "Jib_Mix_Flux_fp8V4Canvas_Galore", family: "flux1", files: [[854, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib_Mix_Flux_v72Pixel_Heaven", rubric: "uncurated", name: "Jib_Mix_Flux_v72Pixel_Heaven", family: "flux1", files: [[855, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib_Mix_Flux_v78Clear_Text_Focus", rubric: "uncurated", name: "Jib_Mix_Flux_v78Clear_Text_Focus", family: "flux1", files: [[856, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib_Mix_Flux_v7Pixel_Heaven_Beta", rubric: "uncurated", name: "Jib_Mix_Flux_v7Pixel_Heaven_Beta", family: "flux1", files: [[857, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib_Mix_Flux_v85Consisteight", rubric: "uncurated", name: "Jib_Mix_Flux_v85Consisteight", family: "flux1", files: [[858, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib_Mix_Flux_v8Accentueight_Now", rubric: "uncurated", name: "Jib_Mix_Flux_v8Accentueight_Now", family: "flux1", files: [[859, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Jib-Mix-Pony-Realistic", rubric: "uncurated", name: "Jib-Mix-Pony-Realistic", family: "sdxl_base_v0.9", files: [[860, 11]], requires: [861, 862, 246], modes: ["text2image"] }, { id: "Jib-Mix-Realistic-XL", rubric: "uncurated", name: "Jib-Mix-Realistic-XL", family: "sdxl_base_v0.9", files: [[863, 11]], requires: [864, 865, 246], modes: ["text2image"] }, { id: "JujuMix", rubric: "uncurated", name: "JujuMix", family: "sdxl_base_v0.9", files: [[866, 11]], requires: [867, 868, 246], modes: ["text2image"] }, { id: "Kageillustrious-Illustrious-XL", rubric: "uncurated", name: "Kageillustrious-Illustrious-XL", family: "sdxl_base_v0.9", files: [[869, 11]], requires: [870, 871, 246], modes: ["text2image"] }, { id: "KantanMIX-XLIllustrious", rubric: "uncurated", name: "KantanMIX-XLIllustrious", family: "sdxl_base_v0.9", files: [[872, 11]], requires: [873, 874, 246], modes: ["text2image"] }, { id: "KFT-Requiem-Fur-a-Dream-Illustrious-Semi-Real-Checkpoint", rubric: "uncurated", name: "KFT-Requiem-Fur-a-Dream-Illustrious-Semi-Real-Checkpoint", family: "sdxl_base_v0.9", files: [[875, 11]], requires: [876, 877, 246], modes: ["text2image"] }, { id: "KonanMix-NoobAI-XL-IllustriousXL", rubric: "uncurated", name: "KonanMix-NoobAI-XL-IllustriousXL", family: "sdxl_base_v0.9", files: [[878, 11]], requires: [879, 880, 246], modes: ["text2image"] }, { id: "koronemix-illustrious", rubric: "uncurated", name: "koronemix-illustrious", family: "sdxl_base_v0.9", files: [[881, 11]], requires: [882, 883, 246], modes: ["text2image"] }, { id: "Lah_Mysterious_Flux_flux_Alpha", rubric: "uncurated", name: "Lah_Mysterious_Flux_flux_Alpha", family: "flux1", files: [[884, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Like-Reality-Pony-by-Ethanar", rubric: "uncurated", name: "Like-Reality-Pony-by-Ethanar", family: "sdxl_base_v0.9", files: [[885, 11]], requires: [886, 887, 246], modes: ["text2image"] }, { id: "Lox_s-Souls-Mix-Prisma-", rubric: "uncurated", name: "Lox_s-Souls-Mix-Prisma-", family: "sdxl_base_v0.9", files: [[888, 11]], requires: [889, 890, 246], modes: ["text2image"] }, { id: "LunarGrapeMix-Illustrious", rubric: "uncurated", name: "LunarGrapeMix-Illustrious", family: "sdxl_base_v0.9", files: [[891, 11]], requires: [892, 893, 246], modes: ["text2image"] }, { id: "Lyh_Anime_Flux_delete", rubric: "uncurated", name: "Lyh_Anime_Flux_delete", family: "flux1", files: [[894, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Madly-Mix-ver-NightNoob", rubric: "uncurated", name: "Madly-Mix-ver-NightNoob", family: "sdxl_base_v0.9", files: [[895, 11]], requires: [896, 897, 246], modes: ["text2image"] }, { id: "Majicflus_v10", rubric: "uncurated", name: "Majicflus_v10", family: "flux1", files: [[898, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "MeichiDarkMix-Reload", rubric: "uncurated", name: "MeichiDarkMix-Reload", family: "sdxl_base_v0.9", files: [[899, 11]], requires: [900, 901, 246], modes: ["text2image"] }, { id: "miruku", rubric: "uncurated", name: "miruku", family: "sdxl_base_v0.9", files: [[902, 11]], requires: [903, 904, 246], modes: ["text2image"] }, { id: "Mistoon-Anime", rubric: "uncurated", name: "Mistoon-Anime", family: "sdxl_base_v0.9", files: [[905, 11]], requires: [906, 907, 246], modes: ["text2image"] }, { id: "Mol-Keun-Mix", rubric: "uncurated", name: "Mol-Keun-Mix", family: "sdxl_base_v0.9", files: [[908, 11]], requires: [909, 910, 246], modes: ["text2image"] }, { id: "MolcajeteMix-NoobIL", rubric: "uncurated", name: "MolcajeteMix-NoobIL", family: "sdxl_base_v0.9", files: [[911, 11]], requires: [912, 913, 246], modes: ["text2image"] }, { id: "Moxie_Flux1DS_flux1D8Step", rubric: "uncurated", name: "Moxie_Flux1DS_flux1D8Step", family: "flux1", files: [[914, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Flux1DS_flux1S8Step", rubric: "uncurated", name: "Moxie_Flux1DS_flux1S8Step", family: "flux1", files: [[915, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Flux1DS_v138Step", rubric: "uncurated", name: "Moxie_Flux1DS_v138Step", family: "flux1", files: [[916, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Flux1DS_v14", rubric: "uncurated", name: "Moxie_Flux1DS_v14", family: "flux1", files: [[917, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Flux1DS_v16D", rubric: "uncurated", name: "Moxie_Flux1DS_v16D", family: "flux1", files: [[918, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Flux1DS_v17S", rubric: "uncurated", name: "Moxie_Flux1DS_v17S", family: "flux1", files: [[919, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_17D", rubric: "uncurated", name: "Moxie_Fusion_Flux_17D", family: "flux1", files: [[920, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v1318step", rubric: "uncurated", name: "Moxie_Fusion_Flux_v1318step", family: "flux1", files: [[921, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v132", rubric: "uncurated", name: "Moxie_Fusion_Flux_v132", family: "flux1", files: [[922, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v1328step", rubric: "uncurated", name: "Moxie_Fusion_Flux_v1328step", family: "flux1", files: [[923, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v1338step", rubric: "uncurated", name: "Moxie_Fusion_Flux_v1338step", family: "flux1", files: [[924, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v134", rubric: "uncurated", name: "Moxie_Fusion_Flux_v134", family: "flux1", files: [[925, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v1348step", rubric: "uncurated", name: "Moxie_Fusion_Flux_v1348step", family: "flux1", files: [[926, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v135", rubric: "uncurated", name: "Moxie_Fusion_Flux_v135", family: "flux1", files: [[927, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v141D", rubric: "uncurated", name: "Moxie_Fusion_Flux_v141D", family: "flux1", files: [[928, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v141S", rubric: "uncurated", name: "Moxie_Fusion_Flux_v141S", family: "flux1", files: [[929, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v15S", rubric: "uncurated", name: "Moxie_Fusion_Flux_v15S", family: "flux1", files: [[930, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v16S", rubric: "uncurated", name: "Moxie_Fusion_Flux_v16S", family: "flux1", files: [[931, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Moxie_Fusion_Flux_v17S", rubric: "uncurated", name: "Moxie_Fusion_Flux_v17S", family: "flux1", files: [[932, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ms_Flux_SFWNSFWV3_v3", rubric: "uncurated", name: "Ms_Flux_SFWNSFWV3_v3", family: "flux1", files: [[933, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Myhuman_Flux_12Train", rubric: "uncurated", name: "Myhuman_Flux_12Train", family: "flux1", files: [[934, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Myhuman_Flux_myh11", rubric: "uncurated", name: "Myhuman_Flux_myh11", family: "flux1", files: [[935, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Myhuman_Flux_myh13", rubric: "uncurated", name: "Myhuman_Flux_myh13", family: "flux1", files: [[936, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Myhuman_Flux_myh13Fp8", rubric: "uncurated", name: "Myhuman_Flux_myh13Fp8", family: "flux1", files: [[937, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Nepotism_x_Dit", rubric: "uncurated", name: "Nepotism_x_Dit", family: "flux1", files: [[938, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Nepotism_xi_Dit", rubric: "uncurated", name: "Nepotism_xi_Dit", family: "flux1", files: [[939, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Nevolution_SDXL_v2_anim_1733673", rubric: "uncurated", name: "Nevolution_SDXL_v2_anim_1733673", family: "sdxl_base_v0.9", files: [[940, 11]], requires: [941, 942, 246], modes: ["text2image"] }, { id: "Nevolution_SDXL_v2_base_1645671", rubric: "uncurated", name: "Nevolution_SDXL_v2_base_1645671", family: "sdxl_base_v0.9", variant: "base", files: [[943, 11]], requires: [944, 945, 246], modes: ["text2image"] }, { id: "NoobAI-XL-NAI-XL", rubric: "uncurated", name: "NoobAI-XL-NAI-XL", family: "sdxl_base_v0.9", files: [[946, 11]], requires: [947, 948, 246], modes: ["text2image"] }, { id: "NostraMix", rubric: "uncurated", name: "NostraMix", family: "sdxl_base_v0.9", files: [[949, 11]], requires: [950, 951, 246], modes: ["text2image"] }, { id: "Nova_Animal_XL_Illustrious_v3.0_1634769", rubric: "uncurated", name: "Nova_Animal_XL_Illustrious_v3.0_1634769", family: "sdxl_base_v0.9", files: [[952, 11]], requires: [953, 954, 246], modes: ["text2image"] }, { id: "Nova_Animal_XL_v4.0_1028888", rubric: "uncurated", name: "Nova_Animal_XL_v4.0_1028888", family: "sdxl_base_v0.9", files: [[955, 11]], requires: [956, 957, 246], modes: ["text2image"] }, { id: "Nova_Furry_XL_Illustrious_v6A_1625975", rubric: "uncurated", name: "Nova_Furry_XL_Illustrious_v6A_1625975", family: "sdxl_base_v0.9", files: [[958, 11]], requires: [959, 960, 246], modes: ["text2image"] }, { id: "Nova_Furry_XL_Illustrious_v6B_1626156", rubric: "uncurated", name: "Nova_Furry_XL_Illustrious_v6B_1626156", family: "sdxl_base_v0.9", files: [[961, 11]], requires: [962, 963, 246], modes: ["text2image"] }, { id: "Nova_Furry_XL_Illustrious_v7A_1759909", rubric: "uncurated", name: "Nova_Furry_XL_Illustrious_v7A_1759909", family: "sdxl_base_v0.9", files: [[964, 11]], requires: [965, 966, 246], modes: ["text2image"] }, { id: "Nova_Furry_XL_Illustrious_v7B_1760102", rubric: "uncurated", name: "Nova_Furry_XL_Illustrious_v7B_1760102", family: "sdxl_base_v0.9", files: [[967, 11]], requires: [968, 969, 246], modes: ["text2image"] }, { id: "Nova_Orange_XL_v7.0_1525944", rubric: "uncurated", name: "Nova_Orange_XL_v7.0_1525944", family: "sdxl_base_v0.9", files: [[970, 11]], requires: [971, 972, 246], modes: ["text2image"] }, { id: "Nova_Orange_XL_v9.0_1701002", rubric: "uncurated", name: "Nova_Orange_XL_v9.0_1701002", family: "sdxl_base_v0.9", files: [[973, 11]], requires: [974, 975, 246], modes: ["text2image"] }, { id: "Nova-3DCG-XL", rubric: "uncurated", name: "Nova-3DCG-XL", family: "sdxl_base_v0.9", files: [[976, 11]], requires: [977, 978, 246], modes: ["text2image"] }, { id: "Nova-Anime-XL", rubric: "uncurated", name: "Nova-Anime-XL", family: "sdxl_base_v0.9", files: [[979, 11]], requires: [980, 981, 246], modes: ["text2image"] }, { id: "Nova-Anime3D-XL", rubric: "uncurated", name: "Nova-Anime3D-XL", family: "sdxl_base_v0.9", files: [[982, 11]], requires: [983, 984, 246], modes: ["text2image"] }, { id: "Nova-Asian-XL", rubric: "uncurated", name: "Nova-Asian-XL", family: "sdxl_base_v0.9", files: [[985, 11]], requires: [986, 987, 246], modes: ["text2image"] }, { id: "Nova-Cross-XL", rubric: "uncurated", name: "Nova-Cross-XL", family: "sdxl_base_v0.9", files: [[988, 11]], requires: [989, 990, 246], modes: ["text2image"] }, { id: "Nova-Flat-XL", rubric: "uncurated", name: "Nova-Flat-XL", family: "sdxl_base_v0.9", files: [[991, 11]], requires: [992, 993, 246], modes: ["text2image"] }, { id: "Nova-Reality-XL", rubric: "uncurated", name: "Nova-Reality-XL", family: "sdxl_base_v0.9", files: [[994, 11]], requires: [995, 996, 246], modes: ["text2image"] }, { id: "Nova-Unreal-XL", rubric: "uncurated", name: "Nova-Unreal-XL", family: "sdxl_base_v0.9", files: [[997, 11]], requires: [998, 999, 246], modes: ["text2image"] }, { id: "ONE-FOR-ALL-Pony-Fantasy-DPOVAE", rubric: "uncurated", name: "ONE-FOR-ALL-Pony-Fantasy-DPOVAE", family: "sdxl_base_v0.9", files: [[1e3, 11]], requires: [1001, 1002, 246], modes: ["text2image"] }, { id: "Oops-All-Toons-Illustrious-v1.0", rubric: "uncurated", name: "Oops-All-Toons-Illustrious-v1.0", family: "sdxl_base_v0.9", files: [[1003, 11]], requires: [1004, 1005, 246], modes: ["text2image"] }, { id: "Oops-All-vpred-NoobAI-Western-2D-furry-toon", rubric: "uncurated", name: "Oops-All-vpred-NoobAI-Western-2D-furry-toon", family: "sdxl_base_v0.9", files: [[1006, 11]], requires: [1007, 1008, 246], modes: ["text2image"] }, { id: "Origin_By_N0utis_flux_FP8V1", rubric: "uncurated", name: "Origin_By_N0utis_flux_FP8V1", family: "flux1", files: [[1009, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Photonic-Fusion-SDXL", rubric: "uncurated", name: "Photonic-Fusion-SDXL", family: "sdxl_base_v0.9", files: [[1010, 11]], requires: [1011, 1012, 246], modes: ["text2image"] }, { id: "pikon-reality_v2_alt", rubric: "uncurated", name: "Pikon_Realism_v2_alt", family: "sdxl_base_v0.9", files: [[1013, 11], [1014, 5]], requires: [1015, 1016, 246], modes: ["text2image"] }, { id: "Pixelwave_flux1Dev02", rubric: "uncurated", name: "Pixelwave_flux1Dev02", family: "flux1", files: [[1017, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Pixelwave_flux1Dev03", rubric: "uncurated", name: "Pixelwave_flux1Dev03", family: "flux1", files: [[1018, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Pixelwave_flux1Schnell03", rubric: "uncurated", name: "Pixelwave_flux1Schnell03", family: "flux1", files: [[1019, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Plant_Milk_Model_Suite_Flax_1331188", rubric: "uncurated", name: "Plant_Milk_Model_Suite_Flax_1331188", family: "sdxl_base_v0.9", files: [[1020, 11]], requires: [1021, 1022, 246], modes: ["text2image"] }, { id: "Plant_Milk_Model_Suite_Hemp_II_1714314", rubric: "uncurated", name: "Plant_Milk_Model_Suite_Hemp_II_1714314", family: "sdxl_base_v0.9", files: [[1023, 11]], requires: [1024, 1025, 246], modes: ["text2image"] }, { id: "Pony_Realism_v2.1_534642", rubric: "uncurated", name: "Pony_Realism_v2.1_534642", family: "sdxl_base_v0.9", files: [[1026, 11]], requires: [1027, 1028, 246], modes: ["text2image"] }, { id: "Pony_Realism_v2.2_914390", rubric: "uncurated", name: "Pony_Realism_v2.2_914390", family: "sdxl_base_v0.9", files: [[1029, 11]], requires: [1030, 1031, 246], modes: ["text2image"] }, { id: "Praeclarus-IllustriousXL", rubric: "uncurated", name: "Praeclarus-IllustriousXL", family: "sdxl_base_v0.9", files: [[1032, 11]], requires: [1033, 1034, 246], modes: ["text2image"] }, { id: "Prefect_illustrious_XL_v1.0_1379960", rubric: "uncurated", name: "Prefect_illustrious_XL_v1.0_1379960", family: "sdxl_base_v0.9", files: [[1035, 11]], requires: [1036, 1037, 246], modes: ["text2image"] }, { id: "Prefect_illustrious_XL_v1.5_1731647", rubric: "uncurated", name: "Prefect_illustrious_XL_v1.5_1731647", family: "sdxl_base_v0.9", files: [[1038, 11]], requires: [1039, 1040, 246], modes: ["text2image"] }, { id: "Prefect-Pony-XL", rubric: "uncurated", name: "Prefect-Pony-XL", family: "sdxl_base_v0.9", files: [[1041, 11]], requires: [1042, 1043, 246], modes: ["text2image"] }, { id: "Project_Gaia_Flux1D_v10UNET", rubric: "uncurated", name: "Project_Gaia_Flux1D_v10UNET", family: "flux1", files: [[1044, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_real1sm_FP16", rubric: "uncurated", name: "Project0_real1sm_FP16", family: "flux1", files: [[1045, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_real1sm_V2FP16", rubric: "uncurated", name: "Project0_real1sm_V2FP16", family: "flux1", files: [[1046, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_real1sm_V2FP8", rubric: "uncurated", name: "Project0_real1sm_V2FP8", family: "flux1", files: [[1047, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_real1sm_V3FP16", rubric: "uncurated", name: "Project0_real1sm_V3FP16", family: "flux1", files: [[1048, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_real1sm_V3FP8AIO", rubric: "uncurated", name: "Project0_real1sm_V3FP8AIO", family: "flux1", files: [[1049, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_v10FP8Unet_Only", rubric: "uncurated", name: "Project0_v10FP8Unet_Only", family: "flux1", files: [[1050, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_v20FP16", rubric: "uncurated", name: "Project0_v20FP16", family: "flux1", files: [[1051, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_v20FP8", rubric: "uncurated", name: "Project0_v20FP8", family: "flux1", files: [[1052, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Project0_v30Art_FP8", rubric: "uncurated", name: "Project0_v30Art_FP8", family: "flux1", files: [[1053, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ratatoskr_Animal_Creature_v29", rubric: "uncurated", name: "Ratatoskr_Animal_Creature_v29", family: "flux1", files: [[1054, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ratatoskr_Animal_Creature_v40FP8", rubric: "uncurated", name: "Ratatoskr_Animal_Creature_v40FP8", family: "flux1", files: [[1055, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ratatoskr_Animal_Creature_v41", rubric: "uncurated", name: "Ratatoskr_Animal_Creature_v41", family: "flux1", files: [[1056, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ratatoskr_Animal_Creature_v594FP8Dev1Hybrid", rubric: "uncurated", name: "Ratatoskr_Animal_Creature_v594FP8Dev1Hybrid", family: "flux1", files: [[1057, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ratatoskr_Animal_Creature_v667FP16", rubric: "uncurated", name: "Ratatoskr_Animal_Creature_v667FP16", family: "flux1", files: [[1058, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ratatoskr_Animal_Creature_v667FP8", rubric: "uncurated", name: "Ratatoskr_Animal_Creature_v667FP8", family: "flux1", files: [[1059, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ratatoskr-Animal_-Creature-and-Furry-", rubric: "uncurated", name: "Ratatoskr-Animal_-Creature-and-Furry-", family: "sdxl_base_v0.9", files: [[1060, 11]], requires: [1061, 1062, 246], modes: ["text2image"] }, { id: "Rayflux_v10", rubric: "uncurated", name: "Rayflux_v10", family: "flux1", files: [[1063, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Rayflux_v30AIO", rubric: "uncurated", name: "Rayflux_v30AIO", family: "flux1", files: [[1064, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Real_Dream_flux1V1", rubric: "uncurated", name: "Real_Dream_flux1V1", family: "flux1", files: [[1065, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "RealCartoon-XL", rubric: "uncurated", name: "RealCartoon-XL", family: "sdxl_base_v0.9", files: [[1066, 11]], requires: [1067, 1068, 246], modes: ["text2image"] }, { id: "Realflux10b_10b_Compact_Schnell", rubric: "uncurated", name: "Realflux10b_10b_Compact_Schnell", family: "flux1", variant: "turbo", files: [[1069, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Realflux10b_10b_Transformer", rubric: "uncurated", name: "Realflux10b_10b_Transformer", family: "flux1", files: [[1070, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Realflux10b_10b_Transformer_Dev", rubric: "uncurated", name: "Realflux10b_10b_Transformer_Dev", family: "flux1", variant: "dev", files: [[1071, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Realism_By_Stable_Yogi_Pony_V3_VAE_992946", rubric: "uncurated", name: "Realism_By_Stable_Yogi_Pony_V3_VAE_992946", family: "sdxl_base_v0.9", files: [[1072, 11]], requires: [1073, 1074, 246], modes: ["text2image"] }, { id: "Realism_By_Stable_Yogi_v4.0_FP16_1422871", rubric: "uncurated", name: "Realism_By_Stable_Yogi_v4.0_FP16_1422871", family: "sdxl_base_v0.9", files: [[1075, 11]], requires: [1076, 1077, 246], modes: ["text2image"] }, { id: "Realism-SDXL-By-Stable-Yogi", rubric: "uncurated", name: "Realism-SDXL-By-Stable-Yogi", family: "sdxl_base_v0.9", files: [[1078, 11]], requires: [1079, 1080, 246], modes: ["text2image"] }, { id: "Realistic-Blend-XL", rubric: "uncurated", name: "Realistic-Blend-XL", family: "sdxl_base_v0.9", files: [[1081, 11]], requires: [1082, 1083, 246], modes: ["text2image"] }, { id: "Red_Blue_Fantasy_fluxv10", rubric: "uncurated", name: "Red_Blue_Fantasy_fluxv10", family: "flux1", files: [[1084, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_f1Fill_NSFW", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_f1Fill_NSFW", family: "flux1", modifier: "inpainting", files: [[1085, 5]], requires: [200, 115, 201], modes: ["inpaint-model"] }, { id: "Redcraft_CADSUpdated_JUN1_new_REVEAL", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_new_REVEAL", family: "flux1", files: [[1086, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_rasch1Forge", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_rasch1Forge", family: "flux1", files: [[1087, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_rasch2", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_rasch2", family: "flux1", files: [[1088, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_rasch3RUSHReveal", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_rasch3RUSHReveal", family: "flux1", files: [[1089, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_realreveal5", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_realreveal5", family: "flux1", files: [[1090, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_red_Edit_Icedit11", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_red_Edit_Icedit11", family: "flux1", modifier: "inpainting", files: [[1091, 5]], requires: [200, 115, 201], modes: ["inpaint-model"] }, { id: "Redcraft_CADSUpdated_JUN1_red_OMNIFlux1Dreamo", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_red_OMNIFlux1Dreamo", family: "flux1", files: [[1092, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_reveal_NSFW", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_reveal_NSFW", family: "flux1", files: [[1093, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_reveal_ULTRAV35", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_reveal_ULTRAV35", family: "flux1", files: [[1094, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_reveal5SFWULTRA", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_reveal5SFWULTRA", family: "flux1", files: [[1095, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Redcraft_CADSUpdated_JUN1_turbo_Reveal_Hotfix21", rubric: "uncurated", name: "Redcraft_CADSUpdated_JUN1_turbo_Reveal_Hotfix21", family: "flux1", variant: "turbo", files: [[1096, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "RedCraft-CADS-UPdated-May4-Commercial-_-Advertising-Design-System", rubric: "uncurated", name: "RedCraft-CADS-UPdated-May4-Commercial-_-Advertising-Design-System", family: "sdxl_base_v0.9", files: [[1097, 11]], requires: [1098, 1099, 246], modes: ["text2image"] }, { id: "richyrichMixIXL", rubric: "uncurated", name: "richyrichMixIXL", family: "sdxl_base_v0.9", files: [[1100, 11]], requires: [1101, 1102, 246], modes: ["text2image"] }, { id: "Rillusm-Realistic-IL", rubric: "uncurated", name: "Rillusm-Realistic-IL", family: "sdxl_base_v0.9", files: [[1103, 11]], requires: [1104, 1105, 246], modes: ["text2image"] }, { id: "Sdvn11Ghibli_Flux_fp8Hyper", rubric: "uncurated", name: "Sdvn11Ghibli_Flux_fp8Hyper", family: "flux1", files: [[1106, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "SilvermoonMix-Illustrious-Evolved", rubric: "uncurated", name: "SilvermoonMix-Illustrious-Evolved", family: "sdxl_base_v0.9", files: [[1107, 11]], requires: [246, 1108, 1109], modes: ["text2image"] }, { id: "SinGlo-illustrious", rubric: "uncurated", name: "SinGlo-illustrious", family: "sdxl_base_v0.9", files: [[1110, 11]], requires: [246, 1111, 1112], modes: ["text2image"] }, { id: "SkibidiMix", rubric: "uncurated", name: "SkibidiMix", family: "sdxl_base_v0.9", files: [[1113, 11]], requires: [246, 1114, 1115], modes: ["text2image"] }, { id: "Smooth_Mix_NoobAI_Illustrious_Pony_Illustrious_v.2_1401686", rubric: "uncurated", name: "Smooth_Mix_NoobAI_Illustrious_Pony_Illustrious_v.2_1401686", family: "sdxl_base_v0.9", files: [[1116, 11]], requires: [246, 1117, 1118], modes: ["text2image"] }, { id: "Smooth_Mix_NoobAI_Illustrious_Pony_Illustrious_v.3_1470541", rubric: "uncurated", name: "Smooth_Mix_NoobAI_Illustrious_Pony_Illustrious_v.3_1470541", family: "sdxl_base_v0.9", files: [[1119, 11]], requires: [246, 1120, 1121], modes: ["text2image"] }, { id: "Smooth_Mix_NoobAI_Illustrious_Pony_NoobAI_v2.0_1629718", rubric: "uncurated", name: "Smooth_Mix_NoobAI_Illustrious_Pony_NoobAI_v2.0_1629718", family: "sdxl_base_v0.9", files: [[1122, 11]], requires: [246, 1123, 1124], modes: ["text2image"] }, { id: "Smooth_Mix_NoobAI_Illustrious_Pony_Pony_v.3_997031", rubric: "uncurated", name: "Smooth_Mix_NoobAI_Illustrious_Pony_Pony_v.3_997031", family: "sdxl_base_v0.9", files: [[1125, 11]], requires: [246, 1126, 1127], modes: ["text2image"] }, { id: "Smooth_Mix_NoobAI_Illustrious_Pony_Realism_1675843", rubric: "uncurated", name: "Smooth_Mix_NoobAI_Illustrious_Pony_Realism_1675843", family: "sdxl_base_v0.9", files: [[1128, 11]], requires: [246, 1129, 1130], modes: ["text2image"] }, { id: "SnowPony", rubric: "uncurated", name: "SnowPony", family: "sdxl_base_v0.9", files: [[1131, 11]], requires: [246, 1132, 1133], modes: ["text2image"] }, { id: "SteinIllustrious", rubric: "uncurated", name: "SteinIllustrious", family: "sdxl_base_v0.9", files: [[1134, 11]], requires: [246, 1135, 1136], modes: ["text2image"] }, { id: "Stoiqo_Newreality_FLUXSD35_F1DAlpha", rubric: "uncurated", name: "Stoiqo_Newreality_FLUXSD35_F1DAlpha", family: "flux1", files: [[1137, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Stoiqo_Newreality_FLUXSD35_f1DAlpha_Two", rubric: "uncurated", name: "Stoiqo_Newreality_FLUXSD35_f1DAlpha_Two", family: "flux1", files: [[1138, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "STOIQOAfrodite_FLUXXL_F1DAlpha", rubric: "uncurated", name: "STOIQOAfrodite_FLUXXL_F1DAlpha", family: "flux1", files: [[1139, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "The_Araminta_Experiment_flux1A1", rubric: "uncurated", name: "The_Araminta_Experiment_flux1A1", family: "flux1", files: [[1140, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Throwing-Pasta-MIX-Spaghetti", rubric: "uncurated", name: "Throwing-Pasta-MIX-Spaghetti", family: "sdxl_base_v0.9", files: [[1141, 11]], requires: [246, 1142, 1143], modes: ["text2image"] }, { id: "Toonify_Toonify_Illustrious_1495132", rubric: "uncurated", name: "Toonify_Toonify_Illustrious_1495132", family: "sdxl_base_v0.9", files: [[1144, 11]], requires: [246, 1145, 1146], modes: ["text2image"] }, { id: "Toonify_Toonify_PonyDiffusionXL_410539", rubric: "uncurated", name: "Toonify_Toonify_PonyDiffusionXL_410539", family: "sdxl_base_v0.9", files: [[1147, 11]], requires: [246, 1148, 1149], modes: ["text2image"] }, { id: "tt-animerge", rubric: "uncurated", name: "tt-animerge", family: "v1", files: [[1150, 11]], requires: [1151], modes: ["text2image"] }, { id: "Ultra-Realistic-By-Stable-Yogi-Pony", rubric: "uncurated", name: "Ultra-Realistic-By-Stable-Yogi-Pony", family: "sdxl_base_v0.9", files: [[1152, 11]], requires: [246, 1153, 1154], modes: ["text2image"] }, { id: "Ultrareal_Fine_Tune_v1", rubric: "uncurated", name: "Ultrareal_Fine_Tune_v1", family: "flux1", files: [[1155, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ultrareal_Fine_Tune_v10", rubric: "uncurated", name: "Ultrareal_Fine_Tune_v10", family: "flux1", files: [[1156, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ultrareal_Fine_Tune_v20", rubric: "uncurated", name: "Ultrareal_Fine_Tune_v20", family: "flux1", files: [[1157, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Ultrareal_Fine_Tune_v4", rubric: "uncurated", name: "Ultrareal_Fine_Tune_v4", family: "flux1", files: [[1158, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "UmbroxPonyXL", rubric: "uncurated", name: "UmbroxPonyXL", family: "sdxl_base_v0.9", files: [[1159, 11]], requires: [246, 1160, 1161], modes: ["text2image"] }, { id: "Uncanny-valley", rubric: "uncurated", name: "Uncanny-valley", family: "sdxl_base_v0.9", files: [[1162, 11]], requires: [246, 1163, 1164], modes: ["text2image"] }, { id: "untitled-pony", rubric: "uncurated", name: "untitled-pony", family: "sdxl_base_v0.9", files: [[1165, 11]], requires: [246, 1166, 1167], modes: ["text2image"] }, { id: "Verus_Vision10b_10b_Transformer", rubric: "uncurated", name: "Verus_Vision10b_10b_Transformer", family: "flux1", files: [[1168, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Virtual-Diffusion-Pony-XL-2025", rubric: "uncurated", name: "Virtual-Diffusion-Pony-XL-2025", family: "sdxl_base_v0.9", files: [[1169, 11]], requires: [246, 1170, 1171], modes: ["text2image"] }, { id: "Vixons-Dream-Weave", rubric: "uncurated", name: "Vixon_s-Dream-Weave", family: "sdxl_base_v0.9", files: [[1172, 11], [1173, 11]], requires: [246, 1174, 1172, 1175], modes: ["text2image"] }, { id: "WAI-SHUFFLE-NOOB", rubric: "uncurated", name: "WAI-SHUFFLE-NOOB", family: "sdxl_base_v0.9", files: [[1176, 11]], requires: [246, 1177, 1178], modes: ["text2image"] }, { id: "Whiteflux1_v10", rubric: "uncurated", name: "Whiteflux1_v10", family: "flux1", files: [[1179, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Xe_Hentai_Anime_FLUX_03", rubric: "uncurated", name: "Xe_Hentai_Anime_FLUX_03", family: "flux1", files: [[1180, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Xe_Hentai_Anime_FLUX_04", rubric: "uncurated", name: "Xe_Hentai_Anime_FLUX_04", family: "flux1", files: [[1181, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "Xuer_One_Cyan_Ten_Color_flux_V10", rubric: "uncurated", name: "Xuer_One_Cyan_Ten_Color_flux_V10", family: "flux1", files: [[1182, 5]], requires: [200, 115, 201], modes: ["text2image"] }, { id: "ZavyChromaXL", rubric: "uncurated", name: "ZavyChromaXL", family: "sdxl_base_v0.9", files: [[1183, 11]], requires: [246, 1184, 1185], modes: ["text2image"] }, { id: "ZEP9", rubric: "uncurated", name: "ZEP9", family: "sdxl_base_v0.9", files: [[1186, 11]], requires: [246, 1187, 1188], modes: ["text2image"] }] };
// src/services/modelInventory.ts
var runtimeCatalog = modelZoo_runtime_default;
var asRecord = (v) => v && typeof v === "object" ? v : {};
function decodeJsonBytes(buf) {
if (!buf) return [];
if (Array.isArray(buf)) return buf;
try {
const parsed = JSON.parse(Buffer.from(buf).toString("utf8") || "[]");
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function parseEchoResponse(resp) {
const r = asRecord(resp);
const files = Array.isArray(r.files) ? r.files.filter((f) => typeof f === "string") : [];
const models = decodeJsonBytes(asRecord(r.override).models).map(asRecord).filter((m) => typeof m.file === "string");
return { files, models };
}
var LINE_DROP = /* @__PURE__ */ new Set(["turbo", "fast", "instant", "distilled", "lightning", "schnell", "base", "raw", "exact", "dev", "bf", "bf16", "f16"]);
function modelLine(id) {
return id.toLowerCase().replace(/_/g, "-").split("-").filter((t) => t && !LINE_DROP.has(t)).join("-");
}
function buildInventory(echo, catalog = runtimeCatalog) {
const files = new Set(echo.files);
const specByFile = new Map(echo.models.map((m) => [m.file, m]));
const catalogFiles = /* @__PURE__ */ new Set();
const installed = [];
const byFile = /* @__PURE__ */ new Map();
for (const [rank, m] of catalog.models.entries()) {
const names = m.files.map(([i]) => catalog.files[i]);
names.forEach((n) => catalogFiles.add(n));
const present = names.filter((n) => files.has(n));
if (!present.length) continue;
const precisionRank = Math.max(...m.files.filter(([i]) => files.has(catalog.files[i])).map(([, r]) => r ?? -1));
const missing = (m.requires ?? []).map((i) => catalog.files[i]).filter((n) => !files.has(n));
const entry = {
id: m.id,
rubric: m.rubric,
name: m.name,
family: m.family,
kind: catalog.families[m.family]?.kind ?? "image",
modes: m.modes,
modesUncertain: !!m.modesUncertain,
file: present[0],
installedFiles: present,
missing,
ready: missing.length === 0,
specKnown: present.some((n) => specByFile.has(n)),
deprecated: !!m.deprecated,
rank,
line: modelLine(m.id),
variant: m.variant,
precisionRank,
hasRecommendation: !!m.recommended || !!catalog.families[m.family]?.fallback
};
installed.push(entry);
present.forEach((n) => byFile.set(n, entry));
}
const custom = [];
const customByFile = /* @__PURE__ */ new Map();
for (const spec of echo.models) {
if (catalogFiles.has(spec.file)) continue;
const missing = [spec.text_encoder, spec.autoencoder].filter((n) => typeof n === "string" && n.endsWith(".ckpt") && !files.has(n));
const entry = { name: spec.name ?? spec.file, file: spec.file, family: spec.version ?? "unknown", modifier: spec.modifier, missing, ready: missing.length === 0 };
custom.push(entry);
customByFile.set(spec.file, entry);
}
installed.sort((a, b) => a.family.localeCompare(b.family) || a.id.localeCompare(b.id));
custom.sort((a, b) => a.file.localeCompare(b.file));
const hash = [
...installed.map((m) => `${m.id}|${m.file}|${m.ready ? 1 : 0}|${m.specKnown ? 1 : 0}`),
...custom.map((m) => `custom|${m.file}|${m.ready ? 1 : 0}`)
].join("\n");
return { files, installed, custom, byFile, customByFile, hash };
}
var MODE_TO_CATALOG = {
text2image: "text2image",
txt2img: "text2image",
image2image: "text2image",
img2img: "text2image",
edit: "edit",
inpaint: "edit",
outpaint: "edit",
text2video: "text2video",
txt2vid: "text2video",
image2video: "image2video",
img2vid: "image2video"
};
function catalogModelById(id) {
return runtimeCatalog.models.find((m) => m.id === id);
}
function catalogModeFor(mode) {
return MODE_TO_CATALOG[mode] ?? mode;
}
function supportsMode(modes, mode) {
const wanted = catalogModeFor(mode);
if (modes.includes(wanted)) return true;
return wanted === "text2image" && IMAGE2IMAGE_MODES.has(mode) && modes.includes("edit");
}
var IMAGE2IMAGE_MODES = /* @__PURE__ */ new Set(["image2image", "img2img"]);
function listAvailable(inv, mode) {
return inv.installed.filter((m) => m.ready && supportsMode(m.modes, mode));
}
var SPEED_RANK = { turbo: 3, dev: 2, base: 1 };
function pickFallbackModel(inv, mode, opts = {}) {
const eligible = inv.installed.filter(
(m) => m.ready && !m.deprecated && m.rubric !== "uncurated" && m.hasRecommendation && supportsMode(m.modes, mode) && (!opts.family || m.family === opts.family) && (!opts.accept || opts.accept(m))
);
if (!eligible.length) return null;
const newest = eligible.reduce((a, b) => b.rank < a.rank ? b : a);
const speed = (m) => SPEED_RANK[m.variant ?? ""] ?? 2;
const model = eligible.filter((m) => m.family === newest.family && m.line === newest.line).reduce((a, b) => (speed(b) - speed(a) || b.precisionRank - a.precisionRank || a.rank - b.rank) > 0 ? b : a);
return { model, notes: [] };
}
function stateOfFile(inv, file) {
const model = inv.byFile.get(file);
if (model) return model.ready ? { state: "ready", model } : { state: "requires-missing", model, missing: model.missing };
const custom = inv.customByFile.get(file);
if (custom) return { state: "custom", model: custom };
return { state: "not-installed" };
}
var fileIndex = null;
function catalogModelOfFile(file) {
if (!fileIndex) {
fileIndex = /* @__PURE__ */ new Map();
for (const m of runtimeCatalog.models) for (const [i] of m.files) fileIndex.set(runtimeCatalog.files[i], m);
}
return fileIndex.get(file);
}
function explainFile(inv, file, mode) {
const s = stateOfFile(inv, file);
if (s.state === "not-installed") {
const sibling = catalogModelOfFile(file);
const other = sibling && inv.installed.find((m) => m.id === sibling.id)?.installedFiles[0];
return other ? `'${file}' is not installed (another precision of the same model is: ${other}).` : `'${file}' is not installed.`;
}
if (s.state === "requires-missing") return `'${file}' is installed, but required files are missing: ${s.missing.join(", ")}.`;
if (s.state === "custom") return s.model.ready ? `'${file}' is a custom model (${s.model.family}).` : `'${file}' is a custom model, but required files are missing: ${s.model.missing.join(", ")}.`;
if (mode && !supportsMode(s.model.modes, mode)) {
const alt = listAvailable(inv, mode).slice(0, 3).map((m) => m.id);
return `'${s.model.name}' does not support mode '${mode}' (supports: ${s.model.modes.join(", ")}).${alt.length ? ` Installed alternatives: ${alt.join(", ")}.` : ""}`;
}
return `'${file}' is ready.`;
}
function createInventoryProvider(opts) {
const ttlMs = opts.ttlMs ?? 45e3;
const timeoutMs = opts.timeoutMs ?? 2e3;
const now = opts.now ?? Date.now;
let last = null;
let inflight = null;
const readSnapshot = () => {
if (!opts.snapshotPath) return null;
try {
const raw = JSON.parse(fs2.readFileSync(opts.snapshotPath, "utf8"));
return buildInventory({ files: raw.files ?? [], models: raw.models ?? [] }, opts.catalog);
} catch {
return null;
}
};
const writeSnapshot = (echo) => {
if (!opts.snapshotPath) return;
try {
const models = echo.models.map(({ file, name, version, modifier, text_encoder, autoencoder }) => ({ file, name, version, modifier, text_encoder, autoencoder }));
fs2.mkdirSync(path2.dirname(opts.snapshotPath), { recursive: true });
fs2.writeFileSync(opts.snapshotPath, JSON.stringify({ files: echo.files, models }));
} catch {
}
};
const refresh = async () => {
const started = now();
let timer;
try {
const echo = await Promise.race([
opts.fetchEcho(),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error("inventory timeout")), timeoutMs);
})
]);
const inventory = buildInventory(echo, opts.catalog);
const durationMs = now() - started;
last = { at: now(), inventory, durationMs };
writeSnapshot(echo);
return { inventory, source: "live", stale: false, durationMs };
} catch {
const snap = last?.inventory ?? readSnapshot();
return { inventory: snap, source: snap ? "snapshot" : "none", stale: true, durationMs: null };
} finally {
if (timer) clearTimeout(timer);
}
};
return {
prime(echo, durationMs = 0) {
const inventory = buildInventory(echo, opts.catalog);
last = { at: now(), inventory, durationMs };
writeSnapshot(echo);
return inventory;
},
peek() {
return last?.inventory ?? null;
},
async get() {
if (last && now() - last.at < ttlMs) return { inventory: last.inventory, source: "cache", stale: false, durationMs: last.durationMs };
inflight ??= refresh().finally(() => {
inflight = null;
});
return inflight;
}
};
}
// src/services/modelInventoryRuntime.ts
import path5 from "node:path";
// src/helpers/paths.ts
import fs3 from "fs";
import path3 from "path";
function resolveProjectRootFrom(startDir) {
try {
{
let dir = startDir;
for (let i = 0; i < 50; i++) {
try {
if (fs3.existsSync(path3.join(dir, "manifest.json"))) return dir;
} catch {
}
const parent = path3.dirname(dir);
if (parent === dir) break;
dir = parent;
}
}
{
let dir = startDir;
for (let i = 0; i < 50; i++) {
try {
if (fs3.existsSync(path3.join(dir, "package.json"))) return dir;
} catch {
}
const parent = path3.dirname(dir);
if (parent === dir) break;
dir = parent;
}
}
{
let dir = startDir;
for (let i = 0; i < 30; i++) {
const base = path3.basename(dir);
if (base === "dist" || base === "src") return path3.dirname(dir);
const parent = path3.dirname(dir);
if (parent === dir) break;
dir = parent;
}
}
} catch {
}
return startDir;
}
function getProjectRoot() {
try {
if (fs3.existsSync(path3.join(process.cwd(), "manifest.json"))) {
return process.cwd();
}
} catch {
}
try {
const filePath = typeof __filename !== "undefined" && __filename ? __filename : process.argv && process.argv[1] ? process.argv[1] : process.cwd();
const moduleDir = path3.dirname(filePath);
return resolveProjectRootFrom(moduleDir);
} catch {
return resolveProjectRootFrom(process.cwd());
}
}
function getLogsDir() {
return path3.join(getProjectRoot(), "logs");
}
var cachedPluginLogFilename;
function getPluginLogFilename() {
if (cachedPluginLogFilename !== void 0) return cachedPluginLogFilename;
try {
const raw = fs3.readFileSync(path3.join(getProjectRoot(), "manifest.json"), "utf-8");
const name = JSON.parse(raw)?.name;
if (typeof name === "string" && name.trim()) {
cachedPluginLogFilename = `${name.trim()}-plugin.log`;
return cachedPluginLogFilename;
}
} catch {
}
cachedPluginLogFilename = "generate-image-plugin.log";
return cachedPluginLogFilename;
}
function ensureLogsDir() {
const dir = getLogsDir();
try {
if (!fs3.existsSync(dir)) fs3.mkdirSync(dir, { recursive: true });
} catch {
}
}
// src/services/catalogParams.ts
var RECOMMENDED_KEYS = ["steps", "guidance_scale", "shift", "sampler", "resolution_dependent_shift", "clip_skip"];
function recommendedParamsFor(model) {
const own = model.recommended;
const fallback = runtimeCatalog.families[model.family]?.fallback;
const src = own ? { params: own.params, source: own.source } : fallback ? { params: fallback.params, source: "family-fallback" } : null;
if (!src) return null;
const params = {};
for (const k of RECOMMENDED_KEYS) if (src.params[k] !== void 0) params[k] = src.params[k];
return Object.keys(params).length ? { params, source: src.source } : null;
}
var loraFiles = (overlay) => (Array.isArray(overlay.loras) ? overlay.loras : []).map((l) => l?.file).filter((f) => typeof f === "string" && !!f);
function loraFallbackOverlay(overlay, inv) {
const loras = loraFiles(overlay);
const main = overlay.model;
if (!inv || !loras.length || typeof main !== "string" || !inv.files.has(main)) return null;
const missing = loras.filter((f) => !inv.files.has(f));
const model = catalogModelOfFile(main);
const rec = model && recommendedParamsFor(model);
if (!missing.length || !rec) return null;
const params = { ...overlay, loras: [] };
for (const k of RECOMMENDED_KEYS) delete params[k];
Object.assign(params, rec.params);
const steps = typeof rec.params.steps === "number" ? `, ${rec.params.steps} steps` : "";
return { params, note: `LoRA '${missing[0]}' is not installed; using the model's recommended settings (${rec.source}${steps}) instead of the tuned turbo settings. Expect slower rendering.` };
}
function catalogOverlayFor(key, inv) {
const model = catalogModelById(key) ?? catalogModelOfFile(key);
if (!model) {
const custom = inv?.customByFile.get(key);
return custom ? { params: { model: key }, note: `Custom model '${custom.name}': no recommended settings, engine defaults apply.` } : null;
}
const installed = inv?.installed.find((m) => m.id === model.id);
const file = key.endsWith(".ckpt") && model.files.some(([i]) => runtimeCatalog.files[i] === key) ? key : installed?.file ?? runtimeCatalog.files[model.files[0][0]];
const rec = recommendedParamsFor(model);
return {
params: { model: file, ...rec?.params ?? {} },
note: rec ? `No tuned preset for '${model.id}'; using its recommended settings (${rec.source}).` : `No tuned preset or recommended settings for '${model.id}'; using engine defaults.`
};
}
var OVERLAY_MODE = {
text2image: "txt2img",
image2image: "img2img",
edit: "edit",
inpaint: "edit",
outpaint: "edit",
text2video: "txt2vid",
image2video: "img2vid"
};
function toOverlayMode(mode) {
return OVERLAY_MODE[mode] ?? null;
}
function installedFileOf(file, inv) {
if (!file || !inv || inv.files.has(file)) return { file, substituted: false };
const model = catalogModelOfFile(file);
const installed = model && inv.installed.find((m) => m.id === model.id && m.ready);
return installed ? { file: installed.file, substituted: true } : { file, substituted: false };
}
function withInstalledPrecision(overlay, inv) {
const model = overlay.model;
if (typeof model !== "string") return overlay;
const { file, substituted } = installedFileOf(model, inv);
return substituted ? { ...overlay, model: file } : overlay;
}
function tunedPresetFor(modelId, mode, inv, onlyFile) {
const overlayMode = toOverlayMode(mode) ?? mode;
const model = runtimeCatalog.models.find((m) => m.id === modelId);
const files = new Set(model?.files.map(([i]) => runtimeCatalog.files[i]));
for (const id of MODEL_IDS) {
if (id === "auto" || id === "custom") continue;
const file = getModelFilename(id, overlayMode);
if (!file || !files.has(file)) continue;
const effective = onlyFile ? file === onlyFile ? file : null : installedFileOf(file, inv).file;
if (effective && inv.files.has(effective)) return id;
}
return null;
}
function officialNameFor(name) {
if (name === "auto" || name === "custom") return name;
for (const mode of ["txt2img", "edit", "txt2vid", "img2img", "img2vid"]) {
const file = getModelFilename(name, mode);
const model = file ? catalogModelOfFile(file) : void 0;
if (model) return model.family;
}
return name;
}
// src/catalog/modelAliases.generated.json
var modelAliases_generated_default = {
schema: "dtc.model-aliases.generated.v1",
comment: "Generated by scripts/build-model-catalog.mjs from the public catalog (tag and label of every family). Do not edit; manual additions belong in modelAliases.manual.json.",
sources: {
drawThingsCommunity: "db37e657ad329dd16c2f1200bb47f940369cd9f4",
communityModels: "e9851164709187e7249471701708301842f9f222"
},
aliases: {
auraflow: [
"auraflow"
],
cosmos: [
"cosmos2.5_2b"
],
"cosmos-2-5": [
"cosmos2.5_2b"
],
"cosmos-2-5-2b": [
"cosmos2.5_2b"
],
"cosmos2-5": [
"cosmos2.5_2b"
],
"cosmos2-5-2b": [
"cosmos2.5_2b"
],
ernie: [
"ernie_image"
],
"ernie-image": [
"ernie_image"
],
flux: [
"flux1",
"flux2",
"flux2_4b",
"flux2_9b",
"flux3_5b"
],
"flux-1": [
"flux1"
],
"flux-2": [
"flux2",
"flux2_4b",
"flux2_9b"
],
"flux-2-4b": [
"flux2_4b"
],
"flux-2-9b": [
"flux2_9b"
],
"flux-3": [
"flux3_5b"
],
"flux-3-5b": [
"flux3_5b"
],
flux1: [
"flux1"
],
flux2: [
"flux2",
"flux2_4b",
"flux2_9b"
],
"flux2-4b": [
"flux2_4b"
],
"flux2-9b": [
"flux2_9b"
],
flux3: [
"flux3_5b"
],
"flux3-5b": [
"flux3_5b"
],
hidream: [
"hidream_i1"
],
"hidream-i1": [
"hidream_i1"
],
hunyuan: [
"hunyuan_video"
],
"hunyuan-video": [
"hunyuan_video"
],
ideogram: [
"ideogram_4"
],
"ideogram-4": [
"ideogram_4"
],
kandinsky: [
"kandinsky2.1"
],
"kandinsky-v2-1": [
"kandinsky2.1"
],
"kandinsky2-1": [
"kandinsky2.1"
],
krea: [
"krea_2"
],
"krea-2": [
"krea_2"
],
ltx: [
"ltx2",
"ltx2.3"
],
"ltx-2": [
"ltx2"
],
"ltx-2-3": [
"ltx2.3"
],
ltx2: [
"ltx2"
],
"ltx2-3": [
"ltx2.3"
],
minimax: [
"minimax_h3"
],
"minimax-h3": [
"minimax_h3"
],
moss: [
"moss_image"
],
"moss-image": [
"moss_image"
],
pixart: [
"pixart"
],
"pixart-sigma": [
"pixart"
],
qwen: [
"qwen_image",
"qwen_image_2.1"
],
"qwen-image": [
"qwen_image",
"qwen_image_2.1"
],
"qwen-image-2-1": [
"qwen_image_2.1"
],
sd3: [
"sd3",
"sd3_large"
],
"sd3-large": [
"sd3_large"
],
sdxl: [
"sdxl_base_v0.9",
"sdxl_refiner_v0.9"
],
"sdxl-base": [
"sdxl_base_v0.9"
],
"sdxl-base-v0-9": [
"sdxl_base_v0.9"
],
"sdxl-refiner": [
"sdxl_refiner_v0.9"
],
"sdxl-refiner-v0-9": [
"sdxl_refiner_v0.9"
],
seedvr: [
"seedvr2_3b",
"seedvr2_7b"
],
seedvr2: [
"seedvr2_3b",
"seedvr2_7b"
],
"seedvr2-3b": [
"seedvr2_3b"
],
"seedvr2-7b": [
"seedvr2_7b"
],
segmind: [
"ssd_1b"
],
"segmind-stable": [
"ssd_1b"
],
"segmind-stable-diffusion": [
"ssd_1b"
],
"segmind-stable-diffusion-xl": [
"ssd_1b"
],
"segmind-stable-diffusion-xl-1b": [
"ssd_1b"
],
ssd: [
"ssd_1b"
],
"ssd-1b": [
"ssd_1b"
],
"stable-cascade": [
"wurstchen_v3.0_stage_c"
],
"stable-cascade-w-rstchen": [
"wurstchen_v3.0_stage_c"
],
"stable-cascade-w-rstchen-v3-0": [
"wurstchen_v3.0_stage_c"
],
"stable-diffusion-3": [
"sd3",
"sd3_large"
],
"stable-diffusion-3-large": [
"sd3_large"
],
"stable-diffusion-3-medium": [
"sd3"
],
"stable-diffusion-v1": [
"v1"
],
"stable-diffusion-v2": [
"v2"
],
"stable-diffusion-xl": [
"sdxl_base_v0.9",
"sdxl_refiner_v0.9"
],
"stable-diffusion-xl-base": [
"sdxl_base_v0.9"
],
"stable-diffusion-xl-refiner": [
"sdxl_refiner_v0.9"
],
"stable-video": [
"svd_i2v"
],
"stable-video-diffusion": [
"svd_i2v"
],
svd: [
"svd_i2v"
],
"svd-i2v": [
"svd_i2v"
],
wan: [
"wan_v2.1_1.3b",
"wan_v2.1_14b",
"wan_v2.2_5b"
],
"wan-v2-1": [
"wan_v2.1_1.3b",
"wan_v2.1_14b"
],
"wan-v2-1-1-3b": [
"wan_v2.1_1.3b"
],
"wan-v2-1-14b": [
"wan_v2.1_14b"
],
"wan-v2-2": [
"wan_v2.2_5b"
],
"wan-v2-2-5b": [
"wan_v2.2_5b"
],
"wan-v2-x": [
"wan_v2.1_14b"
],
"wan-v2-x-14b": [
"wan_v2.1_14b"
],
wurstchen: [
"wurstchen_v3.0_stage_c"
],
"wurstchen-v3-0": [
"wurstchen_v3.0_stage_c"
],
"wurstchen-v3-0-stage": [
"wurstchen_v3.0_stage_c"
],
"wurstchen-v3-0-stage-c": [
"wurstchen_v3.0_stage_c"
],
"z-image": [
"z_image"
]
},
agentNames: [
{
name: "AuraFlow",
kind: "family",
scope: "families",
families: [
"auraflow"
],
models: [
"auraflow_v0.2"
],
modes: [
"text2image"
],
keys: [
"auraflow"
]
},
{
name: "Cosmos 2.5",
kind: "family",
scope: "families",
families: [
"cosmos2.5_2b"
],
models: [
"anima-aesthetic-1.1",
"anima-base-1.0",
"anima-turbo-1.0"
],
modes: [
"text2image"
],
keys: [
"cosmos-2-5",
"cosmos2-5"
]
},
{
name: "ERNIE Image",
kind: "family",
scope: "families",
families: [
"ernie_image"
],
models: [
"ernie-image-1.0-exact",
"ernie-image-turbo-1.0-exact",
"ernie_image",
"ernie_image_turbo"
],
modes: [
"text2image"
],
keys: [
"ernie-image"
]
},
{
name: "FLUX.1",
kind: "family",
scope: "families",
families: [
"flux1"
],
models: [
"artsy-vibe-v1",
"chroma-1-hd",
"chroma-v47-detail-calibrated",
"chroma-v48-detail-calibrated",
"devmode-v0.3-turbo",
"flux-1-canny-dev",
"flux-1-depth-dev",
"flux-1-dev",
"flux-1-dev-de-distill",
"flux-1-dev-exact",
"flux-1-fill-dev",
"flux-1-kontext-dev",
"flux-1-kontext-dev-exact",
"flux-1-krea-dev",
"pixelwave-flux-1-schnell-04",
"rayflux-v3.0",
"schnellmode-v3.3",
"shuttle-jaguar",
"shuttle-v3.1-aesthetic",
"flux_1_schnell"
],
modes: [
"text2image",
"edit"
],
keys: [
"flux-1",
"flux1"
]
},
{
name: "FLUX.2",
kind: "family",
scope: "families",
families: [
"flux2",
"flux2_4b",
"flux2_9b"
],
models: [
"flux-2-dev",
"flux-2-dev-exact",
"flux-2-klein-4b-exact",
"flux-2-klein-base-4b-exact",
"flux_2_klein_4b",
"flux_2_klein_base_4b",
"flux-2-klein-9b",
"flux-2-klein-9b-exact",
"flux-2-klein-9b-kv",
"flux-2-klein-9b-kv-exact",
"flux-2-klein-base-9b",
"flux-2-klein-base-9b-exact"
],
modes: [
"text2image",
"image2image",
"edit"
],
keys: [
"flux-2",
"flux2"
]
},
{
name: "FLUX.3",
kind: "family",
scope: "families",
families: [
"flux3_5b"
],
models: [
"flux-3-klein",
"flux-3-klein-base",
"flux-3-klein-base-exact",
"flux-3-klein-exact"
],
modes: [
"text2image",
"edit"
],
keys: [
"flux-3",
"flux3"
]
},
{
name: "HiDream I1",
kind: "family",
scope: "families",
families: [
"hidream_i1"
],
models: [
"hidream-e1-1-exact",
"hidream-i1-dev-exact",
"hidream-i1-fast-exact",
"hidream-i1-full-exact",
"hidream_e1_1",
"hidream_e1_full",
"hidream_i1_dev",
"hidream_i1_fast",
"hidream_i1_full"
],
modes: [
"text2image",
"edit"
],
keys: [
"hidream-i1"
]
},
{
name: "Hunyuan Video",
kind: "family",
scope: "families",
families: [
"hunyuan_video"
],
models: [
"hunyuan-video-t2v-720p",
"skyreels-v1-hunyuan-i2v-544p",
"skyreels-v1-hunyuan-t2v-544p"
],
modes: [
"text2video",
"image2video"
],
keys: [
"hunyuan-video"
]
},
{
name: "Ideogram 4",
kind: "family",
scope: "families",
families: [
"ideogram_4"
],
models: [
"ideogram-4",
"ideogram-4-fast",
"ideogram-4-instant"
],
modes: [
"text2image"
],
keys: [
"ideogram-4",
"ideogram4"
]
},
{
name: "Krea 2",
kind: "family",
scope: "families",
families: [
"krea_2"
],
models: [
"krea-2-raw",
"krea-2-turbo"
],
modes: [
"text2image",
"image2image"
],
keys: [
"krea-2",
"krea2"
]
},
{
name: "LTX-2",
kind: "family",
scope: "families",
families: [
"ltx2"
],
models: [
"ltx_2_19b_dev",
"ltx_2_19b_distilled"
],
modes: [
"text2video",
"image2video"
],
keys: [
"ltx-2",
"ltx2"
]
},
{
name: "LTX-2.3",
kind: "family",
scope: "families",
families: [
"ltx2.3"
],
models: [
"ltx-2.3-22b-dev-exact",
"ltx-2.3-22b-distilled-exact",
"ltx_2.3_22b_dev",
"ltx_2.3_22b_distilled_1.1"
],
modes: [
"text2video",
"image2video"
],
keys: [
"ltx-2-3",
"ltx2-3"
]
},
{
name: "MOSS Image",
kind: "family",
scope: "families",
families: [
"moss_image"
],
models: [
"moss_image_base",
"moss_image_sft"
],
modes: [
"text2image"
],
keys: [
"moss-image"
]
},
{
name: "PixArt Sigma",
kind: "family",
scope: "families",
families: [
"pixart"
],
models: [
"pixart_sigma_xl_2_1024_ms",
"pixart_sigma_xl_2_512_ms"
],
modes: [
"text2image"
],
keys: [
"pixart-sigma"
]
},
{
name: "Qwen Image",
kind: "family",
scope: "families",
families: [
"qwen_image"
],
models: [
"qwen-image-1.0-bf-exact",
"qwen-image-1.0-exact",
"qwen-image-2512-bf-exact",
"qwen-image-edit-2509-bf-exact",
"qwen-image-edit-2509-exact",
"qwen_image_1.0",
"qwen_image_1.0_bf16",
"qwen_image_2512",
"qwen_image_2512_bf16",
"qwen_image_edit_1.0",
"qwen_image_edit_2509",
"qwen_image_edit_2509_bf16",
"qwen_image_edit_2511",
"qwen_image_edit_2511_bf16",
"qwen_image_layered_1.0",
"qwen_image_layered_1.0_bf16"
],
modes: [
"text2image",
"image2image",
"edit"
],
keys: [
"qwen-image"
]
},
{
name: "Qwen Image 2.1",
kind: "family",
scope: "families",
families: [
"qwen_image_2.1"
],
models: [
"qwen-image-2.1",
"qwen-image-2.1-exact",
"qwen-image-2.1-turbo",
"qwen-image-2.1-turbo-exact"
],
modes: [
"text2image",
"edit"
],
keys: [
"qwen-image-2-1"
]
},
{
name: "Stable Diffusion 3 Medium",
kind: "family",
scope: "families",
families: [
"sd3"
],
models: [
"sd3-medium",
"sd3-medium-3.5"
],
modes: [
"text2image"
],
keys: [
"stable-diffusion-3-medium"
]
},
{
name: "Stable Diffusion 3 Large",
kind: "family",
scope: "families",
families: [
"sd3_large"
],
models: [
"sd3-large-3.5",
"sd3-large-3.5-exact",
"sd3-large-turbo-3.5"
],
modes: [
"text2image"
],
keys: [
"stable-diffusion-3-large"
]
},
{
name: "Stable Diffusion XL Base",
kind: "family",
scope: "families",
families: [
"sdxl_base_v0.9"
],
models: [
"animagine-xl",
"colorfulxl-v6.0",
"dreamshaper-xl-v2.1-turbo",
"icatcher-cartoon",
"icatcher-realistic",
"juggernaut-xl-ragnarok",
"juggernaut-xl-v9",
"juggernaut-xl-v9-lightning",
"juggernaut-xl-x",
"kwai-kolors-1.0",
"kwai-kolors-inpainting-1.0",
"pixelwave-v10",
"pixelwave-v9",
"playground-v2",
"playground-v2.5",
"proteus-v0.3",
"realvisxl-v4.0",
"sdxl-turbo",
"fooocus_inpaint_sd_xl_v2.6",
"fooocus_inpaint_sd_xl_v2.6_q6p",
"sd_xl_base_1.0",
"sd_xl_base_1.0_q6p"
],
modes: [
"text2image"
],
keys: [
"stable-diffusion-xl-base"
]
},
{
name: "Stable Diffusion XL Refiner",
kind: "family",
scope: "families",
families: [
"sdxl_refiner_v0.9"
],
models: [
"sd_xl_refiner_1.0",
"sd_xl_refiner_1.0_q6p"
],
modes: [
"text2image"
],
keys: [
"stable-diffusion-xl-refiner"
]
},
{
name: "Segmind Stable Diffusion XL",
kind: "family",
scope: "families",
families: [
"ssd_1b"
],
models: [
"ssd-1b"
],
modes: [
"text2image"
],
keys: [
"segmind-stable-diffusion-xl"
]
},
{
name: "Stable Video Diffusion",
kind: "family",
scope: "families",
families: [
"svd_i2v"
],
models: [
"animatelcm-svd-xt-v1.1",
"svd-v1.0",
"svd-xt-v1.1"
],
modes: [
"image2video"
],
keys: [
"stable-video-diffusion"
]
},
{
name: "Stable Diffusion v1",
kind: "family",
scope: "families",
families: [
"v1"
],
models: [
"aloeveras-simpmaker-3k1",
"analog-v1",
"anything-v3",
"arcane-v3",
"balloon-art-v1",
"classic-animation-v1",
"counterfeit-v3.0",
"cyberpunk-anime",
"deliberate-v2.0",
"disney-pixar-cartoon-type-b",
"dnd-classes-and-species",
"dreamshaper-v8",
"dungeons-and-diffusion-30000",
"elden-ring-v3",
"f222",
"ghibli-v1",
"ha-3dkx-1.1",
"hassanblend-v1.5.1.2",
"inkpunk-v2",
"juggernaut-reborn",
"majicmix-realistic-v7",
"modern-disney-v1",
"multi-style-nitro-diffusion-v1",
"ootd-vton-full-body-v1",
"ootd-vton-upper-body-v1",
"openjourney",
"paper-cut-v1",
"realistic-vision-v5.1",
"redshift-v1",
"rev-animated-v1.22",
"samdoesart-v3",
"seek.art-mega-v1",
"spider-verse-v1",
"super-mario-nation-v2",
"tron-legacy",
"van-gogh-style-lvngvncnt-v2",
"voxelart-v1",
"waifu-diffusion-v1.3",
"sd_v1.5",
"sd_v1.5_inpainting"
],
modes: [
"text2image",
"edit"
],
keys: [
"stable-diffusion-v1"
]
},
{
name: "Stable Diffusion v2",
kind: "family",
scope: "families",
families: [
"v2"
],
models: [
"readshift-768",
"sd_v2.0_depth",
"sd_v2.0_inpainting",
"sd_v2.1",
"sd_v2.1_768_v"
],
modes: [
"text2image"
],
keys: [
"stable-diffusion-v2"
]
},
{
name: "Wan v2.1",
kind: "family",
scope: "families",
families: [
"wan_v2.1_1.3b"
],
models: [
"skyreels-v2-1.3b-i2v-540p",
"wan-2.1-1.3b-fun-inp",
"wan-2.1-1.3b-v1.1-fun-inp",
"wan_v2.1_1.3b_480p"
],
modes: [
"text2video",
"image2video"
],
keys: [
"wan-v2-1"
]
},
{
name: "Wan v2.x",
kind: "family",
scope: "families",
families: [
"wan_v2.1_14b"
],
models: [
"anisora-v3.2-i2v-wan-2.2-a14b-hne",
"anisora-v3.2-i2v-wan-2.2-a14b-lne",
"chronoedit-14b",
"skyreels-v2-14b-i2v-540p",
"skyreels-v2-14b-i2v-720p",
"skyreels-v2-14b-t2v-540p",
"skyreels-v2-14b-t2v-720p",
"wan-2.1-14b-fun-inp",
"wan-2.1-14b-i2v-fusionx",
"wan-2.1-14b-t2v-fusionx",
"wan-2.1-14b-v1.1-fun-inp",
"wan-v2.2-a14b-hne-t2v-lightning-250928",
"wan_v2.1_14b_720p",
"wan_v2.1_14b_i2v_480p",
"wan_v2.1_14b_i2v_720p",
"wan_v2.2_a14b_hne_i2v",
"wan_v2.2_a14b_hne_t2v",
"wan_v2.2_a14b_lne_i2v",
"wan_v2.2_a14b_lne_t2v"
],
modes: [
"text2video",
"image2video"
],
keys: [
"wan-v2-x"
]
},
{
name: "Wan v2.2",
kind: "family",
scope: "families",
families: [
"wan_v2.2_5b"
],
models: [
"wan_v2.2_5b_ti2v"
],
modes: [
"text2video",
"image2video"
],
keys: [
"wan-v2-2"
]
},
{
name: "Stable Cascade (W\xFCrstchen v3.0)",
kind: "family",
scope: "families",
families: [
"wurstchen_v3.0_stage_c"
],
models: [
"stable-cascade"
],
modes: [
"text2image"
],
keys: [
"stable-cascade-w-rstchen-v3-0"
]
},
{
name: "Z Image",
kind: "family",
scope: "families",
families: [
"z_image"
],
models: [
"z-image-1.0-exact",
"z-image-turbo-1.0-exact",
"z_image_1.0",
"z_image_turbo_1.0"
],
modes: [
"text2image",
"image2image"
],
keys: [
"z-image"
]
},
{
name: "MiniMax H3",
kind: "family",
scope: "models",
families: [
"minimax_h3"
],
models: [
"minimax-h3-fl2va"
],
modes: [
"text2video",
"image2video"
],
keys: [
"minimax-h3"
]
},
{
name: "MiniMax H3 [ref2va]",
kind: "family",
scope: "models",
families: [
"minimax_h3"
],
models: [
"minimax-h3-ref2va"
],
modes: [
"text2video",
"image2video"
],
keys: [
"minimax-h3-ref2va"
]
},
{
name: "Qwen Image Edit",
kind: "supplement",
scope: "models",
families: [],
models: [
"qwen_image_edit_2511",
"qwen_image_edit_2509"
],
modes: [
"image2image",
"edit"
],
keys: [
"qwen-image-edit"
]
}
]
};
// src/catalog/modelAliases.manual.json
var modelAliases_manual_default = {
schema: "dtc.model-aliases.manual.v1",
comment: 'Our additions, NOT from public sources. Edited by hand; scripts/build-model-catalog.mjs never writes this file. An entry wins over a generated alias with the same normalized name. `kind`: `spelling` = another spelling or legacy name of something the public catalog already names (the official name is taken from the catalog; no `label` allowed). `supplement` = closes a gap in the public catalog and needs a plain-text `label`, like an official family has. `families` are family tags (ModelZoo `version`), `models` are catalog model ids. `legacy: true` = accepted, but never named in lists or error answers for the agent. `agentNames` overrides the name the agent is told when the official name is unusable or one family must be split: [{ "name": "Wan 2.x", "families": ["wan_v2.1_14b"] }] renames a family, [{ "name": "MiniMax H3", "models": ["minimax-h3-fl2va"] }] names single models (a family with model-level names is described by those names only). By default the official name without a trailing size is used. An entry may list several spellings in `aliases` instead of one `alias`. Spec: draw-things-chat/instructions/development/model-used-family-resolution_v3.md',
agentNames: [
{ name: "MiniMax H3", models: ["minimax-h3-fl2va"], note: "ModelZoo has one family `minimax_h3`; fl2va and ref2va differ functionally, so the agent gets them separately. Other models of the family (FastH3 Omni) stay reachable by name or file." },
{ name: "MiniMax H3 [ref2va]", tag: "minimax_h3_ref2va", models: ["minimax-h3-ref2va"], note: "Our own tag: the overlay is named after it (minimax_h3_ref2vaParamsDrawThings.ts)." }
],
aliases: [
{
alias: "flux",
kind: "spelling",
families: ["flux3_5b", "flux2_9b", "flux2_4b", "flux2"],
legacy: true,
note: "FLUX.3 first, then FLUX.2 klein, then FLUX.2 dev. Excludes flux1 (Chroma and FLUX.1 fine-tunes), which the generated alias would include. Until 2026-11 `flux` meant FLUX.2 [klein] 9B."
},
{
alias: "flux-3-klein",
kind: "spelling",
families: ["flux3_5b"],
legacy: true,
note: "Old preset name."
},
{
alias: "krea2",
kind: "spelling",
families: ["krea_2"],
legacy: true,
note: "Old preset name."
},
{
alias: "qwen-image-2.1-turbo",
kind: "spelling",
models: ["qwen-image-2.1-turbo"],
legacy: true,
note: "Old preset name for the Turbo model of Qwen Image 2.1."
},
{
alias: "qwen-edit",
kind: "supplement",
label: "Qwen Image Edit",
models: ["qwen_image_edit_2511", "qwen_image_edit_2509"],
legacy: true,
note: "Not a family in ModelZoo: Qwen Image Edit is a model of `qwen_image`. Without this entry qwen_image_edit_2511_q6p.ckpt is hard to reach by name."
},
{
aliases: ["minimax", "minimax-h3", "minimax-h3-fl", "minimax-fl", "minimax-fl2va", "minimax-h3-fl2va"],
kind: "spelling",
models: ["minimax-h3-fl2va"],
legacy: true,
note: "MiniMax H3 (first/last-frame variant, fl2va). `minimax` is the old preset name; `minimax-h3` would otherwise mean the whole family."
},
{
aliases: ["minimax-h3-ref", "minimax-ref", "minimax-ref2va", "minimax-h3-ref2va"],
kind: "spelling",
models: ["minimax-h3-ref2va"],
legacy: true,
note: "MiniMax H3 [ref2va] (reference-image variant). `minimax-ref` is the old preset name."
}
]
};
// src/services/modelAliases.ts
var normalizeModelName = (s) => s.toLowerCase().replace(/\.ckpt$/, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
var generated = modelAliases_generated_default;
var manual = modelAliases_manual_default;
var AGENT_NAMES = generated.agentNames;
var manualIndex = null;
var agentIndex = null;
var familyNames = null;
var modelNames = null;
function buildIndexes() {
manualIndex = /* @__PURE__ */ new Map();
for (const a of manual.aliases) {
for (const alias of [a.alias, ...a.aliases ?? []]) {
if (!alias) continue;
manualIndex.set(normalizeModelName(alias), { label: alias, families: a.families ?? [], models: a.models ?? [], legacy: !!a.legacy });
}
}
agentIndex = /* @__PURE__ */ new Map();
familyNames = /* @__PURE__ */ new Map();
modelNames = /* @__PURE__ */ new Map();
for (const e of AGENT_NAMES) {
const byModel = e.scope === "models";
const target2 = { label: e.name, families: byModel ? [] : e.families, models: byModel ? e.models : [], legacy: false, exclusive: true };
for (const key of [normalizeModelName(e.name), ...e.keys]) agentIndex.set(key, target2);
if (byModel) for (const id of e.models) modelNames.set(id, e.name);
else for (const tag of e.families) familyNames.set(tag, e.name);
}
}
function manualAlias(n) {
if (!manualIndex) buildIndexes();
return manualIndex.get(n) ?? null;
}
function agentNameTarget(n) {
if (!agentIndex) buildIndexes();
return agentIndex.get(n) ?? null;
}
function generatedAlias(n) {
const families = generated.aliases[n];
return families?.length ? { label: n, families, models: [], legacy: false } : null;
}
var belongsTo = (t, m) => t.models.includes(m.id) || t.families.includes(m.family);
function familyAgentName(tag) {
if (!familyNames) buildIndexes();
return familyNames.get(tag) ?? null;
}
function agentNameOfModel(m) {
if (!modelNames) buildIndexes();
return modelNames.get(m.id) ?? familyNames.get(m.family);
}
function agentNameOfFamily(tag) {
if (!familyNames) buildIndexes();
return familyNames.get(tag) ?? runtimeCatalog.families[tag]?.label ?? tag;
}
// src/services/customConfigsLoader.ts
import fs4 from "fs";
import path4 from "path";
import os from "os";
var MODE_ALIASES = {
text2image: "txt2img",
t2i: "txt2img",
txt2img: "txt2img",
image2image: "img2img",
i2i: "img2img",
img2img: "img2img",
edit: "edit",
zoom: "zoom",
restore: "restore",
text2video: "txt2vid",
t2v: "txt2vid",
txt2vid: "txt2vid",
image2video: "img2vid",
i2v: "img2vid",
img2vid: "img2vid"
};
var USER_MODE_NAME = {
txt2img: "text2image",
img2img: "image2image",
edit: "edit",
zoom: "zoom",
restore: "restore",
txt2vid: "text2video",
img2vid: "image2video"
};
var cachedPresets = null;
var configFilePath = null;
var didWarnCacheUninitialized = false;
var didLogUsingPreset = /* @__PURE__ */ new Set();
function isVerboseCustomConfigsLoggingEnabled() {
try {
return process?.env?.DTC_CUSTOM_CONFIGS_VERBOSE === "1";
} catch {
return false;
}
}
function getPresetsCacheOrNull() {
if (cachedPresets === null && !configFilePath) {
cachedPresets = /* @__PURE__ */ new Map();
}
return cachedPresets;
}
function getConfiguredCustomConfigsPath() {
return configFilePath;
}
async function checkCustomConfigs(customPath) {
try {
cachedPresets = null;
const rawPath = typeof customPath === "string" ? customPath.trim() : "";
if (!rawPath) {
configFilePath = null;
cachedPresets = /* @__PURE__ */ new Map();
didWarnCacheUninitialized = false;
return {
available: false,
filePath: null
};
}
const expandedPath = rawPath.startsWith("~") ? path4.join(os.homedir(), rawPath.slice(1)) : rawPath;
configFilePath = expandedPath;
didWarnCacheUninitialized = false;
await fs4.promises.access(expandedPath, fs4.constants.R_OK);
return {
available: true,
filePath: expandedPath
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error";
return {
available: false,
filePath: null,
error: errorMessage
};
}
}
async function loadCustomConfigs() {
if (cachedPresets !== null) {
return cachedPresets;
}
const presets = /* @__PURE__ */ new Map();
try {
if (!configFilePath) {
cachedPresets = presets;
return presets;
}
const fileContent = await fs4.promises.readFile(configFilePath, "utf-8");
const rawPresets = JSON.parse(fileContent);
if (!Array.isArray(rawPresets)) {
console.warn(
"[CustomConfigs] Expected array of presets, got:",
typeof rawPresets
);
cachedPresets = presets;
return presets;
}
for (const rawPreset of rawPresets) {
try {
const preset = parsePreset(rawPreset);
if (preset) {
presets.set(preset.name, preset);
}
} catch (error) {
}
}
if (presets.size > 0) {
const presetNames = Array.from(presets.keys()).join(", ");
console.log(
`[CustomConfigs] Loaded ${presets.size} presets: ${presetNames}`
);
} else {
console.log(
`[CustomConfigs] No valid presets found in ${configFilePath}`
);
}
} catch (error) {
console.warn(
"[CustomConfigs] Failed to load custom_configs.json:",
error instanceof Error ? error.message : error
);
}
cachedPresets = presets;
didWarnCacheUninitialized = false;
return presets;
}
function convertParamNames(config) {
const converted = {};
for (const [key, value] of Object.entries(config)) {
const snakeKey = key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase();
if (Array.isArray(value)) {
converted[snakeKey] = value.map(
(item) => typeof item === "object" && item !== null ? convertParamNames(item) : item
);
} else if (typeof value === "object" && value !== null) {
converted[snakeKey] = convertParamNames(value);
} else {
converted[snakeKey] = value;
}
}
return converted;
}
function parsePreset(rawPreset) {
const { name, configuration } = rawPreset;
if (!name || typeof name !== "string") {
console.warn("[CustomConfigs] Preset missing name field");
return null;
}
const dotIdx = name.indexOf(".");
if (dotIdx <= 0 || dotIdx === name.length - 1) {
return null;
}
const modeRaw = name.slice(0, dotIdx);
const modelId = name.slice(dotIdx + 1);
const mode = MODE_ALIASES[modeRaw.trim().toLowerCase()];
if (!mode) {
return null;
}
const convertedConfig = convertParamNames(configuration);
const params = convertedConfig;
return {
// Stored under the spelled-out mode so that lookups work for every accepted spelling.
name: `${USER_MODE_NAME[mode]}.${modelId}`,
mode,
modelId,
params
};
}
function getCustomPreset(notation) {
const cache = getPresetsCacheOrNull();
if (!cache) {
if (!didWarnCacheUninitialized) {
console.warn(
"[CustomConfigs] Cache not initialized, call loadCustomConfigs() first"
);
didWarnCacheUninitialized = true;
}
return null;
}
return cache.get(notation) ?? null;
}
function findCustomPresetsByModelFile(mode, files) {
const cache = getPresetsCacheOrNull();
if (!cache) return [];
const internal = MODE_ALIASES[mode.trim().toLowerCase()] ?? (mode === "inpaint" || mode === "outpaint" ? "edit" : void 0);
if (!internal) return [];
const wanted = new Set([...files].map((f) => path4.basename(f).trim().toLowerCase()));
return [...cache.values()].filter((p) => {
const model = p.params.model;
return p.mode === internal && typeof model === "string" && wanted.has(path4.basename(model).trim().toLowerCase());
}).sort((a, b) => a.modelId.localeCompare(b.modelId));
}
function clearCustomConfigsCache() {
cachedPresets = null;
configFilePath = null;
didWarnCacheUninitialized = false;
didLogUsingPreset = /* @__PURE__ */ new Set();
}
function getEffectiveOverlay(modelId, mode) {
const normalizedModelId = modelId?.trim() ? modelId.trim() : void 0;
const cache = getPresetsCacheOrNull();
if (cache) {
const effectiveModelId = normalizedModelId ? normalizeModelId(normalizedModelId) : "auto";
const notation = buildPresetNotation(mode, effectiveModelId);
const verbose = isVerboseCustomConfigsLoggingEnabled();
if (verbose) {
console.debug(
`[CustomConfigs] getEffectiveOverlay: modelId=${effectiveModelId}, mode=${mode}, notation=${notation}, cacheSize=${cache.size}`
);
}
const familyTag = officialNameFor(effectiveModelId);
const presetNames = [.../* @__PURE__ */ new Set([normalizedModelId ?? effectiveModelId, effectiveModelId, ...legacyNamesOf(effectiveModelId), familyTag])];
let customPreset = null;
for (const name of presetNames) {
customPreset = getCustomPreset(buildPresetNotation(mode, name));
if (customPreset) break;
}
const byFile = !customPreset && normalizedModelId?.toLowerCase().endsWith(".ckpt") ? findCustomPresetsByModelFile(mode, [normalizedModelId])[0] : void 0;
if (byFile) return { source: "custom", presetName: byFile.name, params: byFile.params };
if (customPreset) {
if (verbose && !didLogUsingPreset.has(notation)) {
console.info(`[CustomConfigs] Using custom preset '${notation}'`);
didLogUsingPreset.add(notation);
}
return {
source: "custom",
presetName: customPreset.name,
params: customPreset.params
};
} else {
if (verbose) {
console.debug(
`[CustomConfigs] Custom preset '${notation}' not found, falling back to model overlay`
);
}
}
} else {
if (configFilePath && !didWarnCacheUninitialized) {
console.warn(
`[CustomConfigs] cachedPresets is null (loadCustomConfigs() was not called or failed)`
);
didWarnCacheUninitialized = true;
}
}
const isPreset = !!normalizedModelId && MODEL_IDS.includes(normalizeModelId(normalizedModelId));
let overlayId = normalizedModelId;
if (normalizedModelId && !isPreset && normalizedModelId !== "auto" && mode !== "zoom" && mode !== "restore") {
const tunedId = normalizedModelId.toLowerCase().endsWith(".ckpt") ? MODEL_IDS.find((id) => id !== "auto" && id !== "custom" && getModelOverlay(id, mode)?.model === normalizedModelId) : void 0;
if (tunedId) overlayId = tunedId;
else {
const fromCatalog = catalogOverlayFor(normalizedModelId, peekInventory());
if (fromCatalog) return { source: "catalog", note: fromCatalog.note, params: fromCatalog.params };
}
}
const modelOverlay = getModelOverlay(overlayId, mode);
if (modelOverlay) {
const tuned = withInstalledPrecision(modelOverlay, peekInventory());
const fallback = loraFallbackOverlay(tuned, peekInventory());
if (fallback) return { source: "recommended", note: fallback.note, params: fallback.params };
return {
source: "modelOverlay",
params: tuned
};
}
return {
source: "default",
params: null
};
}
function buildPresetNotation(mode, modelId) {
return `${USER_MODE_NAME[mode]}.${modelId}`;
}
function getAvailableCustomCombinations() {
const cache = getPresetsCacheOrNull();
if (!cache) return [];
const combinations = [];
for (const preset of cache.values()) {
if (preset.mode === "zoom" || preset.mode === "restore") continue;
combinations.push([USER_MODE_NAME[preset.mode], preset.modelId]);
}
return combinations;
}
function getCustomPresetLabelsUsingModelFilename(modelFilenameOrPath) {
const cache = getPresetsCacheOrNull();
if (!cache) return [];
if (typeof modelFilenameOrPath !== "string") return [];
const wanted = path4.basename(modelFilenameOrPath).trim().toLowerCase();
if (!wanted) return [];
const labels = /* @__PURE__ */ new Set();
for (const preset of cache.values()) {
const presetModel = preset.params?.model;
if (typeof presetModel !== "string") continue;
const presetBase = path4.basename(presetModel).trim().toLowerCase();
if (presetBase === wanted) {
labels.add(preset.name);
}
}
return Array.from(labels).sort();
}
// src/services/image2imagePolicy.ts
var isImage2ImageMode = (mode) => mode === "image2image" || mode === "img2img";
function image2imagePresetOf(model, inv, onlyFile) {
const user = findCustomPresetsByModelFile("image2image", onlyFile ? [onlyFile] : model.installedFiles)[0];
if (user) return { kind: "user", preset: user };
const ours = tunedPresetFor(model.id, "image2image", inv, onlyFile);
return ours ? { kind: "ours", preset: ours } : null;
}
function listImage2ImageModels(inv) {
return inv.installed.filter((m) => m.ready && !m.deprecated && m.rubric !== "uncurated" && image2imagePresetOf(m, inv));
}
function image2imageAlternatives(inv) {
const names = [...new Set(listImage2ImageModels(inv).map((m) => m.name))].slice(0, 5);
return names.length ? `image2image is available for: ${names.join(", ")}.` : "No installed model has an image2image preset.";
}
function image2imageUnavailable(subject, inv) {
return `${subject} has no image2image preset (a preset with a tuned strength). ${image2imageAlternatives(inv)}`;
}
// src/services/agentNames.ts
var AGENT_MODE_ORDER = ["text2image", "image2image", "edit", "text2video", "image2video"];
function installedAgentNames(inv, mode) {
const byName = /* @__PURE__ */ new Map();
for (const m of [...inv.installed].sort((a, b) => a.rank - b.rank)) {
if (!m.ready || m.deprecated || m.rubric === "uncurated") continue;
const kind = runtimeCatalog.families[m.family]?.kind;
if (kind === "upscaler") continue;
const name = agentNameOfModel(m);
if (!name) continue;
const entryOf = (n) => byName.get(n) ?? byName.set(n, { kind: kind === "video" ? "video" : "image", modes: /* @__PURE__ */ new Set() }).get(n);
const own = entryOf(name);
m.modes.forEach((x) => x !== "image2image" && own.modes.add(x));
if (image2imagePresetOf(m, inv)) own.modes.add("image2image");
const familyName = familyAgentName(m.family);
if (familyName && familyName !== name) {
const fam = entryOf(familyName);
for (const x of AGENT_MODE_ORDER) if (x === "image2image" ? image2imagePresetOf(m, inv) : tunedPresetFor(m.id, x, inv)) fam.modes.add(x);
}
}
const wanted = mode === "inpaint" || mode === "outpaint" ? "edit" : mode;
return [...byName].map(([name, e]) => ({ name, kind: e.kind, modes: AGENT_MODE_ORDER.filter((x) => e.modes.has(x)) })).filter((e) => e.modes.length > 0 && (!wanted || e.modes.includes(wanted))).sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === "image" ? -1 : 1);
}
// src/services/modelInventoryRuntime.ts
var fetcher = null;
var provider = null;
function snapshotPath() {
try {
return path5.join(getProjectRoot(), "logs", "model-inventory.json");
} catch {
return void 0;
}
}
function getProvider() {
provider ??= createInventoryProvider({
fetchEcho: () => fetcher ? fetcher() : Promise.reject(new Error("no echo fetcher registered")),
snapshotPath: snapshotPath()
});
return provider;
}
function registerInventoryFetcher(fn) {
fetcher = fn;
}
function primeInventoryFromEcho(echoResponse, durationMs = 0) {
try {
return getProvider().prime(parseEchoResponse(echoResponse), durationMs);
} catch {
return null;
}
}
function echoFetcherForClient(client, clientName2, sharedSecret) {
return () => new Promise((resolve, reject) => {
const echo = client?.echo?.bind(client);
if (typeof echo !== "function") return reject(new Error("client has no echo"));
const req = { name: clientName2 };
if (sharedSecret) req.sharedSecret = sharedSecret;
echo(req, (err, resp) => err ? reject(err) : resolve(parseEchoResponse(resp)));
});
}
function peekInventory() {
return provider ? provider.peek() : null;
}
async function currentInventory() {
try {
return (await getProvider().get()).inventory;
} catch {
return null;
}
}
var OVERLAY_MODE2 = {
text2image: "txt2img",
image2image: "img2img",
edit: "edit",
inpaint: "edit",
outpaint: "edit",
text2video: "txt2vid",
image2video: "img2vid"
};
function presetAvailability(inv, mode) {
const overlayMode = OVERLAY_MODE2[mode];
const out = { usable: [], degraded: [], unusable: [] };
if (!overlayMode) return out;
for (const id of MODEL_IDS) {
if (id === "auto" || id === "custom") continue;
const wanted = getModelFilename(id, overlayMode);
if (!wanted) continue;
const file = installedFileOf(wanted, inv).file;
const state = stateOfFile(inv, file);
const ready = state.state === "ready" || state.state === "custom" && state.model.ready;
const missingLoras = getModelRequiredFiles(id, overlayMode).filter((f) => f !== wanted && !inv.files.has(f));
if (ready && !missingLoras.length) out.usable.push(id);
else if (ready && loraFallbackOverlay(withInstalledPrecision(getModelOverlay(id, overlayMode), inv), inv)) {
out.degraded.push({ preset: id, reason: `LoRA '${missingLoras[0]}' is not installed, so the slower recommended settings apply` });
} else out.unusable.push({ preset: id, reason: ready ? `LoRA '${missingLoras[0]}' is not installed` : explainFile(inv, file) });
}
return out;
}
var unique = (list) => [...new Set(list)];
function agentNameOfPreset(preset) {
for (const mode of ["txt2img", "edit", "txt2vid", "img2vid", "img2img"]) {
const file = getModelFilename(preset, mode);
const model = file ? catalogModelOfFile(file) : void 0;
const name = model && agentNameOfModel(model);
if (name) return name;
}
return agentNameOfFamily(officialNameFor(preset));
}
var firstPerName = (list) => {
const byName = /* @__PURE__ */ new Map();
for (const u of list) if (!byName.has(agentNameOfPreset(u.preset))) byName.set(agentNameOfPreset(u.preset), u.reason.replace(/\.$/, ""));
return [...byName].map(([name, reason]) => `${name} (${reason})`);
};
function formatModelHint(inv, mode) {
const { usable, degraded, unusable } = presetAvailability(inv, mode);
const usableNames = installedAgentNames(inv, mode).map((e) => e.name);
const lines = [
usableNames.length ? `Models usable on this machine for mode '${mode}': ${usableNames.join(", ")}.` : `No model is usable on this machine for mode '${mode}'.`
];
const usableTuned = new Set(usable.map(agentNameOfPreset));
const slower = degraded.filter((d) => !usableTuned.has(agentNameOfPreset(d.preset)));
if (slower.length) lines.push(`Slower than tuned: ${firstPerName(slower).join("; ")}.`);
const known = /* @__PURE__ */ new Set([...usableNames, ...usableTuned, ...degraded.map((d) => agentNameOfPreset(d.preset))]);
const blocked = unusable.filter((u) => !known.has(agentNameOfPreset(u.preset)));
if (blocked.length) lines.push(`Not usable here: ${firstPerName(blocked).join("; ")}.`);
return lines.join("\n");
}
async function appendModelHint(message, mode) {
try {
const inv = await currentInventory();
return inv ? `${message}
${formatModelHint(inv, mode)}` : message;
} catch {
return message;
}
}
async function listUsablePresets(mode) {
try {
const inv = await currentInventory();
if (!inv) return null;
const a = presetAvailability(inv, mode);
return unique([...a.usable, ...a.degraded.map((d) => d.preset)].map(officialNameFor));
} catch {
return null;
}
}
async function explainRequiredFile(file) {
try {
const inv = await currentInventory();
return inv ? explainFile(inv, file) : null;
} catch {
return null;
}
}
function hasInventoryFetcher() {
return fetcher !== null;
}
// src/services/modelResolver.ts
var PRECISION_RE = /_(bf16_q8p|bf16|f16|f32|q8p|q6p|q5p|q4p|i8x|i6x|i5x|i4x|i3x)(_svd)?\.ckpt$/;
var fileOf = (i) => runtimeCatalog.files[i];
var precisionOf = (file) => PRECISION_RE.exec(file)?.[1] ?? null;
function precisionFromHint(hint) {
const h = hint.toLowerCase();
const bits = /(\d)\s*-?\s*bit(\s*s\b)?/.exec(h);
if (bits) return bits[2] ? `i${bits[1]}x` : `q${bits[1]}p`;
if (/exact|f16/.test(h)) return "f16";
if (/f32/.test(h)) return "f32";
if (/bf16/.test(h)) return "bf16";
return null;
}
var index = null;
function getIndex() {
if (index) return index;
const idx = { tags: /* @__PURE__ */ new Map(), labels: /* @__PURE__ */ new Map(), files: /* @__PURE__ */ new Map(), names: /* @__PURE__ */ new Map(), ids: /* @__PURE__ */ new Map() };
for (const [tag, fam] of Object.entries(runtimeCatalog.families)) {
idx.tags.set(normalizeModelName(tag), tag);
if (fam.label) idx.labels.set(normalizeModelName(fam.label), tag);
}
for (const m of runtimeCatalog.models) {
idx.ids.set(normalizeModelName(m.id), m);
const key = normalizeModelName(m.name);
idx.names.set(key, [...idx.names.get(key) ?? [], m]);
for (const [i] of m.files) idx.files.set(normalizeModelName(fileOf(i)), { model: m, file: fileOf(i) });
}
index = idx;
return idx;
}
function isPresetName(name) {
return name === "auto" || name === "custom" || isLegacyPresetName(name);
}
function kindMismatch(model, mode) {
const kind = runtimeCatalog.families[model.family]?.kind;
const videoMode = mode === "text2video" || mode === "image2video";
return kind === "upscaler" || videoMode !== (kind === "video");
}
function modeProblem(model, mode) {
if (kindMismatch(model, mode) || !model.modesUncertain && !supportsMode(model.modes, mode)) {
return `Model '${model.name}' does not support mode '${mode}'. Supported modes for this model: ${model.modes.join(", ")}.`;
}
return null;
}
function userPresetFor(mode, files, prefer) {
const hits = findCustomPresetsByModelFile(mode, files);
if (!hits.length) return null;
const preferred = new Set(prefer.map(normalizeModelName));
const official = (p) => preferred.has(normalizeModelName(p.modelId)) || isPresetName(p.modelId) || !!runtimeCatalog.families[p.modelId];
return hits.find(official) ?? hits[0];
}
var userPresetNote = (p) => `Using your preset '${p.name}' (${p.params.model}).`;
function tunedPresetWithoutHijack(preset, mode) {
return preset && [preset, ...legacyNamesOf(preset)].some((name) => getCustomPreset(`${mode}.${name}`)) ? null : preset;
}
function alternativesOf(name, mode, inv) {
if (!name) return "";
const files = inv.installed.filter((m) => m.ready && agentNameOfModel(m) === name && supportsMode(m.modes, mode)).flatMap((m) => m.installedFiles);
return files.length ? ` Installed for '${name}' (mode '${mode}'): ${files.join(", ")}.` : ` Nothing is installed for '${name}' in mode '${mode}'.`;
}
function concrete(model, requestedFile, precision, mode, inv) {
const problem = modeProblem(model, mode);
if (problem) return { ok: false, reason: problem };
const modelFiles = model.files.map(([i]) => fileOf(i));
if (!inv) return { ok: true, passAs: requestedFile ?? modelFiles.find((f) => !precision || precisionOf(f)?.startsWith(precision)) ?? modelFiles[0] };
const installed = inv.installed.find((m) => m.id === model.id);
if (!installed) return { ok: false, reason: `Model '${model.name}' is not installed.${alternativesOf(agentNameOfModel(model), mode, inv)}` };
if (!installed.ready) return { ok: false, reason: explainFile(inv, installed.file) };
const wanted = requestedFile ?? (precision ? installed.installedFiles.find((f) => precisionOf(f)?.startsWith(precision)) : void 0);
if (requestedFile && !installed.installedFiles.includes(requestedFile)) {
return { ok: false, reason: explainFile(inv, requestedFile) };
}
if (precision && !wanted) {
return { ok: false, reason: `'${model.name}' is not installed in precision '${precision}'. Installed: ${installed.installedFiles.join(", ")}.` };
}
const file = wanted ?? installed.file;
const mine = userPresetFor(mode, wanted ? [wanted] : installed.installedFiles, [model.id, model.family]);
if (mine) return { ok: true, passAs: mine.modelId, note: userPresetNote(mine) };
const preset = tunedPresetWithoutHijack(tunedPresetFor(model.id, mode, inv, wanted), mode);
if (isImage2ImageMode(mode) && !preset) return { ok: false, reason: image2imageUnavailable(`'${requestedFile ?? model.name}'`, inv) };
return { ok: true, passAs: preset ?? file };
}
function supportedModesOf(belongs, display, inv) {
const modes = new Set(inv.installed.filter((m) => m.ready && belongs(m)).flatMap((m) => m.modes));
return modes.size ? ` Installed models of '${display}' support: ${[...modes].join(", ")}.` : ` Nothing is installed for '${display}'.`;
}
function group(display, belongs, mode, inv) {
if (!inv) return { ok: false, reason: `'${display}' can only be resolved against the server's installed models, which are not available.` };
const pick = pickFallbackModel(inv, mode, { accept: (m) => belongs(m) && (!isImage2ImageMode(mode) || !!image2imagePresetOf(m, inv)) });
if (!pick) {
return { ok: false, reason: isImage2ImageMode(mode) ? `'${display}' has no installed model with an image2image preset (a preset with a tuned strength). ${image2imageAlternatives(inv)}` : `No installed model of '${display}' supports mode '${mode}'.${supportedModesOf(belongs, display, inv)}` };
}
const tag = pick.model.family;
const mine = userPresetFor(mode, pick.model.installedFiles, [pick.model.id, tag]);
if (mine) return { ok: true, passAs: mine.modelId, familyTag: tag, note: `'${display}': ${userPresetNote(mine)}` };
const preset = tunedPresetWithoutHijack(tunedPresetFor(pick.model.id, mode, inv), mode);
if (isImage2ImageMode(mode) && !preset) return { ok: false, reason: image2imageUnavailable(`'${pick.model.name}'`, inv) };
return {
ok: true,
passAs: preset ?? pick.model.file,
familyTag: tag,
note: `'${display}' resolved to '${pick.model.name}' (${preset ? `preset ${preset}` : pick.model.file}).`
};
}
var family = (tag, mode, inv) => group(tag, (m) => m.family === tag, mode, inv);
var target = (t, display, mode, inv) => group(display, (m) => belongsTo(t, m) && (!t.exclusive || agentNameOfModel(m) === t.label || !!inv && !!tunedPresetFor(m.id, mode, inv)), mode, inv);
function resolveModelArgument(input, mode, inv) {
const raw = input.trim();
if (!raw || raw === "auto" || raw === "custom") return null;
const idx = getIndex();
const n = normalizeModelName(raw);
const byFile = idx.files.get(n);
if (byFile) return concrete(byFile.model, byFile.file, null, mode, inv);
const named = manualAlias(n) ?? agentNameTarget(n);
if (named) return target(named, agentNameTarget(n)?.label ?? raw, mode, inv);
let nameHits = idx.names.get(n);
let precision = null;
if (!nameHits) {
const m = /^(.*?)\s*\(([^()]*)\)\s*$/.exec(raw);
if (m) {
precision = precisionFromHint(m[2]);
nameHits = precision ? idx.names.get(normalizeModelName(m[1])) : void 0;
}
}
if (nameHits) {
if (nameHits.length > 1) return { ok: false, reason: `'${raw}' is ambiguous: ${nameHits.map((m) => m.name).join(", ")}.` };
return concrete(nameHits[0], void 0, precision, mode, inv);
}
const byId = idx.ids.get(n);
if (byId) return concrete(byId, void 0, null, mode, inv);
const custom = inv && [...inv.customByFile.values()].filter((c) => normalizeModelName(c.name) === n || normalizeModelName(c.file) === n);
if (custom && custom.length > 1) return { ok: false, reason: `'${raw}' is ambiguous among custom models: ${custom.map((c) => c.file).join(", ")}.` };
if (custom?.length) {
const c = custom[0];
return c.ready ? { ok: true, passAs: c.file, note: `Custom model '${c.name}' (${c.family}): no curated settings, engine defaults apply.` } : { ok: false, reason: explainFile(inv, c.file) };
}
const tag = idx.tags.get(n);
if (tag) return family(tag, mode, inv);
const label = idx.labels.get(n);
if (label) return family(label, mode, inv);
const prefix = generatedAlias(n);
return prefix ? target(prefix, raw, mode, inv) : lookalike(raw, mode, inv);
}
var LOOSE_PRECISION_RE = new RegExp(PRECISION_RE.source.replace("\\.ckpt$", "(?:\\.ckpt)?$"));
function lookalike(raw, mode, inv) {
const stem = normalizeModelName(raw.replace(/\s*\([^()]*\)\s*$/, "").replace(LOOSE_PRECISION_RE, ""));
if (stem.length < 5) return null;
const names = /* @__PURE__ */ new Set();
for (const m of runtimeCatalog.models) {
const keys = [m.name, m.id, ...m.files.map(([i]) => fileOf(i).replace(PRECISION_RE, ""))].map(normalizeModelName);
const name = keys.some((k) => k === stem || k.startsWith(`${stem}-`)) ? agentNameOfModel(m) : void 0;
if (name) names.add(name);
}
if (!names.size) return null;
const parts = [...names].map((name) => {
const files = inv?.installed.filter((m) => m.ready && agentNameOfModel(m) === name && supportsMode(m.modes, mode)).flatMap((m) => m.installedFiles) ?? [];
return files.length ? `${name} (installed for mode '${mode}': ${files.join(", ")})` : `${name} (nothing installed for mode '${mode}')`;
});
return { ok: false, reason: `'${raw}' is not a known model. It looks like: ${parts.join("; ")}. Use the name to get the best installed variant, or one of the listed files.` };
}
async function resolveRequestedModel(name, mode) {
try {
const r = resolveModelArgument(name, mode, await currentInventory());
if (!r) return null;
return r.ok ? { modelId: r.passAs, familyTag: r.familyTag, note: r.note } : { error: r.reason };
} catch {
return null;
}
}
// src/capabilities.ts
var cachedSelfPluginIdentifier;
function getSelfPluginIdentifier() {
if (cachedSelfPluginIdentifier !== void 0)
return cachedSelfPluginIdentifier;
try {
const pluginIdentifier = getPluginMeta().pluginIdentifier;
if (pluginIdentifier && pluginIdentifier !== "unknown") {
cachedSelfPluginIdentifier = pluginIdentifier;
return cachedSelfPluginIdentifier;
}
} catch (err) {
console.warn(
"[Capabilities] Failed to resolve pluginIdentifier from manifest.json.",
err
);
cachedSelfPluginIdentifier = null;
return cachedSelfPluginIdentifier;
}
console.warn(
"[Capabilities] manifest.json did not contain valid owner/name."
);
cachedSelfPluginIdentifier = null;
return cachedSelfPluginIdentifier;
}
var MEDIA_HARVESTING_CONFIG = {
/**
* Attachments: User-uploaded files.
* allow: "all" because LM Studio controls the source.
* SSOT Location: User-Turns → message.files[]
*/
attachment: {
allow: "all"
},
/**
* Variants: Our own generate_image outputs.
* allow: "all" because we control the source (ourselves).
*/
variant: {
allow: "all"
// Implicitly: only our own plugin via getSelfPluginIdentifier()
},
/**
* Images: 3rd-party image generators.
* allow: "all" because LM Studio is the gatekeeper:
* If base64 arrives and gets decoded to ChatWd, we trust it.
*/
image: {
allow: "all"
// Universal: any tool that delivers base64/filename
},
/**
* Pictures: External URLs from web searches.
* allow: "only" because extraction logic is tool-specific
* (Brave JSON structure ≠Google JSON structure ≠...).
*/
picture: {
allow: "only",
tools: {
"mcp/brave-search-mcp": ["brave_image_search"],
// NUR brave_image_search
"ceveyne/draw-things-index": ["index_image"],
"ceveyne/find-image": ["find_image"]
// Add new picture tools here...
}
}
};
function isToolAllowlistedForMediaType(mediaType, pluginIdentifier, toolName2) {
const config = MEDIA_HARVESTING_CONFIG[mediaType];
if (config.allow === "all") {
return true;
}
const tools = config.tools[pluginIdentifier];
if (!tools) return false;
return tools.includes(toolName2);
}
function getMediaTypeForTool(pluginIdentifier, toolName2) {
if (isToolAllowlistedForMediaType("picture", pluginIdentifier, toolName2)) {
return "picture";
}
const selfPlugin2 = getSelfPluginIdentifier();
if (selfPlugin2 && pluginIdentifier === selfPlugin2) {
return "variant";
}
return "image";
}
function isAllowlistedSsotToolCall(input) {
const name = input?.name;
const pluginIdentifier = input?.pluginIdentifier;
if (typeof pluginIdentifier !== "string" || !pluginIdentifier.trim()) {
return false;
}
if (typeof name !== "string" || !name.trim()) {
return false;
}
return getMediaTypeForTool(pluginIdentifier, name) !== void 0;
}
var CAPABILITY_MAP = {
// Local LM Studio Models (Orchestrator/Agent)
"google/gemma-4-26b-a4b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<|channel>thought",
endString: "<channel|>"
},
requiresEnableThinkingFlag: false
},
supportsStreaming: true
},
"google/gemma-4-31b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<|channel>thought",
endString: "<channel|>"
},
requiresEnableThinkingFlag: false
},
supportsStreaming: true
},
"google/gemma-4-26b-a4b-it": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<|channel>thought",
endString: "<channel|>"
},
requiresEnableThinkingFlag: false
},
supportsStreaming: true
},
"google/gemma-4-31b-it": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<|channel>thought",
endString: "<channel|>"
},
requiresEnableThinkingFlag: false
},
supportsStreaming: true
},
"google/gemma-4-12b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: false,
supportsStreaming: true
},
"qwen/qwen3.6-35b-a3b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<think>",
endString: "</think>"
},
// Qwen3.6 does NOT support the /think soft-switch of Qwen3.
// The Jinja template opens <think> by default, but only if
// `enable_thinking` is NOT explicitly set to false.
// To be safe and explicit, we always send the flag as true.
requiresEnableThinkingFlag: true
},
supportsStreaming: true
},
"qwen/qwen3.5-35b-a3b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<think>",
endString: "</think>"
},
// Qwen3.5 does NOT support the /think soft-switch of Qwen3.
// The Jinja template opens <think> by default, but only if
// `enable_thinking` is NOT explicitly set to false.
// To be safe and explicit, we always send the flag as true.
requiresEnableThinkingFlag: true
},
supportsStreaming: true
},
"qwen/qwen3.8-27b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<think>",
endString: "</think>"
},
requiresEnableThinkingFlag: true
},
supportsStreaming: true
},
"qwen/qwen3.6-27b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<think>",
endString: "</think>"
},
requiresEnableThinkingFlag: true
},
supportsStreaming: true
},
"qwen/qwen3.5-27b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<think>",
endString: "</think>"
},
requiresEnableThinkingFlag: true
},
supportsStreaming: true
},
"qwen/qwen3.5-9b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<think>",
endString: "</think>"
},
requiresEnableThinkingFlag: true
},
supportsStreaming: true
},
"qwen/qwen3-vl-30b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: false,
supportsStreaming: true
},
"google/gemma-3-27b": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: false,
supportsStreaming: true
},
"mistralai/magistral-small-2509": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "[THINK]",
endString: "[/THINK]"
}
},
supportsStreaming: true
},
"mistralai/devstral-small-2-2512": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<think>",
endString: "</think>"
}
},
supportsStreaming: true
},
"zai-org/glm-4.6v-flash": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: true,
// Spontaneous <think>...</think> reasoning
thinking: {
levels: [],
// No explicit levels, model decides spontaneously
defaultLevel: "",
reasoningSectionParsing: {
enabled: true,
startString: "<think>",
endString: "</think>"
}
},
supportsStreaming: true
},
// OpenAI API (https://api.openai.com/v1)
"openai/gpt-5.5": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: false,
// Reasoning is internal, not exposed as stream tokens
supportsStreaming: true
},
// Anthropic API via OpenAI-compatible endpoint (no Anthropic SDK)
// Extended thinking tokens are not surfaced through the OpenAI-compatible layer.
"anthropic/claude-sonnet-4-6": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: false,
supportsStreaming: true
},
"anthropic/claude-opus-4-7": {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: false,
supportsStreaming: true
}
};
var CAPABILITY_SUBSTRING_ALIASES = {
"qwen36-27b": "qwen/qwen3.6-27b",
"qwen36-35b": "qwen/qwen3.6-35b-a3b"
};
var DEFAULT_CAPABILITIES = {
supportsTools: true,
supportsVision: true,
supportsImage: false,
supportsThinking: false,
supportsStreaming: true
};
function stripPublisher(modelId) {
const idx = modelId.indexOf("/");
return idx >= 0 ? modelId.slice(idx + 1) : modelId;
}
function detectCapabilities(modelId) {
const input = (modelId || "").trim();
const inputLower = input.toLowerCase();
const inputStripped = stripPublisher(input).toLowerCase();
if (CAPABILITY_MAP[input]) {
return CAPABILITY_MAP[input];
}
for (const key of Object.keys(CAPABILITY_MAP)) {
if (key.toLowerCase() === inputLower) {
return CAPABILITY_MAP[key];
}
}
for (const key of Object.keys(CAPABILITY_MAP)) {
const keyStripped = stripPublisher(key).toLowerCase();
if (keyStripped === inputStripped) {
return CAPABILITY_MAP[key];
}
}
for (const key of Object.keys(CAPABILITY_MAP)) {
const keyStripped = stripPublisher(key).toLowerCase();
if (inputStripped.startsWith(keyStripped + "-")) {
return CAPABILITY_MAP[key];
}
}
for (const [alias, targetKey] of Object.entries(CAPABILITY_SUBSTRING_ALIASES)) {
if (inputStripped.includes(alias) && CAPABILITY_MAP[targetKey]) {
return CAPABILITY_MAP[targetKey];
}
}
console.warn(`[Capabilities] Unknown model ID "${modelId}", using defaults.`);
return DEFAULT_CAPABILITIES;
}
function isKnownModel(modelId) {
const input = (modelId || "").trim();
const inputLower = input.toLowerCase();
const inputStripped = stripPublisher(input).toLowerCase();
if (CAPABILITY_MAP[input]) return true;
for (const key of Object.keys(CAPABILITY_MAP)) {
if (key.toLowerCase() === inputLower) return true;
}
for (const key of Object.keys(CAPABILITY_MAP)) {
if (stripPublisher(key).toLowerCase() === inputStripped) return true;
}
for (const key of Object.keys(CAPABILITY_MAP)) {
if (inputStripped.startsWith(stripPublisher(key).toLowerCase() + "-")) return true;
}
for (const [alias, targetKey] of Object.entries(CAPABILITY_SUBSTRING_ALIASES)) {
if (inputStripped.includes(alias) && CAPABILITY_MAP[targetKey]) return true;
}
return false;
}
function shouldUseFilesApiForModel(modelId, userToggle) {
if (!userToggle) return false;
return true;
}
var PROMPT_UPSAMPLING_MODEL_FAMILIES = {
"flux-3-image-klein-pup": {
contextLength: 16384,
ggufVariant: "UD-Q4_K_XL",
knownModels: [
"flux-3-image-klein-pup",
"unsloth/flux-3-image-klein-pup",
"lmstudio-community/flux-3-image-klein-pup",
"mlx-community/flux-3-image-klein-pup-8bit",
"unsloth/flux-3-image-klein-pup-GGUF"
]
}
};
var CAPABILITY_ENTRIES = {
// IMPORTANT: keys are Draw Things model filenames without extension,
// using hyphens instead of underscores, and without quantization suffix.
"z-image-turbo-1.0": {
modelFilenames: [
"z_image_turbo_1.0_q8p.ckpt",
"z_image_turbo_1.0_q6p.ckpt",
"z_image_turbo_1.0_i8x.ckpt"
]
},
"z-image-1.0": {
modelFilenames: [
"z_image_1.0_q8p.ckpt",
"z_image_1.0_q6p.ckpt",
"z_image_1.0_i8x.ckpt"
]
},
"krea-2-turbo": {
modelFilenames: [
"krea_2_turbo_i8x.ckpt",
"krea_2_turbo_i6x.ckpt",
"krea_2_turbo_q8p.ckpt",
"krea_2_turbo_q6p.ckpt"
]
},
"krea-2-raw": {
modelFilenames: [
"krea_2_raw_i8x.ckpt",
"krea_2_raw_q8p.ckpt",
"krea_2_raw_q6p.ckpt"
]
},
"qwen-image-1.0": {
modelFilenames: [
// Legacy / stable names
"qwen_image_1.0_q8p.ckpt",
"qwen_image_1.0_q6p.ckpt",
// Current Draw Things builds
"qwen_image_2512_bf16_q8p.ckpt",
"qwen_image_2512_bf16_q6p.ckpt",
"qwen_image_2512_i8x.ckpt",
"qwen_image_2512_bf16_i8x.ckpt",
// Edit models (used by defaults/overlays depending on mode and version)
"qwen_image_edit_2509_q8p.ckpt",
"qwen_image_edit_2509_q6p.ckpt",
"qwen_image_edit_2511_q8p.ckpt",
"qwen_image_edit_2511_q6p.ckpt"
]
},
// Unified qwen-edit preset (covers both 2509 and 2511 edit models)
"qwen-edit": {
modelFilenames: [
"qwen_image_edit_2509_q6p.ckpt",
"qwen_image_edit_2511_q6p.ckpt",
"qwen_image_edit_2511_i8x.ckpt",
"qwen_image_edit_2511_bf16_i8x.ckpt"
]
},
"qwen-image-edit-2509": {
modelFilenames: ["qwen_image_edit_2509_q6p.ckpt"]
},
"qwen-image-edit-2511": {
modelFilenames: [
"qwen_image_edit_2511_q6p.ckpt",
"qwen_image_edit_2511_i8x.ckpt",
"qwen_image_edit_2511_bf16_i8x.ckpt"
]
},
"flux-1-schnell": {
modelFilenames: ["flux_1_schnell_q8p.ckpt"]
},
"flux-2-klein": {
modelFilenames: [
// Common variants
"flux_2_klein_9b_q6p.ckpt",
"flux_2_klein_9b_q8p.ckpt",
"flux_2_klein_9b_kv_q6p.ckpt",
"flux_2_klein_9b_kv_q8p.ckpt",
"flux_2_klein_base_9b_q8p.ckpt",
// Seen in logs for custom presets (still in the Flux family)
"flux_2_dev_q6p.ckpt",
// 4B variants
"flux_2_klein_4b_i8x.ckpt",
"flux_2_klein_base_4b_i8x.ckpt"
]
},
// FLUX.3 [klein] 5.6B
"flux-3-klein": {
promptUpsampling: { promptUpsamplingModelFamily: "flux-3-image-klein-pup", maxImages: 10 },
modelFilenames: [
// Distilled (default: q8p; currently used: f16 "Exact")
"flux_3_klein_q8p.ckpt",
"flux_3_klein_f16.ckpt",
"flux_3_klein_i8x.ckpt",
"flux_3_klein_i4x.ckpt",
// Base (undistilled)
"flux_3_klein_base_q8p.ckpt",
"flux_3_klein_base_f16.ckpt",
"flux_3_klein_base_i8x.ckpt",
"flux_3_klein_base_i4x.ckpt"
]
},
"ltx-2-distilled": {
video: {
defaultFps: 25,
audioSampleRate: 24e3
},
// ModelZoo: framesPerSecondForModel(.ltx2) = 25, audioSampleRateForModel(.ltx2) = 24 000
modelFilenames: [
"ltx_2_19b_distilled_q6p.ckpt",
"ltx_2_19b_distilled_q8p.ckpt"
]
},
"ltx-2-dev": {
video: {
defaultFps: 25,
audioSampleRate: 24e3
},
// ModelZoo: framesPerSecondForModel(.ltx2) = 25, audioSampleRateForModel(.ltx2) = 24 000
modelFilenames: [
"ltx_2_19b_dev_q6p.ckpt",
"ltx_2_19b_dev_q8p.ckpt"
]
},
"ltx-2.3-distilled": {
video: {
defaultFps: 25,
audioSampleRate: 48e3
},
// ModelZoo: framesPerSecondForModel(.ltx2_3) = 25, audioSampleRateForModel(.ltx2_3) = 48 000
modelFilenames: [
"ltx_2.3_22b_distilled_q6p.ckpt",
"ltx_2.3_22b_distilled_q8p.ckpt",
"ltx_2.3_22b_distilled_1.1_q6p.ckpt",
"ltx_2.3_22b_distilled_1.1_q8p.ckpt",
"ltx_2.3_22b_distilled_i8x.ckpt",
"ltx_2.3_22b_distilled_1.1_i8x.ckpt"
]
},
"ltx-2.3-dev": {
video: {
defaultFps: 25,
audioSampleRate: 48e3
},
// ModelZoo: framesPerSecondForModel(.ltx2_3) = 25, audioSampleRateForModel(.ltx2_3) = 48 000
modelFilenames: [
"ltx_2.3_22b_dev_q6p.ckpt",
"ltx_2.3_22b_dev_q8p.ckpt",
"ltx_2.3_22b_dev_i8x.ckpt"
]
},
"seedvr2-7b": {
modelFilenames: [
"seedvr2_7b_q8p.ckpt",
"seedvr2_7b_q6p.ckpt"
]
},
"qwen-image-2.1": {
modelFilenames: [
"qwen_image_2.1_q8p.ckpt",
"qwen_image_2.1_q6p.ckpt",
"qwen_image_2.1_i8x.ckpt",
"qwen_image_2.1_i4x.ckpt"
]
},
"qwen-image-2.1-turbo": {
modelFilenames: [
"qwen_image_2.1_turbo_q8p.ckpt",
"qwen_image_2.1_turbo_q6p.ckpt",
"qwen_image_2.1_turbo_i8x.ckpt",
"qwen_image_2.1_turbo_i4x.ckpt"
]
},
// MiniMax H3 (first/last-frame-conditioned): canvas = first frame, first enabled
// moodboard image = last frame (or omit images for text-to-video).
"minimax-h3-fl2va": {
video: {
defaultFps: 24,
audioSampleRate: 32e3
// ModelZoo note: "24 FPS video with synchronized 32 kHz stereo audio"
},
modelFilenames: [
"minimax_h3_fl2va_q8p.ckpt",
"minimax_h3_fl2va_q6p.ckpt",
"minimax_h3_fl2va_i8x.ckpt",
"minimax_h3_fl2va_i4x.ckpt"
]
},
// MiniMax H3 [ref2va]: subject/object/scene-guided generation via canvas + moodboard.
"minimax-h3-ref2va": {
video: {
defaultFps: 24,
audioSampleRate: 32e3
// ModelZoo note: "24 FPS video with synchronized 32 kHz stereo audio"
},
modelFilenames: [
"minimax_h3_ref2va_q8p.ckpt",
"minimax_h3_ref2va_q6p.ckpt",
"minimax_h3_ref2va_i8x.ckpt",
"minimax_h3_ref2va_i4x.ckpt"
]
}
};
var OVERLAY_MODES = ["txt2img", "img2img", "edit", "txt2vid", "img2vid"];
function deriveCapabilities(entries) {
const overlayIds = (mode) => MODEL_IDS.filter((id) => id !== "auto" && id !== "custom" && getModelFilename(id, mode));
const filesOfModel = (m) => m.files.map(([i]) => runtimeCatalog.files[i]);
const all = { ...entries };
const listed = new Set(Object.values(entries).flatMap((e) => (e.modelFilenames ?? []).map((f) => catalogModelOfFile(f)?.id).filter(Boolean)));
for (const id of MODEL_IDS) {
if (id === "auto" || id === "custom" || all[id]) continue;
const files = OVERLAY_MODES.map((mode) => getModelFilename(id, mode)).filter((f) => !!f);
if (files.length && !files.some((f) => listed.has(catalogModelOfFile(f)?.id ?? ""))) all[id] = { modelFilenames: files };
}
const out = {};
for (const [key, entry] of Object.entries(all)) {
const models = (entry.modelFilenames ?? []).map((file) => catalogModelOfFile(file)).filter((m) => !!m);
const modelIds = new Set(models.map((m) => m.id));
const catalogModes = new Set(models.flatMap((m) => m.modes));
const modelFilenames = [.../* @__PURE__ */ new Set([...entry.modelFilenames ?? [], ...models.flatMap(filesOfModel)])];
const overlaysOf = (mode) => overlayIds(mode).filter((id) => modelIds.has(catalogModelOfFile(getModelFilename(id, mode) ?? "")?.id ?? ""));
const image2image = overlaysOf("img2img").length > 0;
const edit = catalogModes.has("edit");
const modes = {
text2image: catalogModes.has("text2image"),
image2image,
edit,
text2video: catalogModes.has("text2video"),
image2video: catalogModes.has("image2video"),
refine: image2image
};
out[key] = {
...entry,
modelFilenames,
modes,
...edit ? { edit: { maxReferenceImages: getMaxReferenceImages(overlaysOf("edit")[0], "edit") } } : {},
...image2image ? { image2image: { maxReferenceImages: 1 } } : {}
};
}
return out;
}
var IMAGE_MODEL_CAPABILITY_MAP = deriveCapabilities(CAPABILITY_ENTRIES);
var DEFAULT_IMAGE_MODEL_CAPABILITIES = {
modes: {
text2image: false,
image2image: false,
edit: false,
text2video: false,
image2video: false
}
};
var MODEL_PRESET_TO_CAPABILITY_KEY = {
"z-image": "z-image-turbo-1.0",
krea: "krea-2-turbo",
krea2: "krea-2-turbo",
"qwen-image": "qwen-image-1.0",
"qwen-image-2.1": "qwen-image-2.1",
"qwen-image-2.1-turbo": "qwen-image-2.1-turbo",
"qwen-edit": "qwen-edit",
// qwen_image_edit_2509_q6p.ckpt or qwen_image_edit_2511_q6p.ckpt
flux: "flux-2-klein",
"flux-2": "flux-2-klein",
"flux-3": "flux-3-klein",
"flux-3-klein": "flux-3-klein",
ltx: "ltx-2.3-distilled",
// ltx-2-distilled is obsolete; current LTX family is 2.3 (distilled variant)
minimax: "minimax-h3-fl2va",
"minimax-ref": "minimax-h3-ref2va",
seedvr2: "seedvr2-7b"
// Note: 'custom' is not in this map - it uses custom_configs.json only
};
function detectImageModelCapabilities(modelId) {
const m = (modelId || "").toLowerCase();
if (IMAGE_MODEL_CAPABILITY_MAP[modelId]) {
return IMAGE_MODEL_CAPABILITY_MAP[modelId];
}
const key = Object.keys(IMAGE_MODEL_CAPABILITY_MAP).find(
(k) => k.toLowerCase() === m
);
if (key) {
return IMAGE_MODEL_CAPABILITY_MAP[key];
}
return DEFAULT_IMAGE_MODEL_CAPABILITIES;
}
function getDefaultFpsForModel(modelId) {
const direct = detectImageModelCapabilities(modelId);
if (direct !== DEFAULT_IMAGE_MODEL_CAPABILITIES) {
return direct.video?.defaultFps;
}
const lower = (modelId || "").toLowerCase();
for (const caps of Object.values(IMAGE_MODEL_CAPABILITY_MAP)) {
if (caps.modelFilenames?.some((f) => f.toLowerCase() === lower)) {
return caps.video?.defaultFps;
}
}
return void 0;
}
function getAudioSampleRateForModel(modelId) {
const direct = detectImageModelCapabilities(modelId);
if (direct !== DEFAULT_IMAGE_MODEL_CAPABILITIES) {
return direct.video?.audioSampleRate;
}
const lower = (modelId || "").toLowerCase();
for (const caps of Object.values(IMAGE_MODEL_CAPABILITY_MAP)) {
if (caps.modelFilenames?.some((f) => f.toLowerCase() === lower)) {
return caps.video?.audioSampleRate;
}
}
return void 0;
}
function findImageModelCapabilitiesByFilename(filename) {
const lower = (filename || "").toLowerCase();
if (!lower) return void 0;
for (const caps of Object.values(IMAGE_MODEL_CAPABILITY_MAP)) {
if (caps.modelFilenames?.some((f) => f.toLowerCase() === lower)) return caps;
}
return void 0;
}
function checkCatalogModel(name, mode) {
const r = resolveModelArgument(name, mode, peekInventory());
if (!r) return null;
return r.ok ? { supported: true } : { supported: false, reason: r.reason };
}
function capabilityKeyOfPreset(preset) {
const listed = MODEL_PRESET_TO_CAPABILITY_KEY[preset] ?? legacyNamesOf(preset).map((name) => MODEL_PRESET_TO_CAPABILITY_KEY[name]).find(Boolean);
if (listed) return listed;
for (const mode of OVERLAY_MODES) {
const file = getModelFilename(preset, mode)?.toLowerCase();
const key = file && Object.keys(IMAGE_MODEL_CAPABILITY_MAP).find((k) => IMAGE_MODEL_CAPABILITY_MAP[k].modelFilenames?.some((f) => f.toLowerCase() === file));
if (key) return key;
}
return void 0;
}
function getCapabilityKeyForPreset(preset) {
if (preset === "auto") return void 0;
return capabilityKeyOfPreset(preset);
}
function checkModeSupport(modelPreset, mode) {
if (modelPreset === "auto") {
return { supported: true };
}
const capKey = capabilityKeyOfPreset(modelPreset);
if (!capKey) {
const catalogCheck = checkCatalogModel(modelPreset, mode);
if (catalogCheck) return catalogCheck;
return {
supported: false,
reason: `Unknown model '${modelPreset}'. Use auto or one of the names listed here; a model name or a file name also works.`
};
}
const caps = detectImageModelCapabilities(capKey);
if (!caps.modes[mode]) {
const supportedModes = Object.entries(caps.modes).filter(([, v]) => v).map(([k]) => k);
return {
supported: false,
reason: `Model '${modelPreset}' does not support mode '${mode}'. Supported modes for this model: ${supportedModes.join(", ") || "none"}.`
};
}
return { supported: true };
}
function checkModeSupportWithCustom(modelPreset, mode, getAvailableCombos) {
if (getAvailableCombos) {
try {
const customCombos = getAvailableCombos();
const hasCustomConfig = customCombos.some(
([customMode, customModelId]) => customMode === mode && customModelId === modelPreset
);
if (hasCustomConfig) {
return { supported: true };
}
} catch {
}
}
const baseCheck = checkModeSupport(modelPreset, mode);
if (baseCheck.supported || !getAvailableCombos) {
return baseCheck;
}
let reason = baseCheck.reason;
try {
const customCombos = getAvailableCombos();
const customForModel = customCombos.filter(
([, modelId]) => modelId === modelPreset
);
if (customForModel.length > 0) {
const customModes = customForModel.map(([m]) => m).join(", ");
reason += ` Custom configs available for '${modelPreset}': ${customModes}.`;
} else {
const customForMode = customCombos.filter(([m]) => m === mode);
if (customForMode.length > 0) {
const customModels = customForMode.map(([, modelId]) => modelId);
reason += ` Mode '${mode}' is available via custom configs for: ${customModels.join(
", "
)}.`;
}
}
} catch {
}
return {
supported: false,
reason
};
}
function resolvePresetFromModelFilename(filename) {
const needle = (filename || "").trim().toLowerCase();
if (!needle) return void 0;
const capKey = Object.keys(IMAGE_MODEL_CAPABILITY_MAP).find(
(k) => IMAGE_MODEL_CAPABILITY_MAP[k].modelFilenames?.some((f) => f.toLowerCase() === needle)
);
if (!capKey) return void 0;
return Object.keys(MODEL_PRESET_TO_CAPABILITY_KEY).find(
(preset) => MODEL_PRESET_TO_CAPABILITY_KEY[preset] === capKey
);
}
function selectAutoModel(mode) {
const defaultModelFilename = mode === "edit" ? defaultParamsImg2Img2.model : mode === "image2image" ? defaultParamsImg2Img.model : mode === "text2video" ? defaultParamsText2Video.model : mode === "image2video" ? defaultParamsImage2Video.model : defaultParams.model;
const resolved = resolvePresetFromModelFilename(defaultModelFilename);
if (resolved) return resolved;
console.warn(
`[Capabilities] selectAutoModel(${mode}): default model '${defaultModelFilename}' is not registered in IMAGE_MODEL_CAPABILITY_MAP/MODEL_PRESET_TO_CAPABILITY_KEY.`
);
return defaultModelFilename ?? "unknown";
}
var VISION_WINDOW_SIZES = {
/** Window 1: User attachments */
attachments: 5,
/** Window 2: Variants + Images (shared cap) */
everythingElse: 4
};
var MEDIA_SOURCE_REGISTRY = {
attachment: {
kind: "attachment",
indexPrefix: "a",
stateArrayKey: "attachments",
counterKey: "nextAttachmentA",
dedupeKey: "originAbs",
visionPromoted: true,
window: 1
},
variant: {
kind: "variant",
indexPrefix: "v",
stateArrayKey: "variants",
counterKey: "nextVariantV",
dedupeKey: "filename",
visionPromoted: true,
window: 2
},
picture: {
kind: "picture",
indexPrefix: "p",
stateArrayKey: "pictures",
counterKey: "nextPictureP",
dedupeKey: "sourceUrl",
visionPromoted: false
// No window assignment: not vision-promoted
},
image: {
kind: "image",
indexPrefix: "i",
stateArrayKey: "images",
counterKey: "nextImageI",
dedupeKey: "filename",
visionPromoted: true,
window: 2
}
};
function getAttachmentWindowSize() {
return VISION_WINDOW_SIZES.attachments;
}
function getEverythingElseWindowSize() {
return VISION_WINDOW_SIZES.everythingElse;
}
function getWindowSizeForKind(kind) {
const config = MEDIA_SOURCE_REGISTRY[kind];
if (!config.visionPromoted || config.window === void 0) return void 0;
return config.window === 1 ? VISION_WINDOW_SIZES.attachments : VISION_WINDOW_SIZES.everythingElse;
}
var FASTVLM_DEFAULT_ENDPOINT = "http://localhost:8765/analyze";
var MLX_VISION_ANALYZE_IMAGE_PROMPT = "";
var MLX_VISION_INDEX_IMAGE_PROMPT = "";
// src/config.ts
import { createConfigSchematics } from "@lmstudio/sdk";
var configSchematics = createConfigSchematics().field(
"model",
"string",
{
displayName: "Agent Model",
subtitle: "Enter the vision model to use as orchestrator. Default: Qwen3.6 35B \u0410\u0417\u0412.",
placeholder: "qwen/qwen3.6-35b-a3b"
},
"qwen/qwen3.6-35b-a3b"
).field(
"usePromptUpsampling",
"boolean",
{
displayName: "Use Prompt Upsampling",
subtitle: "Rewrites the prompt with a prompt upsampling model before rendering, for models that support it. OFF: the prompt goes to Draw Things unchanged.",
engineDoesNotSupport: false
},
true
).field(
"visionPromotionPersistent",
"boolean",
{
displayName: "Vision Promotion: Persistent",
subtitle: "ON: promote up to 5 attachments + 4 variants every turn. OFF: promote only when new.",
engineDoesNotSupport: true
},
false
).field(
"logRequests",
"boolean",
{
displayName: "Debug: Log requests/response",
subtitle: "Logs full request/response JSON; may include sensitive data.",
engineDoesNotSupport: true
},
false
).field(
"debugPromotion",
"boolean",
{
displayName: "Debug: Media promotion",
subtitle: "Verbose logs for media state, previews and cleanup.",
engineDoesNotSupport: true
},
false
).field(
"debugChunks",
"boolean",
{
displayName: "Debug: Stream chunk logs",
subtitle: "Log raw streaming chunks to console (verbose).",
engineDoesNotSupport: true
},
false
).build();
var globalConfigSchematics = createConfigSchematics().field(
"baseUrl",
"string",
{
displayName: "LM Studio API base-URL",
subtitle: "Local LM Studio server base-URL. Default: http://127.0.0.1:1234/v1",
placeholder: "http://127.0.0.1:1234/v1"
},
"http://127.0.0.1:1234/v1"
).field(
"apiKey",
"string",
{
displayName: "(Optional) API Key",
subtitle: "Only needed if your LM Studio server requires authentication.",
isProtected: true,
placeholder: "sk-..."
},
""
).field(
"PREVIEW_IN_CHAT",
"boolean",
{
displayName: "Simple Previews in Chat",
subtitle: "When enabled, tool responses include client-based image previews. Not recommended for advanced functionality.",
engineDoesNotSupport: false
},
false
).field(
"unloadAgentModelDuringRender",
"boolean",
{
displayName: "Unload Agent Model During Render",
subtitle: "When enabled, unloads the agent model from VRAM before long renders (image2image, edit, text2video, image2video). Only applies to local LM Studio instances.",
engineDoesNotSupport: false
},
true
).field(
"DRAW_THINGS_HOST",
"string",
{
displayName: "Draw Things Host",
subtitle: "Hostname or IP of the Draw Things backend server.",
placeholder: "127.0.0.1"
},
"127.0.0.1"
).field(
"DRAW_THINGS_HTTP_PORT",
"numeric",
{
displayName: "Draw Things HTTP Port",
subtitle: "HTTP API port (default: 7860)."
},
7860
).field(
"DRAW_THINGS_GRPC_PORT",
"numeric",
{
displayName: "Draw Things gRPC Port",
subtitle: "gRPC port (default: 7859)."
},
7859
).field(
"embedPngMetadata",
"boolean",
{
displayName: "Embed Metadata in PNGs",
subtitle: "Write generation parameters (prompt, model, seed, LoRAs, sources) into saved PNGs as XMP metadata. Compatible with draw-things-index and find-image.",
engineDoesNotSupport: false
},
true
).field(
"customConfigsPath",
"string",
{
displayName: "Custom Configs Path",
subtitle: "Path to custom_configs.json from Draw Things. Change to: `none` to disable.",
placeholder: "~/Library/Containers/com.liuliu.draw-things/Data/Documents/Models/custom_configs.json",
engineDoesNotSupport: false
},
"~/Library/Containers/com.liuliu.draw-things/Data/Documents/Models/custom_configs.json"
).field(
"HTTP_SERVER_PORT",
"numeric",
{
displayName: "Local HTTP Server Port",
subtitle: "Port for serving generated images over localhost (default: 54760).",
engineDoesNotSupport: true
},
54760
).build();
// src/preprocessor.ts
async function preprocess(ctl, userMessage) {
try {
const originalText = userMessage.getText();
const files = userMessage.consumeFiles(ctl.client, (file) => file.type !== "image");
let injected = "";
for (const file of files) {
const { content } = await ctl.client.files.parseDocument(file, { signal: ctl.abortSignal });
const snippet = content.length > 2e5 ? content.slice(0, 2e5) + "\n...[truncated]" : content;
injected += `
[Attachment: ${file.name}]
${snippet}
`;
}
const wrappers = [];
const inlineImageUrls = /* @__PURE__ */ new Set();
const mdImg = /!\[[^\]]*\]\((https?:[^\s)]+)\)/g;
let m;
while ((m = mdImg.exec(originalText)) !== null) inlineImageUrls.add(m[1]);
const tagImg = /\[image:\s*(https?:[^\]\s]+)\s*\]/gi;
while ((m = tagImg.exec(originalText)) !== null) inlineImageUrls.add(m[1]);
for (const url of inlineImageUrls) {
wrappers.push(`[[LMSTUDIO_ATTACHMENT: ${JSON.stringify({ kind: "image", url })}]]`);
}
if (injected.length === 0 && wrappers.length === 0) return userMessage;
const combined = `${originalText}${injected}${wrappers.length ? "\n\n" + wrappers.join("\n") : ""}`.trim();
userMessage.replaceText(combined);
return userMessage;
} catch (err) {
return userMessage;
}
}
// src/vision-promotion.ts
import fs5 from "fs";
// src/helpers/projectUriResolver.ts
var flatbuffers6 = __toESM(require_flatbuffers(), 1);
import { copyFileSync, existsSync, readFileSync, unlinkSync } from "fs";
import { execFileSync } from "child_process";
import { tmpdir } from "os";
import { join } from "path";
// src/interfaces/thumbnail-history-node.ts
var flatbuffers = __toESM(require_flatbuffers(), 1);
var ThumbnailHistoryNode = class _ThumbnailHistoryNode {
bb = null;
bb_pos = 0;
__init(i, bb) {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsThumbnailHistoryNode(bb, obj) {
return (obj || new _ThumbnailHistoryNode()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
static getSizePrefixedRootAsThumbnailHistoryNode(bb, obj) {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new _ThumbnailHistoryNode()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
id() {
const offset = this.bb.__offset(this.bb_pos, 4);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
data(index2) {
const offset = this.bb.__offset(this.bb_pos, 6);
return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index2) : 0;
}
dataLength() {
const offset = this.bb.__offset(this.bb_pos, 6);
return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
}
dataArray() {
const offset = this.bb.__offset(this.bb_pos, 6);
if (!offset) return null;
const start = this.bb.__vector(this.bb_pos + offset);
const len = this.bb.__vector_len(this.bb_pos + offset);
return this.bb.bytes().subarray(start, start + len);
}
};
// src/interfaces/tensor-history-node.ts
var flatbuffers4 = __toESM(require_flatbuffers(), 1);
// src/interfaces/control.ts
var flatbuffers2 = __toESM(require_flatbuffers(), 1);
// src/interfaces/control-input-type.ts
var ControlInputType = /* @__PURE__ */ ((ControlInputType2) => {
ControlInputType2[ControlInputType2["Unspecified"] = 0] = "Unspecified";
ControlInputType2[ControlInputType2["Custom"] = 1] = "Custom";
ControlInputType2[ControlInputType2["Depth"] = 2] = "Depth";
ControlInputType2[ControlInputType2["Canny"] = 3] = "Canny";
ControlInputType2[ControlInputType2["Scribble"] = 4] = "Scribble";
ControlInputType2[ControlInputType2["Pose"] = 5] = "Pose";
ControlInputType2[ControlInputType2["Normalbae"] = 6] = "Normalbae";
ControlInputType2[ControlInputType2["Color"] = 7] = "Color";
ControlInputType2[ControlInputType2["Lineart"] = 8] = "Lineart";
ControlInputType2[ControlInputType2["Softedge"] = 9] = "Softedge";
ControlInputType2[ControlInputType2["Seg"] = 10] = "Seg";
ControlInputType2[ControlInputType2["Inpaint"] = 11] = "Inpaint";
ControlInputType2[ControlInputType2["Ip2p"] = 12] = "Ip2p";
ControlInputType2[ControlInputType2["Shuffle"] = 13] = "Shuffle";
ControlInputType2[ControlInputType2["Mlsd"] = 14] = "Mlsd";
ControlInputType2[ControlInputType2["Tile"] = 15] = "Tile";
ControlInputType2[ControlInputType2["Blur"] = 16] = "Blur";
ControlInputType2[ControlInputType2["Lowquality"] = 17] = "Lowquality";
ControlInputType2[ControlInputType2["Gray"] = 18] = "Gray";
return ControlInputType2;
})(ControlInputType || {});
// src/interfaces/control-mode.ts
var ControlMode = /* @__PURE__ */ ((ControlMode2) => {
ControlMode2[ControlMode2["Balanced"] = 0] = "Balanced";
ControlMode2[ControlMode2["Prompt"] = 1] = "Prompt";
ControlMode2[ControlMode2["Control"] = 2] = "Control";
return ControlMode2;
})(ControlMode || {});
// src/interfaces/control.ts
var Control = class _Control {
bb = null;
bb_pos = 0;
__init(i, bb) {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsControl(bb, obj) {
return (obj || new _Control()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
static getSizePrefixedRootAsControl(bb, obj) {
bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
return (obj || new _Control()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
file(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 4);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
weight() {
const offset = this.bb.__offset(this.bb_pos, 6);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1;
}
guidanceStart() {
const offset = this.bb.__offset(this.bb_pos, 8);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0;
}
guidanceEnd() {
const offset = this.bb.__offset(this.bb_pos, 10);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1;
}
noPrompt() {
const offset = this.bb.__offset(this.bb_pos, 12);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
globalAveragePooling() {
const offset = this.bb.__offset(this.bb_pos, 14);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true;
}
downSamplingRate() {
const offset = this.bb.__offset(this.bb_pos, 16);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1;
}
controlMode() {
const offset = this.bb.__offset(this.bb_pos, 18);
return offset ? this.bb.readInt8(this.bb_pos + offset) : 0 /* Balanced */;
}
targetBlocks(index2, optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 20);
return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index2 * 4, optionalEncoding) : null;
}
targetBlocksLength() {
const offset = this.bb.__offset(this.bb_pos, 20);
return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
}
inputOverride() {
const offset = this.bb.__offset(this.bb_pos, 22);
return offset ? this.bb.readInt8(this.bb_pos + offset) : 0 /* Unspecified */;
}
static startControl(builder) {
builder.startObject(10);
}
static addFile(builder, fileOffset) {
builder.addFieldOffset(0, fileOffset, 0);
}
static addWeight(builder, weight) {
builder.addFieldFloat32(1, weight, 1);
}
static addGuidanceStart(builder, guidanceStart) {
builder.addFieldFloat32(2, guidanceStart, 0);
}
static addGuidanceEnd(builder, guidanceEnd) {
builder.addFieldFloat32(3, guidanceEnd, 1);
}
static addNoPrompt(builder, noPrompt) {
builder.addFieldInt8(4, +noPrompt, 0);
}
static addGlobalAveragePooling(builder, globalAveragePooling) {
builder.addFieldInt8(5, +globalAveragePooling, 1);
}
static addDownSamplingRate(builder, downSamplingRate) {
builder.addFieldFloat32(6, downSamplingRate, 1);
}
static addControlMode(builder, controlMode) {
builder.addFieldInt8(7, controlMode, 0 /* Balanced */);
}
static addTargetBlocks(builder, targetBlocksOffset) {
builder.addFieldOffset(8, targetBlocksOffset, 0);
}
static createTargetBlocksVector(builder, data) {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
static startTargetBlocksVector(builder, numElems) {
builder.startVector(4, numElems, 4);
}
static addInputOverride(builder, inputOverride) {
builder.addFieldInt8(9, inputOverride, 0 /* Unspecified */);
}
static endControl(builder) {
const offset = builder.endObject();
return offset;
}
static createControl(builder, fileOffset, weight, guidanceStart, guidanceEnd, noPrompt, globalAveragePooling, downSamplingRate, controlMode, targetBlocksOffset, inputOverride) {
_Control.startControl(builder);
_Control.addFile(builder, fileOffset);
_Control.addWeight(builder, weight);
_Control.addGuidanceStart(builder, guidanceStart);
_Control.addGuidanceEnd(builder, guidanceEnd);
_Control.addNoPrompt(builder, noPrompt);
_Control.addGlobalAveragePooling(builder, globalAveragePooling);
_Control.addDownSamplingRate(builder, downSamplingRate);
_Control.addControlMode(builder, controlMode);
_Control.addTargetBlocks(builder, targetBlocksOffset);
_Control.addInputOverride(builder, inputOverride);
return _Control.endControl(builder);
}
};
// src/interfaces/lo-ra.ts
var flatbuffers3 = __toESM(require_flatbuffers(), 1);
// src/interfaces/lo-ramode.ts
var LoRAMode = /* @__PURE__ */ ((LoRAMode2) => {
LoRAMode2[LoRAMode2["All"] = 0] = "All";
LoRAMode2[LoRAMode2["Base"] = 1] = "Base";
LoRAMode2[LoRAMode2["Refiner"] = 2] = "Refiner";
return LoRAMode2;
})(LoRAMode || {});
// src/interfaces/lo-ra.ts
var LoRA = class _LoRA {
bb = null;
bb_pos = 0;
__init(i, bb) {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsLoRA(bb, obj) {
return (obj || new _LoRA()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
static getSizePrefixedRootAsLoRA(bb, obj) {
bb.setPosition(bb.position() + flatbuffers3.SIZE_PREFIX_LENGTH);
return (obj || new _LoRA()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
file(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 4);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
weight() {
const offset = this.bb.__offset(this.bb_pos, 6);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.6;
}
mode() {
const offset = this.bb.__offset(this.bb_pos, 8);
return offset ? this.bb.readInt8(this.bb_pos + offset) : 0 /* All */;
}
static startLoRA(builder) {
builder.startObject(3);
}
static addFile(builder, fileOffset) {
builder.addFieldOffset(0, fileOffset, 0);
}
static addWeight(builder, weight) {
builder.addFieldFloat32(1, weight, 0.6);
}
static addMode(builder, mode) {
builder.addFieldInt8(2, mode, 0 /* All */);
}
static endLoRA(builder) {
const offset = builder.endObject();
return offset;
}
static createLoRA(builder, fileOffset, weight, mode) {
_LoRA.startLoRA(builder);
_LoRA.addFile(builder, fileOffset);
_LoRA.addWeight(builder, weight);
_LoRA.addMode(builder, mode);
return _LoRA.endLoRA(builder);
}
};
// src/interfaces/sampler-type.ts
var SamplerType = /* @__PURE__ */ ((SamplerType2) => {
SamplerType2[SamplerType2["DPMPP2MKarras"] = 0] = "DPMPP2MKarras";
SamplerType2[SamplerType2["EulerA"] = 1] = "EulerA";
SamplerType2[SamplerType2["DDIM"] = 2] = "DDIM";
SamplerType2[SamplerType2["PLMS"] = 3] = "PLMS";
SamplerType2[SamplerType2["DPMPPSDEKarras"] = 4] = "DPMPPSDEKarras";
SamplerType2[SamplerType2["UniPC"] = 5] = "UniPC";
SamplerType2[SamplerType2["LCM"] = 6] = "LCM";
SamplerType2[SamplerType2["EulerASubstep"] = 7] = "EulerASubstep";
SamplerType2[SamplerType2["DPMPPSDESubstep"] = 8] = "DPMPPSDESubstep";
SamplerType2[SamplerType2["TCD"] = 9] = "TCD";
SamplerType2[SamplerType2["EulerATrailing"] = 10] = "EulerATrailing";
SamplerType2[SamplerType2["DPMPPSDETrailing"] = 11] = "DPMPPSDETrailing";
SamplerType2[SamplerType2["DPMPP2MAYS"] = 12] = "DPMPP2MAYS";
SamplerType2[SamplerType2["EulerAAYS"] = 13] = "EulerAAYS";
SamplerType2[SamplerType2["DPMPPSDEAYS"] = 14] = "DPMPPSDEAYS";
SamplerType2[SamplerType2["DPMPP2MTrailing"] = 15] = "DPMPP2MTrailing";
SamplerType2[SamplerType2["DDIMTrailing"] = 16] = "DDIMTrailing";
SamplerType2[SamplerType2["UniPCTrailing"] = 17] = "UniPCTrailing";
SamplerType2[SamplerType2["UniPCAYS"] = 18] = "UniPCAYS";
SamplerType2[SamplerType2["TCDTrailing"] = 19] = "TCDTrailing";
return SamplerType2;
})(SamplerType || {});
// src/interfaces/seed-mode.ts
var SeedMode = /* @__PURE__ */ ((SeedMode2) => {
SeedMode2[SeedMode2["Legacy"] = 0] = "Legacy";
SeedMode2[SeedMode2["TorchCpuCompatible"] = 1] = "TorchCpuCompatible";
SeedMode2[SeedMode2["ScaleAlike"] = 2] = "ScaleAlike";
SeedMode2[SeedMode2["NvidiaGpuCompatible"] = 3] = "NvidiaGpuCompatible";
return SeedMode2;
})(SeedMode || {});
// src/interfaces/reason.ts
var Reason = /* @__PURE__ */ ((Reason2) => {
Reason2[Reason2["Other"] = 0] = "Other";
Reason2[Reason2["Generate"] = 1] = "Generate";
Reason2[Reason2["Imported"] = 2] = "Imported";
Reason2[Reason2["Draw"] = 3] = "Draw";
Reason2[Reason2["Mask"] = 4] = "Mask";
Reason2[Reason2["Scribble"] = 5] = "Scribble";
Reason2[Reason2["Moodboard"] = 6] = "Moodboard";
Reason2[Reason2["DepthMap"] = 7] = "DepthMap";
Reason2[Reason2["Clear"] = 8] = "Clear";
return Reason2;
})(Reason || {});
// src/interfaces/tensor-history-node.ts
var TensorHistoryNode = class _TensorHistoryNode {
bb = null;
bb_pos = 0;
__init(i, bb) {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsTensorHistoryNode(bb, obj) {
return (obj || new _TensorHistoryNode()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
static getSizePrefixedRootAsTensorHistoryNode(bb, obj) {
bb.setPosition(bb.position() + flatbuffers4.SIZE_PREFIX_LENGTH);
return (obj || new _TensorHistoryNode()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
lineage() {
const offset = this.bb.__offset(this.bb_pos, 4);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
logicalTime() {
const offset = this.bb.__offset(this.bb_pos, 6);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
startWidth() {
const offset = this.bb.__offset(this.bb_pos, 8);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
}
startHeight() {
const offset = this.bb.__offset(this.bb_pos, 10);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
}
seed() {
const offset = this.bb.__offset(this.bb_pos, 12);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
steps() {
const offset = this.bb.__offset(this.bb_pos, 14);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
guidanceScale() {
const offset = this.bb.__offset(this.bb_pos, 16);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0;
}
strength() {
const offset = this.bb.__offset(this.bb_pos, 18);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0;
}
model(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 20);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
tensorId() {
const offset = this.bb.__offset(this.bb_pos, 22);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
maskId() {
const offset = this.bb.__offset(this.bb_pos, 24);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
depthMapId() {
const offset = this.bb.__offset(this.bb_pos, 48);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
generated() {
const offset = this.bb.__offset(this.bb_pos, 50);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true;
}
wallClock() {
const offset = this.bb.__offset(this.bb_pos, 26);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
textEdits() {
const offset = this.bb.__offset(this.bb_pos, 28);
return offset ? this.bb.readInt64(this.bb_pos + offset) : -1n;
}
textLineage() {
const offset = this.bb.__offset(this.bb_pos, 30);
return offset ? this.bb.readInt64(this.bb_pos + offset) : -1n;
}
batchSize() {
const offset = this.bb.__offset(this.bb_pos, 32);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 1;
}
sampler() {
const offset = this.bb.__offset(this.bb_pos, 34);
return offset ? this.bb.readUint8(this.bb_pos + offset) : 0 /* DPMPP2MKarras */;
}
seedMode() {
const offset = this.bb.__offset(this.bb_pos, 54);
return offset ? this.bb.readUint8(this.bb_pos + offset) : 0 /* Legacy */;
}
controls(index2, obj) {
const offset = this.bb.__offset(this.bb_pos, 58);
return offset ? (obj || new Control()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index2 * 4), this.bb) : null;
}
controlsLength() {
const offset = this.bb.__offset(this.bb_pos, 58);
return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
}
scribbleId() {
const offset = this.bb.__offset(this.bb_pos, 60);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
poseId() {
const offset = this.bb.__offset(this.bb_pos, 62);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
loras(index2, obj) {
const offset = this.bb.__offset(this.bb_pos, 64);
return offset ? (obj || new LoRA()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index2 * 4), this.bb) : null;
}
lorasLength() {
const offset = this.bb.__offset(this.bb_pos, 64);
return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
}
colorPaletteId() {
const offset = this.bb.__offset(this.bb_pos, 66);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
customId() {
const offset = this.bb.__offset(this.bb_pos, 70);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
dataStored() {
const offset = this.bb.__offset(this.bb_pos, 84);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
}
previewId() {
const offset = this.bb.__offset(this.bb_pos, 86);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
targetImageHeight() {
const offset = this.bb.__offset(this.bb_pos, 104);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
targetImageWidth() {
const offset = this.bb.__offset(this.bb_pos, 106);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
shuffleDataStored() {
const offset = this.bb.__offset(this.bb_pos, 120);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
}
generationTime() {
const offset = this.bb.__offset(this.bb_pos, 218);
return offset ? this.bb.readFloat64(this.bb_pos + offset) : 0;
}
textPrompt(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 200);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
negativeTextPrompt(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 202);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
numFrames() {
const offset = this.bb.__offset(this.bb_pos, 130);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 14;
}
clipId() {
const offset = this.bb.__offset(this.bb_pos, 204);
return offset ? this.bb.readInt64(this.bb_pos + offset) : -1n;
}
indexInAClip() {
const offset = this.bb.__offset(this.bb_pos, 206);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
}
reason() {
const offset = this.bb.__offset(this.bb_pos, 220);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0 /* Other */;
}
};
// src/interfaces/text-history-node.ts
var flatbuffers5 = __toESM(require_flatbuffers(), 1);
// src/interfaces/text-range.ts
var TextRange = class _TextRange {
bb = null;
bb_pos = 0;
__init(i, bb) {
this.bb_pos = i;
this.bb = bb;
return this;
}
static createTextRange(bb, offset, obj) {
return (obj || new _TextRange()).__init(offset, bb);
}
location() {
return this.bb.readInt32(this.bb_pos);
}
length() {
return this.bb.readInt32(this.bb_pos + 4);
}
};
// src/interfaces/text-type.ts
var TextType = /* @__PURE__ */ ((TextType2) => {
TextType2[TextType2["PositiveText"] = 0] = "PositiveText";
TextType2[TextType2["NegativeText"] = 1] = "NegativeText";
return TextType2;
})(TextType || {});
// src/interfaces/text-modification.ts
var TextModification = class _TextModification {
bb = null;
bb_pos = 0;
__init(i, bb) {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsTextModification(bb, obj) {
return (obj || new _TextModification()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
type() {
const offset = this.bb.__offset(this.bb_pos, 4);
return offset ? this.bb.readUint8(this.bb_pos + offset) : 0 /* PositiveText */;
}
range(obj) {
const offset = this.bb.__offset(this.bb_pos, 6);
return offset ? (obj || new TextRange()).__init(this.bb_pos + offset, this.bb) : null;
}
text(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 8);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
};
// src/interfaces/text-history-node.ts
var TextHistoryNode = class _TextHistoryNode {
bb = null;
bb_pos = 0;
__init(i, bb) {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsTextHistoryNode(bb, obj) {
return (obj || new _TextHistoryNode()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
static getSizePrefixedRootAsTextHistoryNode(bb, obj) {
bb.setPosition(bb.position() + flatbuffers5.SIZE_PREFIX_LENGTH);
return (obj || new _TextHistoryNode()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
lineage() {
const offset = this.bb.__offset(this.bb_pos, 4);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
logicalTime() {
const offset = this.bb.__offset(this.bb_pos, 6);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
startEdits() {
const offset = this.bb.__offset(this.bb_pos, 8);
return offset ? this.bb.readInt64(this.bb_pos + offset) : 0n;
}
startPositiveText(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 10);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
startNegativeText(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 12);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
modifications(index2, obj) {
const offset = this.bb.__offset(this.bb_pos, 14);
return offset ? (obj || new TextModification()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index2 * 4), this.bb) : null;
}
modificationsLength() {
const offset = this.bb.__offset(this.bb_pos, 14);
return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
}
};
// src/helpers/projectUriResolver.ts
var SQL = null;
async function getSqlJs() {
if (!SQL) {
const { default: initSqlJs } = await import("sql.js");
SQL = await initSqlJs();
}
return SQL;
}
function isProjectUri(uri) {
return typeof uri === "string" && uri.startsWith("project://");
}
function parseProjectUri(uri) {
if (!isProjectUri(uri)) {
return null;
}
const withoutScheme = uri.slice("project://".length);
const hashIndex = withoutScheme.lastIndexOf("#");
if (hashIndex === -1) {
return null;
}
const projectPath = withoutScheme.slice(0, hashIndex);
const thumbnailId = parseInt(withoutScheme.slice(hashIndex + 1), 10);
if (isNaN(thumbnailId) || thumbnailId < 0) {
return null;
}
return { projectPath, thumbnailId };
}
function decodeThumbnailFromBlob(blob) {
const bytes = new Uint8Array(blob.buffer, blob.byteOffset, blob.byteLength);
for (const kind of ["root", "size"]) {
try {
const byteBuffer = new flatbuffers6.ByteBuffer(bytes);
const node = kind === "size" ? ThumbnailHistoryNode.getSizePrefixedRootAsThumbnailHistoryNode(byteBuffer) : ThumbnailHistoryNode.getRootAsThumbnailHistoryNode(byteBuffer);
const data = node.dataArray();
if (data?.length) return Buffer.from(data);
} catch {
}
}
return null;
}
function extractImageFromThumbnailBlob(blob) {
const jpegMarker = Buffer.from([255, 216, 255]);
const jpegStart = blob.indexOf(jpegMarker);
if (jpegStart !== -1) {
const jpegEnd = blob.lastIndexOf(Buffer.from([255, 217]));
if (jpegEnd !== -1 && jpegEnd > jpegStart) {
return blob.slice(jpegStart, jpegEnd + 2);
}
return blob.slice(jpegStart);
}
const pngMarker = Buffer.from([137, 80, 78, 71]);
const pngStart = blob.indexOf(pngMarker);
if (pngStart !== -1) {
const iendMarker = Buffer.from([
73,
69,
78,
68,
174,
66,
96,
130
]);
const pngEnd = blob.lastIndexOf(iendMarker);
if (pngEnd !== -1 && pngEnd > pngStart) {
return blob.slice(pngStart, pngEnd + 8);
}
return blob.slice(pngStart);
}
return null;
}
function normalizedThumbnailIds(thumbnailIds) {
return [...new Set([...thumbnailIds].filter((thumbnailId) => Number.isSafeInteger(thumbnailId) && thumbnailId >= 0))];
}
function thumbnailQuery(thumbnailIds) {
return `SELECT __pk0, p FROM thumbnailhistorynode WHERE __pk0 IN (${thumbnailIds.join(",")})`;
}
function decodeThumbnailRows(rows) {
const thumbnails = /* @__PURE__ */ new Map();
for (const [thumbnailId, rawBlob] of rows) {
const blob = Buffer.from(rawBlob);
const image = decodeThumbnailFromBlob(blob) ?? extractImageFromThumbnailBlob(blob);
if (image) thumbnails.set(thumbnailId, image);
}
return thumbnails;
}
function cleanupFile(filePath) {
if (filePath) try {
unlinkSync(filePath);
} catch {
}
}
async function openProjectDatabase(projectPath) {
const sqlJs = await getSqlJs();
const walPath = projectPath + "-wal";
const shmPath = projectPath + "-shm";
if (existsSync(walPath)) {
const tempFile = join(tmpdir(), `dt-project-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.sqlite3`);
try {
execFileSync("sqlite3", ["-readonly", projectPath, `VACUUM INTO '${tempFile.replace(/'/g, "''")}'`], { timeout: 1e4 });
return { db: new sqlJs.Database(readFileSync(tempFile)), tempFile };
} catch {
cleanupFile(tempFile);
const tempSourceFile = join(tmpdir(), `dt-project-source-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.sqlite3`);
copyFileSync(projectPath, tempSourceFile);
copyFileSync(walPath, `${tempSourceFile}-wal`);
if (existsSync(shmPath)) copyFileSync(shmPath, `${tempSourceFile}-shm`);
execFileSync("sqlite3", [tempSourceFile, `VACUUM INTO '${tempFile.replace(/'/g, "''")}'`], { timeout: 1e4 });
return { db: new sqlJs.Database(readFileSync(tempFile)), tempFile, tempSourceFile };
}
}
return { db: new sqlJs.Database(readFileSync(projectPath)) };
}
function closeProjectDatabase(db, tempFile, tempSourceFile) {
db?.close();
cleanupFile(tempFile);
if (tempSourceFile) {
for (const filePath of [tempSourceFile, `${tempSourceFile}-wal`, `${tempSourceFile}-shm`]) {
cleanupFile(filePath);
}
}
}
async function readThumbnailsFromSnapshot(projectPath, thumbnailIds) {
let db = null;
let tempFile;
let tempSourceFile;
try {
({ db, tempFile, tempSourceFile } = await openProjectDatabase(projectPath));
const result = db.exec(thumbnailQuery(thumbnailIds));
const rows = result.length ? result[0].values.flatMap((row) => typeof row[0] === "number" && row[1] instanceof Uint8Array ? [[row[0], row[1]]] : []) : [];
return decodeThumbnailRows(rows);
} finally {
closeProjectDatabase(db, tempFile, tempSourceFile);
}
}
async function getThumbnailsFromProject(projectPath, thumbnailIds) {
const ids = normalizedThumbnailIds(thumbnailIds);
if (ids.length === 0) return /* @__PURE__ */ new Map();
try {
return await readThumbnailsFromSnapshot(projectPath, ids);
} catch (error) {
console.error(`[ProjectUriResolver] Failed to read thumbnails from ${projectPath}:`, error);
return /* @__PURE__ */ new Map();
}
}
async function getThumbnailFromProject(projectPath, thumbnailId) {
return (await getThumbnailsFromProject(projectPath, [thumbnailId])).get(thumbnailId) ?? null;
}
async function resolveProjectUri(uri) {
const parts = parseProjectUri(uri);
if (!parts) {
console.error(`[ProjectUriResolver] Invalid project URI: ${uri}`);
return null;
}
return getThumbnailFromProject(parts.projectPath, parts.thumbnailId);
}
function bigintToSafeNumber(v) {
const n = Number(v);
if (!Number.isFinite(n)) return void 0;
if (BigInt(Math.trunc(n)) !== v) return void 0;
return n;
}
function coerceFlatbuffersString(v) {
if (typeof v === "string") return v;
if (v instanceof Uint8Array) {
try {
return Buffer.from(v).toString("utf8");
} catch {
return void 0;
}
}
return void 0;
}
function samplerToString(sampler) {
const names = {
[0 /* DPMPP2MKarras */]: "DPM++ 2M Karras",
[1 /* EulerA */]: "Euler A",
[2 /* DDIM */]: "DDIM",
[3 /* PLMS */]: "PLMS",
[4 /* DPMPPSDEKarras */]: "DPM++ SDE Karras",
[5 /* UniPC */]: "UniPC",
[6 /* LCM */]: "LCM",
[7 /* EulerASubstep */]: "Euler A Substep",
[8 /* DPMPPSDESubstep */]: "DPM++ SDE Substep",
[9 /* TCD */]: "TCD",
[10 /* EulerATrailing */]: "Euler A Trailing",
[11 /* DPMPPSDETrailing */]: "DPM++ SDE Trailing",
[12 /* DPMPP2MAYS */]: "DPM++ 2M AYS",
[13 /* EulerAAYS */]: "Euler A AYS",
[14 /* DPMPPSDEAYS */]: "DPM++ SDE AYS",
[15 /* DPMPP2MTrailing */]: "DPM++ 2M Trailing",
[16 /* DDIMTrailing */]: "DDIM Trailing",
[17 /* UniPCTrailing */]: "UniPC Trailing",
[18 /* UniPCAYS */]: "UniPC AYS"
};
return names[sampler] ?? `Unknown(${sampler})`;
}
function decodeTensorHistoryNodeFromBlob(blob) {
const u8 = new Uint8Array(blob.buffer, blob.byteOffset, blob.byteLength);
for (const kind of ["root", "size"]) {
try {
const bb = new flatbuffers6.ByteBuffer(u8);
const node = kind === "size" ? TensorHistoryNode.getSizePrefixedRootAsTensorHistoryNode(bb) : TensorHistoryNode.getRootAsTensorHistoryNode(bb);
const previewId = bigintToSafeNumber(node.previewId());
const logicalTime = bigintToSafeNumber(node.logicalTime());
const textLineage = bigintToSafeNumber(node.textLineage());
const textEdits = bigintToSafeNumber(node.textEdits());
const loras = [];
for (let i = 0; i < node.lorasLength(); i++) {
const lora = node.loras(i);
const file = coerceFlatbuffersString(lora?.file());
if (file?.trim()) loras.push({ file, weight: lora?.weight() });
}
const model = coerceFlatbuffersString(node.model()) ?? void 0;
const prompt = coerceFlatbuffersString(node.textPrompt()) ?? void 0;
const negativePrompt = coerceFlatbuffersString(node.negativeTextPrompt()) ?? void 0;
let width = node.startWidth() || node.targetImageWidth() || void 0;
let height = node.startHeight() || node.targetImageHeight() || void 0;
if (width != null && height != null && Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0 && width <= 64 && height <= 64) {
width = width * 64;
height = height * 64;
}
const generationTimeSec = node.generationTime();
const inferenceTimeMs = Number.isFinite(generationTimeSec) && generationTimeSec > 0 ? Math.round(generationTimeSec * 1e3) : void 0;
return {
seed: node.seed(),
steps: node.steps(),
cfgScale: node.guidanceScale(),
width,
height,
sampler: samplerToString(node.sampler()),
model: model?.trim() ? model : void 0,
prompt: prompt?.trim() ? prompt : void 0,
negativePrompt: negativePrompt?.trim() ? negativePrompt : void 0,
loras: loras.length ? loras : void 0,
previewId,
logicalTime,
textLineage,
textEdits,
inferenceTimeMs
};
} catch {
}
}
return null;
}
function decodeTextHistoryNodeFromBlob(blob) {
const u8 = new Uint8Array(blob.buffer, blob.byteOffset, blob.byteLength);
for (const kind of ["root", "size"]) {
try {
const bb = new flatbuffers6.ByteBuffer(u8);
const node = kind === "size" ? TextHistoryNode.getSizePrefixedRootAsTextHistoryNode(bb) : TextHistoryNode.getRootAsTextHistoryNode(bb);
const lineage = bigintToSafeNumber(node.lineage());
const logicalTime = bigintToSafeNumber(node.logicalTime());
const startEdits = bigintToSafeNumber(node.startEdits()) ?? 0;
if (lineage == null || logicalTime == null) return null;
const startPositiveText = coerceFlatbuffersString(node.startPositiveText()) ?? "";
const startNegativeText = coerceFlatbuffersString(node.startNegativeText()) ?? "";
const modifications = [];
for (let i = 0; i < node.modificationsLength(); i++) {
const mod = node.modifications(i);
if (!mod) continue;
const range = mod.range();
const text = coerceFlatbuffersString(mod.text()) ?? "";
modifications.push({ type: mod.type(), location: range?.location() ?? 0, length: range?.length() ?? 0, text });
}
return { lineage, logicalTime, startEdits, startPositiveText, startNegativeText, modifications };
} catch {
}
}
return null;
}
function applyTextEdit(base, edit) {
const loc = Math.max(0, Math.min(base.length, edit.location));
const end = Math.max(loc, Math.min(base.length, loc + Math.max(0, edit.length)));
return base.slice(0, loc) + edit.text + base.slice(end);
}
function replayTextHistory(history, upToEdits) {
let prompt = history.startPositiveText ?? "";
let negativePrompt = history.startNegativeText ?? "";
let toApply = history.modifications.length;
if (upToEdits != null && Number.isFinite(upToEdits)) {
const remaining = upToEdits - history.startEdits;
toApply = remaining <= 0 ? 0 : Math.min(history.modifications.length, remaining);
}
for (let i = 0; i < toApply; i++) {
const edit = history.modifications[i];
if (edit.type === 0 /* PositiveText */) prompt = applyTextEdit(prompt, edit);
else negativePrompt = applyTextEdit(negativePrompt, edit);
}
return { prompt, negativePrompt };
}
function promptLooksTaggy(s) {
const t = s.toLowerCase();
return t.includes("best quality") || t.includes("high quality") || t.includes("trending on artstation") || t.includes("award-winning") || t.includes("cgsociety");
}
function scorePromptCandidate(s) {
const t = s.trim();
if (t.length < 10) return -1;
if (t.startsWith("{") || t.startsWith("[")) return -1;
if (/\.(ckpt|safetensors|gguf|pt|pth)$/i.test(t)) return -1;
if (/^\w+:\/\//.test(t)) return -1;
if (/^\/[A-Za-z0-9_\-./]+$/.test(t)) return -1;
let score = t.length;
const words = t.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
score += new Set(words).size * 3;
if (t.includes(".")) score += 10;
if (t.includes("'")) score += 5;
const commaCount = t.split(",").length - 1;
if (commaCount >= 6) score -= 25;
if (promptLooksTaggy(t)) score -= 80;
if (/timings|duration|profile/i.test(t)) score -= 30;
if (/[{}]/.test(t)) score -= 20;
return score;
}
function pickTextHistoryForGeneration(historyByLineage, lineage, generationLogicalTime) {
const rows = historyByLineage.get(lineage) ?? [];
if (!rows.length) return null;
const chosen = [...rows].filter((r) => r.logicalTime <= generationLogicalTime).sort((a, b) => b.logicalTime - a.logicalTime)[0];
return chosen ?? rows[rows.length - 1];
}
function pickTextPromptForGeneration(textByLineage, generationLogicalTime) {
if (textByLineage.size === 0) return null;
const lineage = textByLineage.has(0) ? 0 : [...textByLineage.entries()].sort((a, b) => b[1].length - a[1].length)[0][0];
const rows = textByLineage.get(lineage) ?? [];
if (!rows.length) return null;
const candidate = [...rows].filter((r) => r.logicalTime <= generationLogicalTime).sort((a, b) => b.logicalTime - a.logicalTime)[0];
const chosen = candidate ?? rows[rows.length - 1];
return { prompt: chosen.prompt, negativePrompt: chosen.negativePrompt };
}
function findTensorHistoryRowForThumbnail(db, thumbnailId) {
try {
const linkResult = db.exec(`SELECT rowid FROM tensorhistorynode__f86 WHERE f86 = ${thumbnailId}`);
const rowid = linkResult.length && linkResult[0].values.length ? linkResult[0].values[0][0] : void 0;
if (rowid != null) {
const rowResult = db.exec(`SELECT rowid, p FROM tensorhistorynode WHERE rowid = ${rowid}`);
if (rowResult.length && rowResult[0].values.length) {
const row = rowResult[0].values[0];
return { rowid: row[0], p: Buffer.from(row[1]) };
}
}
} catch {
}
const scanResult = db.exec("SELECT rowid, p FROM tensorhistorynode WHERE __pk1 >= 1 ORDER BY rowid");
if (!scanResult.length) return null;
for (const row of scanResult[0].values) {
const blob = Buffer.from(row[1]);
const decoded = decodeTensorHistoryNodeFromBlob(blob);
if (decoded?.previewId === thumbnailId) return { rowid: row[0], p: blob };
}
return null;
}
async function getDrawThingsGenerationMetadata(projectPath, thumbnailId) {
let db = null;
let tempFile;
let tempSourceFile;
try {
({ db, tempFile, tempSourceFile } = await openProjectDatabase(projectPath));
const target2 = findTensorHistoryRowForThumbnail(db, thumbnailId);
if (!target2) return null;
const decoded = decodeTensorHistoryNodeFromBlob(target2.p);
if (!decoded || decoded.inferenceTimeMs === void 0) return null;
const textByLineage = /* @__PURE__ */ new Map();
const textHistoryByLineage = /* @__PURE__ */ new Map();
const textResult = db.exec("SELECT __pk0, __pk1, p FROM texthistorynode ORDER BY __pk0, __pk1");
if (textResult.length && textResult[0].values.length) {
for (const row of textResult[0].values) {
const decodedText = decodeTextHistoryNodeFromBlob(Buffer.from(row[2]));
if (!decodedText) continue;
textHistoryByLineage.set(decodedText.lineage, [...textHistoryByLineage.get(decodedText.lineage) ?? [], decodedText]);
const final = replayTextHistory(decodedText);
const prompt2 = final.prompt.trim();
if (!prompt2) continue;
const score = scorePromptCandidate(prompt2);
if (score < 0) continue;
textByLineage.set(decodedText.lineage, [
...textByLineage.get(decodedText.lineage) ?? [],
{ lineage: decodedText.lineage, logicalTime: decodedText.logicalTime, prompt: prompt2, negativePrompt: final.negativePrompt.trim() || void 0, score }
]);
}
}
let prompt = decoded.prompt;
let negativePrompt = decoded.negativePrompt;
const generationLogicalTime = decoded.logicalTime ?? 0;
if (decoded.textLineage != null && decoded.textEdits != null) {
const history = pickTextHistoryForGeneration(textHistoryByLineage, decoded.textLineage, generationLogicalTime);
if (history) {
const rebuilt = replayTextHistory(history, decoded.textEdits);
prompt = rebuilt.prompt;
negativePrompt = rebuilt.negativePrompt || negativePrompt;
} else {
const textCand = pickTextPromptForGeneration(textByLineage, generationLogicalTime);
if (textCand) {
prompt = textCand.prompt;
negativePrompt = textCand.negativePrompt || negativePrompt;
}
}
}
return {
prompt,
negativePrompt,
model: decoded.model,
sampler: decoded.sampler,
steps: decoded.steps,
guidanceScale: decoded.cfgScale,
seed: decoded.seed,
width: decoded.width,
height: decoded.height,
loras: decoded.loras,
inferenceTimeMs: decoded.inferenceTimeMs
};
} catch (error) {
console.error(`[ProjectUriResolver] Failed to read generation metadata from ${projectPath}:`, error);
return null;
} finally {
closeProjectDatabase(db, tempFile, tempSourceFile);
}
}
async function resolveProjectGenerationMetadata(uri) {
const parts = parseProjectUri(uri);
if (!parts) {
console.error(`[ProjectUriResolver] Invalid project URI: ${uri}`);
return null;
}
return getDrawThingsGenerationMetadata(parts.projectPath, parts.thumbnailId);
}
function detectImageMimeType(buf) {
if (!buf || buf.length < 3) return null;
if (buf[0] === 255 && buf[1] === 216 && buf[2] === 255) return "image/jpeg";
if (buf.length >= 8 && buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71 && buf[4] === 13 && buf[5] === 10 && buf[6] === 26 && buf[7] === 10) return "image/png";
if (buf.length >= 12 && buf[0] === 82 && buf[1] === 73 && buf[2] === 70 && buf[3] === 70 && buf[8] === 87 && buf[9] === 69 && buf[10] === 66 && buf[11] === 80) return "image/webp";
if (buf.length >= 6 && buf[0] === 71 && buf[1] === 73 && buf[2] === 70 && buf[3] === 56 && (buf[4] === 55 || buf[4] === 57) && buf[5] === 97) return "image/gif";
return null;
}
function detectProjectImageType(buf) {
const mimeType = detectImageMimeType(buf);
if (mimeType === "image/jpeg") return "jpeg";
if (mimeType === "image/png") return "png";
return null;
}
// src/vision-promotion.ts
async function toOpenAIPromptParts(items) {
const parts = [];
for (const it of items) {
const label = it.label || "Image";
parts.push({ type: "text", text: label });
const buf = await fs5.promises.readFile(it.previewAbs);
const b64 = buf.toString("base64");
const mime = detectImageMimeType(buf);
if (!mime) throw new Error(`Unsupported image bytes: ${it.previewAbs}`);
parts.push({ type: "image_url", image_url: { url: `data:${mime};base64,${b64}` } });
}
return parts;
}
// src/helpers/agentModelUnload.ts
import fs8 from "fs";
import path7 from "path";
// src/media-promotion-core/state.ts
import fs7 from "fs";
import path6 from "path";
// src/helpers/fileLock.ts
import fs6 from "fs";
var POLL_MS = 15;
var ACQUIRE_TIMEOUT_MS = 15e3;
var MAX_LOCK_AGE_MS = 3e4;
var EMPTY_LOCK_GRACE_MS = 1e3;
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function pidAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch (e) {
return e?.code === "EPERM";
}
}
async function readLockHolder(lockPath) {
try {
const [raw, st] = await Promise.all([fs6.promises.readFile(lockPath, "utf-8"), fs6.promises.stat(lockPath)]);
const pid = parseInt(raw.trim(), 10);
return { pid: Number.isFinite(pid) && pid > 0 ? pid : null, ageMs: Date.now() - st.mtimeMs };
} catch (e) {
if (e?.code === "ENOENT") return null;
throw e;
}
}
async function reclaimIfStale(lockPath) {
const holder = await readLockHolder(lockPath);
if (!holder) return true;
const stale = holder.ageMs > MAX_LOCK_AGE_MS || holder.pid === null && holder.ageMs > EMPTY_LOCK_GRACE_MS || holder.pid !== null && !pidAlive(holder.pid);
if (!stale) return false;
const again = await readLockHolder(lockPath);
if (!again || again.pid !== holder.pid) return true;
await fs6.promises.rm(lockPath, { force: true });
return true;
}
async function withFileLock(lockPath, fn) {
const deadline = Date.now() + ACQUIRE_TIMEOUT_MS;
for (; ; ) {
try {
const handle = await fs6.promises.open(lockPath, "wx");
try {
await handle.writeFile(String(process.pid));
} finally {
await handle.close();
}
break;
} catch (e) {
if (e?.code !== "EEXIST") throw e;
if (await reclaimIfStale(lockPath)) continue;
if (Date.now() > deadline) throw new Error(`Timed out waiting for lock ${lockPath}`);
await sleep(POLL_MS);
}
}
try {
return await fn();
} finally {
await fs6.promises.rm(lockPath, { force: true });
}
}
function uniqueTmpPath(dst) {
return `${dst}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`;
}
// src/media-promotion-core/state.ts
function localTimestamp(d = /* @__PURE__ */ new Date()) {
const pad = (n, len = 2) => String(n).padStart(len, "0");
const year = d.getFullYear();
const month = pad(d.getMonth() + 1);
const day = pad(d.getDate());
const hours = pad(d.getHours());
const minutes = pad(d.getMinutes());
const seconds = pad(d.getSeconds());
const millis = pad(d.getMilliseconds(), 3);
const tzOffset = -d.getTimezoneOffset();
const tzSign = tzOffset >= 0 ? "+" : "-";
const tzHours = pad(Math.floor(Math.abs(tzOffset) / 60));
const tzMins = pad(Math.abs(tzOffset) % 60);
return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${millis}${tzSign}${tzHours}:${tzMins}`;
}
function tsForFilename(d = /* @__PURE__ */ new Date()) {
const year = d.getUTCFullYear();
const month = String(d.getUTCMonth() + 1).padStart(2, "0");
const day = String(d.getUTCDate()).padStart(2, "0");
const hours = String(d.getUTCHours()).padStart(2, "0");
const minutes = String(d.getUTCMinutes()).padStart(2, "0");
const seconds = String(d.getUTCSeconds()).padStart(2, "0");
const millis = String(d.getUTCMilliseconds()).padStart(3, "0");
return `${year}${month}${day}T${hours}${minutes}${seconds}${millis}Z`;
}
var STATE_BASE = /* @__PURE__ */ Symbol.for("dtc.chatMediaState.baseRaw");
function setStateBase(state, raw) {
Object.defineProperty(state, STATE_BASE, {
value: raw,
enumerable: false,
configurable: true,
writable: true
});
}
function emptyState() {
return {
attachments: [],
variants: [],
pictures: [],
images: [],
counters: {}
};
}
async function readState(chatWd) {
const p = path6.join(chatWd, "chat_media_state.json");
let raw = "";
try {
raw = await fs7.promises.readFile(p, "utf-8");
} catch {
raw = "";
}
let state;
try {
state = raw ? normalizeState(JSON.parse(raw)) : emptyState();
} catch {
state = emptyState();
}
setStateBase(state, raw);
return state;
}
var isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
function stableStringify(v) {
if (Array.isArray(v)) return `[${v.map(stableStringify).join(",")}]`;
if (isPlainObject(v)) {
return `{${Object.keys(v).filter((k) => v[k] !== void 0).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(v[k])}`).join(",")}}`;
}
return JSON.stringify(v) ?? "undefined";
}
var jsonEqual = (a, b) => stableStringify(a) === stableStringify(b);
var KEYED_COLLECTIONS = {
attachments: "a",
variants: "v",
pictures: "p",
images: "i"
};
function mergeKeyedRecords(base, mine, theirs, keyField) {
const index2 = (arr) => new Map(arr.map((r) => [r?.[keyField], r]));
const B = index2(base);
const M = index2(mine);
const T = index2(theirs);
const out = [];
for (const k of /* @__PURE__ */ new Set([...M.keys(), ...T.keys()])) {
const inB = B.has(k);
const inM = M.has(k);
const inT = T.has(k);
if (inM && inT) {
out.push(mergeStateValue(B.get(k), M.get(k), T.get(k), ""));
} else if (inM) {
if (!inB || !jsonEqual(M.get(k), B.get(k))) out.push(M.get(k));
} else if (!inB || !jsonEqual(T.get(k), B.get(k))) {
out.push(T.get(k));
}
}
return out;
}
function mergePrimitiveSet(base, mine, theirs) {
const baseSet = new Set(base);
const mineSet = new Set(mine);
const removedByMe = new Set(base.filter((x) => !mineSet.has(x)));
const out = theirs.filter((x) => !removedByMe.has(x));
for (const x of mine) if (!baseSet.has(x) && !out.includes(x)) out.push(x);
return out;
}
function mergeStateValue(base, mine, theirs, p) {
if (jsonEqual(mine, base)) return theirs;
if (jsonEqual(theirs, base) || jsonEqual(mine, theirs)) return mine;
if (isPlainObject(mine) && isPlainObject(theirs)) {
const b = isPlainObject(base) ? base : {};
const out = {};
for (const k of /* @__PURE__ */ new Set([...Object.keys(mine), ...Object.keys(theirs), ...Object.keys(b)])) {
const v = mergeStateValue(b[k], mine[k], theirs[k], p ? `${p}.${k}` : k);
if (v !== void 0) out[k] = v;
}
return out;
}
if (Array.isArray(mine) && Array.isArray(theirs)) {
const b = Array.isArray(base) ? base : [];
const keyField = KEYED_COLLECTIONS[p];
if (keyField) return mergeKeyedRecords(b, mine, theirs, keyField);
const prim = (x) => x === null || typeof x !== "object";
if (b.every(prim) && mine.every(prim) && theirs.every(prim)) return mergePrimitiveSet(b, mine, theirs);
return mine;
}
if (p.startsWith("counters.") && typeof mine === "number" && typeof theirs === "number") {
return Math.max(mine, theirs);
}
return mine;
}
async function readRawOrEmpty(file) {
try {
return await fs7.promises.readFile(file, "utf-8");
} catch {
return "";
}
}
function parseStateOrEmpty(raw) {
try {
return raw ? normalizeState(JSON.parse(raw)) : emptyState();
} catch {
return emptyState();
}
}
async function writeStateAtomic(chatWd, state) {
const dst = path6.join(chatWd, "chat_media_state.json");
await withFileLock(`${dst}.lock`, async () => {
const baseRaw = state[STATE_BASE];
if (typeof baseRaw === "string") {
const currentRaw = await readRawOrEmpty(dst);
if (currentRaw !== baseRaw) {
const merged = mergeStateValue(
JSON.parse(JSON.stringify(parseStateOrEmpty(baseRaw))),
JSON.parse(JSON.stringify(state)),
JSON.parse(JSON.stringify(parseStateOrEmpty(currentRaw))),
""
);
for (const k of Object.keys(state)) delete state[k];
Object.assign(state, merged);
console.info(`[chat_media_state] merged concurrent changes in ${dst}`);
}
}
await writeStateFile(chatWd, state);
});
}
async function writeStateFile(chatWd, state) {
const dst = path6.join(chatWd, "chat_media_state.json");
const tmp = uniqueTmpPath(dst);
if (Array.isArray(state.attachments) && state.attachments.length > 1) {
state.attachments.sort((a, b) => (a.a ?? 0) - (b.a ?? 0));
}
if (Array.isArray(state.variants) && state.variants.length > 1) {
state.variants.sort((a, b) => (a.v ?? 0) - (b.v ?? 0));
}
if (Array.isArray(state.pictures) && state.pictures.length > 1) {
state.pictures.sort((a, b) => (a.p ?? 0) - (b.p ?? 0));
}
if (Array.isArray(state.images) && state.images.length > 1) {
state.images.sort((a, b) => (a.i ?? 0) - (b.i ?? 0));
}
let pretty = JSON.stringify(state, null, 2);
pretty = pretty.replace(
/"(lastPromotedAttachmentAs|lastPromotedVariantVs|lastPromotedImageIs|lastPixelPromotedAttachmentAs|lastPixelPromotedVariantVs|lastPixelPromotedImageIs|injectedMarkdown)":\s*\[\s*\n([\s\S]*?)\n\s*\]/g,
(match, key, content) => {
const items = content.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
return `"${key}": [${items.join(", ")}]`;
}
);
await fs7.promises.writeFile(tmp, pretty, "utf-8");
await fs7.promises.rename(tmp, dst);
setStateBase(state, pretty);
}
function normalizeState(s) {
let lastPromotedAttachmentAs;
if (Array.isArray(s?.lastPromotedAttachmentAs)) {
lastPromotedAttachmentAs = s.lastPromotedAttachmentAs.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
} else if (Array.isArray(s?.lastPromotedAttachmentNs)) {
lastPromotedAttachmentAs = s.lastPromotedAttachmentNs.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
} else if (typeof s?.lastPromotedAttachmentN === "number") {
lastPromotedAttachmentAs = [s.lastPromotedAttachmentN];
} else if (typeof s?.lastPromotedAttachmentA === "number") {
lastPromotedAttachmentAs = [s.lastPromotedAttachmentA];
}
let lastPromotedVariantVs;
if (Array.isArray(s?.lastPromotedVariantVs)) {
lastPromotedVariantVs = s.lastPromotedVariantVs.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
}
let lastPromotedImageIs;
if (Array.isArray(s?.lastPromotedImageIs)) {
lastPromotedImageIs = s.lastPromotedImageIs.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
}
let lastPixelPromotedAttachmentAs;
if (Array.isArray(s?.lastPixelPromotedAttachmentAs)) {
lastPixelPromotedAttachmentAs = s.lastPixelPromotedAttachmentAs.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
} else if (Array.isArray(s?.lastPixelPromotedAttachmentNs)) {
lastPixelPromotedAttachmentAs = s.lastPixelPromotedAttachmentNs.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
}
let lastPixelPromotedVariantVs;
if (Array.isArray(s?.lastPixelPromotedVariantVs)) {
lastPixelPromotedVariantVs = s.lastPixelPromotedVariantVs.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
}
let lastPixelPromotedImageIs;
if (Array.isArray(s?.lastPixelPromotedImageIs)) {
lastPixelPromotedImageIs = s.lastPixelPromotedImageIs.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
}
const normalizeNumberArray = (v) => {
if (!Array.isArray(v)) return void 0;
const a = v.filter((x) => typeof x === "number" && Number.isFinite(x)).map((x) => Math.floor(x)).filter((x) => x > 0);
if (!a.length) return void 0;
return Array.from(new Set(a)).sort((x, y) => x - y);
};
const pendingReviewPromotion = (() => {
const pr = s?.pendingReviewPromotion;
if (!pr || typeof pr !== "object") return void 0;
const requestedAt = typeof pr.requestedAt === "string" && pr.requestedAt.trim() ? String(pr.requestedAt) : "";
const targets = pr.targets && typeof pr.targets === "object" ? pr.targets : null;
if (!requestedAt || !targets) return void 0;
const a = normalizeNumberArray(targets.a);
const v = normalizeNumberArray(targets.v);
const i = normalizeNumberArray(targets.i);
const p = normalizeNumberArray(targets.p);
if (!a && !v && !i && !p) return void 0;
const ttlMs = typeof pr.ttlMs === "number" && Number.isFinite(pr.ttlMs) && pr.ttlMs > 0 ? pr.ttlMs : void 0;
return {
requestedAt,
requestedByToolCallId: typeof pr.requestedByToolCallId === "string" && pr.requestedByToolCallId.trim() ? String(pr.requestedByToolCallId) : void 0,
reason: typeof pr.reason === "string" && pr.reason.trim() ? String(pr.reason) : void 0,
ttlMs,
targets: {
a,
v,
i,
p
}
};
})();
const pendingSequenceReview = (() => {
const ps = s?.pendingSequenceReview;
if (!ps || typeof ps !== "object") return void 0;
const requestedAt = typeof ps.requestedAt === "string" && ps.requestedAt.trim() ? String(ps.requestedAt) : "";
const movAbs = typeof ps.movAbs === "string" && ps.movAbs.trim() ? String(ps.movAbs) : "";
const variant = typeof ps.variant === "number" && Number.isFinite(ps.variant) ? Math.floor(ps.variant) : 0;
if (!requestedAt || !movAbs || variant <= 0) return void 0;
const fps = typeof ps.fps === "number" && Number.isFinite(ps.fps) && ps.fps > 0 ? ps.fps : 2;
const ttlMs = typeof ps.ttlMs === "number" && Number.isFinite(ps.ttlMs) && ps.ttlMs > 0 ? ps.ttlMs : void 0;
return {
requestedAt,
movAbs,
variant,
variantLabel: typeof ps.variantLabel === "string" && ps.variantLabel.trim() ? String(ps.variantLabel) : void 0,
fps,
ttlMs
};
})();
const n = {
attachments: Array.isArray(s?.attachments) ? s.attachments : [],
variants: Array.isArray(s?.variants) ? s.variants : [],
pictures: Array.isArray(s?.pictures) ? s.pictures : [],
images: Array.isArray(s?.images) ? s.images : [],
pendingReviewPromotion,
pendingSequenceReview,
lastEvent: s?.lastEvent,
lastCanvasNotation: typeof s?.lastCanvasNotation === "string" ? s.lastCanvasNotation : void 0,
lastCanvasAt: typeof s?.lastCanvasAt === "string" ? s.lastCanvasAt : void 0,
counters: typeof s?.counters === "object" && s?.counters ? s.counters : {},
injectedMarkdown: Array.isArray(s?.injectedMarkdown) ? s.injectedMarkdown : void 0,
injectedContent: Array.isArray(s?.injectedContent) ? s.injectedContent.filter((x) => typeof x === "string" && x.trim()) : void 0,
lastVariantsTs: typeof s?.lastVariantsTs === "string" ? s.lastVariantsTs : void 0,
lastPromotedTs: typeof s?.lastPromotedTs === "string" ? s.lastPromotedTs : void 0,
lastPromotedAttachmentAs,
// Keep deprecated field for backward compat during transition
lastPromotedAttachmentA: typeof s?.lastPromotedAttachmentA === "number" ? s.lastPromotedAttachmentA : typeof s?.lastPromotedAttachmentN === "number" ? s.lastPromotedAttachmentN : void 0,
lastPromotedVariantVs,
lastPromotedImageIs,
lastPixelPromotedAt: typeof s?.lastPixelPromotedAt === "string" ? s.lastPixelPromotedAt : void 0,
lastPixelPromotedAttachmentAs,
lastPixelPromotedVariantVs,
lastPixelPromotedImageIs,
forcePixelPromotionNextTurn: typeof s?.forcePixelPromotionNextTurn === "boolean" ? s.forcePixelPromotionNextTurn : void 0,
forcePixelPromotionSetAt: typeof s?.forcePixelPromotionSetAt === "string" ? s.forcePixelPromotionSetAt : void 0,
forcePixelPromotionReason: typeof s?.forcePixelPromotionReason === "string" ? s.forcePixelPromotionReason : void 0,
lastSsotMessageCount: typeof s?.lastSsotMessageCount === "number" && Number.isFinite(s.lastSsotMessageCount) ? s.lastSsotMessageCount : void 0
};
if (n.attachments.length > 1) {
n.attachments.sort((a, b) => (a.a ?? 0) - (b.a ?? 0));
}
if (n.variants.length > 1) {
n.variants.sort((a, b) => (a.v ?? 0) - (b.v ?? 0));
}
if (n.pictures.length > 1) {
n.pictures.sort((a, b) => (a.p ?? 0) - (b.p ?? 0));
}
if (n.images.length > 1) {
n.images.sort((a, b) => (a.i ?? 0) - (b.i ?? 0));
}
return n;
}
function upsertAttachment(state, rec) {
const existing = Array.isArray(state.attachments) ? state.attachments : [];
const createdAt = rec.createdAt ?? localTimestamp();
const matches = (a) => {
if (rec.originAbs && a.originAbs && a.originAbs === rec.originAbs)
return true;
return a.filename === rec.filename && a.preview === rec.preview;
};
const idx = existing.findIndex(matches);
if (idx >= 0) {
const keep = existing[idx];
const updated = {
...keep,
filename: rec.filename,
origin: rec.origin,
originAbs: rec.originAbs,
originalName: rec.originalName ?? keep.originalName,
turnId: rec.turnId ?? keep.turnId,
preview: rec.preview,
createdAt: keep.createdAt,
a: keep.a
};
const next2 = [updated, ...existing.filter((_, i) => i !== idx)];
const changed = JSON.stringify(next2) !== JSON.stringify(existing);
if (changed) {
state.attachments = next2;
state.lastEvent = { type: "attachment", at: localTimestamp() };
}
return { changed, state, record: updated };
}
const nextA = rec.a ?? Math.max(1, state.counters.nextAttachmentA ?? 1);
const finalRec = {
filename: rec.filename,
origin: rec.origin,
originAbs: rec.originAbs,
originalName: rec.originalName,
turnId: rec.turnId,
preview: rec.preview,
createdAt,
a: nextA
};
const next = [finalRec, ...existing];
state.attachments = next;
state.counters.nextAttachmentA = nextA + 1;
state.lastEvent = { type: "attachment", at: localTimestamp() };
return { changed: true, state, record: finalRec };
}
function normalizeString(val) {
return typeof val === "string" ? String(val) : void 0;
}
function normalizeNumber(val) {
return typeof val === "number" && Number.isFinite(val) ? val : void 0;
}
var COMMON_MEDIA_KEYS = /* @__PURE__ */ new Set([
"filename",
"preview",
"sourceTool",
"pluginId",
"sourceUrl",
"title",
"confidence",
"width",
"height",
"pageUrl",
"turnId",
"createdAt",
"kind",
"v",
"p",
"i"
]);
function buildMediaRecord(input, index2, indexField, createdAt, existingIndex) {
const base = {
filename: input.filename,
preview: input.preview,
sourceTool: normalizeString(input.sourceTool),
pluginId: normalizeString(input.pluginId),
sourceUrl: normalizeString(input.sourceUrl),
title: normalizeString(input.title),
confidence: normalizeString(input.confidence),
width: normalizeNumber(input.width),
height: normalizeNumber(input.height),
pageUrl: normalizeString(input.pageUrl),
turnId: normalizeNumber(input.turnId),
createdAt: input.createdAt ?? createdAt
};
if (input.kind === "tool_result" || input.kind === "generated") {
base.kind = input.kind;
}
for (const key of Object.keys(input)) {
if (!COMMON_MEDIA_KEYS.has(key) && input[key] != null) {
base[key] = input[key];
}
}
base[indexField] = existingIndex ?? index2;
return base;
}
function upgradeExistingRecord(existing, incoming, indexField) {
const incomingIndex = incoming[indexField];
if (existing[indexField] == null && typeof incomingIndex === "number") {
existing[indexField] = incomingIndex;
}
const fieldsToUpgrade = [
"sourceTool",
"pluginId",
"sourceUrl",
"title",
"confidence",
"pageUrl",
"kind"
];
for (const field of fieldsToUpgrade) {
if (existing[field] == null && incoming[field] != null) {
existing[field] = incoming[field];
}
}
if (existing.width == null && typeof incoming.width === "number") {
existing.width = incoming.width;
}
if (existing.height == null && typeof incoming.height === "number") {
existing.height = incoming.height;
}
if (existing.turnId == null && typeof incoming.turnId === "number") {
existing.turnId = incoming.turnId;
}
for (const key of Object.keys(incoming)) {
if (!COMMON_MEDIA_KEYS.has(key) && existing[key] == null && incoming[key] != null) {
existing[key] = incoming[key];
}
}
}
function appendMediaItems(state, items, config) {
if (!items.length) return { changed: false, state, records: [] };
const {
stateArrayKey,
counterKey,
indexField,
eventType,
getDedupeKey,
filter
} = config;
const existing = Array.isArray(
state[stateArrayKey]
) ? [...state[stateArrayKey]] : [];
const maxExistingIndex = existing.reduce((max, r) => {
const idx = r[indexField];
return Math.max(max, typeof idx === "number" && Number.isFinite(idx) ? idx : 0);
}, 0);
const counterIndex = state.counters[counterKey] ?? 1;
const baseIndex = Math.max(1, counterIndex, maxExistingIndex + 1);
const createdAt = localTimestamp();
let newOnes = items.map(
(it, idx) => buildMediaRecord(
it,
baseIndex + idx,
indexField,
createdAt,
it[indexField]
)
);
if (filter) {
newOnes = newOnes.filter(filter);
}
const existingByKey = /* @__PURE__ */ new Map();
for (const item of existing) {
const key = getDedupeKey(item);
if (key) existingByKey.set(key, item);
}
const all = [...existing];
for (const r of newOnes) {
const key = getDedupeKey(r);
const existingItem = key ? existingByKey.get(key) : void 0;
if (!existingItem) {
all.push(r);
if (key) existingByKey.set(key, r);
} else {
upgradeExistingRecord(
existingItem,
r,
indexField
);
}
}
all.sort((a, b) => {
const aIdx = a[indexField] ?? 0;
const bIdx = b[indexField] ?? 0;
return aIdx - bIdx || String(a.createdAt || "").localeCompare(String(b.createdAt || ""));
});
const changed = JSON.stringify(all) !== JSON.stringify(state[stateArrayKey] || []);
if (changed) {
state[stateArrayKey] = all;
const lastIndex = all.at(-1)?.[indexField];
state.counters[counterKey] = (typeof lastIndex === "number" ? lastIndex : baseIndex - 1) + 1;
state.lastEvent = { type: eventType, at: localTimestamp() };
}
return { changed, state, records: newOnes };
}
var VARIANT_APPEND_CONFIG = {
stateArrayKey: "variants",
counterKey: "nextVariantV",
indexField: "v",
eventType: "variants",
getDedupeKey: (item) => `${item.filename}|${item.preview}`
};
var PICTURE_APPEND_CONFIG = {
stateArrayKey: "pictures",
counterKey: "nextPictureP",
indexField: "p",
eventType: "pictures",
getDedupeKey: (item) => item.sourceUrl ? item.sourceUrl : `${item.filename}|${item.preview}`,
filter: (item) => !!String(item.sourceUrl || "").trim()
};
var IMAGE_APPEND_CONFIG = {
stateArrayKey: "images",
counterKey: "nextImageI",
indexField: "i",
eventType: "images",
getDedupeKey: (item) => `${item.filename}|${item.preview}`
};
function appendVariants(state, items) {
return appendMediaItems(
state,
items,
VARIANT_APPEND_CONFIG
);
}
function appendPictures(state, items) {
return appendMediaItems(
state,
items,
PICTURE_APPEND_CONFIG
);
}
function appendImages(state, items) {
return appendMediaItems(
state,
items,
IMAGE_APPEND_CONFIG
);
}
function referencedFiles(state) {
const s = /* @__PURE__ */ new Set();
for (const a of state.attachments) {
if (a.filename) s.add(a.filename);
if (a.preview) s.add(a.preview);
}
for (const v of state.variants) {
if (v.filename) s.add(v.filename);
if (v.preview) s.add(v.preview);
}
for (const p of state.pictures || []) {
if (p.filename) s.add(p.filename);
if (p.preview) s.add(p.preview);
}
for (const i of state.images || []) {
if (i.filename) s.add(i.filename);
if (i.preview) s.add(i.preview);
}
s.add("chat_media_state.json");
return s;
}
function fileInWd(absOrRel, chatWd) {
return path6.isAbsolute(absOrRel) ? absOrRel : path6.join(chatWd, absOrRel);
}
// src/helpers/agentModelUnload.ts
async function getAxios() {
return (await import("axios")).default;
}
function normalizeLmApiRoot(baseUrl) {
return String(baseUrl || "").trim().replace(/\/(api\/v1|v1)\/?$/i, "").replace(/\/+$/, "");
}
function buildLmApiAuthHeaders(apiKey) {
if (typeof apiKey === "string" && apiKey.trim()) {
return { Authorization: `Bearer ${apiKey.trim()}` };
}
return {};
}
function appendToPluginLog(line) {
try {
const logsDir2 = getLogsDir();
fs8.mkdirSync(logsDir2, { recursive: true });
fs8.appendFileSync(
path7.join(logsDir2, "generate-image-plugin.log"),
`${localTimestamp()} - ${line}
`
);
} catch {
}
}
async function unloadAgentModel(opts) {
const apiRoot = normalizeLmApiRoot(opts.baseUrl);
const unloadUrl = `${apiRoot}/api/v1/models/unload`;
try {
const axios2 = await getAxios();
await axios2.post(
unloadUrl,
{ instance_id: opts.modelKey },
{
timeout: 15e3,
headers: {
"Content-Type": "application/json",
...buildLmApiAuthHeaders(opts.apiKey)
}
}
);
appendToPluginLog(`[INFO] [AgentModel] \u2713 Unloaded: ${opts.modelKey}`);
console.info(`[INFO] [AgentModel] Unloaded model to free VRAM: ${opts.modelKey}`);
return true;
} catch (e) {
console.warn(`[AgentModel] Unload failed (non-fatal):`, e?.message || e);
return false;
}
}
// src/helpers/activeChatContext.ts
import { AsyncLocalStorage } from "async_hooks";
var activeChatContext = null;
var STORE_KEY = /* @__PURE__ */ Symbol.for("draw-things.activeChatContext");
function store() {
const holder = globalThis;
let existing = holder[STORE_KEY];
if (!existing) {
existing = new AsyncLocalStorage();
holder[STORE_KEY] = existing;
}
return existing;
}
function setActiveChatContext(ctx) {
const next = {
chatId: String(ctx.chatId),
workingDir: String(ctx.workingDir),
setAtMs: Date.now(),
requestId: ctx.requestId
};
activeChatContext = next;
store().enterWith(next);
}
function getActiveChatContext(opts) {
const scoped = store().getStore();
if (scoped) return scoped;
const maxAgeMs = typeof opts?.maxAgeMs === "number" && Number.isFinite(opts.maxAgeMs) ? Math.max(0, Math.floor(opts.maxAgeMs)) : 60 * 1e3;
if (!activeChatContext) return null;
if (maxAgeMs === 0) return activeChatContext;
const ageMs = Date.now() - activeChatContext.setAtMs;
if (!Number.isFinite(ageMs) || ageMs < 0) return null;
if (ageMs > maxAgeMs) return null;
return activeChatContext;
}
// src/helpers/attachments.ts
import { promises as fsp2 } from "fs";
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
import path8, { join as join3, extname } from "path";
import os2 from "os";
// src/helpers/findLMStudioHome.ts
import {
existsSync as existsSync2,
readFileSync as readFileSync2,
realpathSync,
writeFileSync
} from "fs";
import { homedir } from "os";
import { join as join2 } from "path";
var lmstudioHome = null;
function findLMStudioHome() {
if (lmstudioHome !== null) {
return lmstudioHome;
}
const resolvedHomeDir = realpathSync(homedir());
const pointerFilePath = join2(resolvedHomeDir, ".lmstudio-home-pointer");
if (existsSync2(pointerFilePath)) {
const candidate = readFileSync2(pointerFilePath, "utf-8").trim();
try {
if (candidate && existsSync2(candidate)) {
const hasConversations = existsSync2(join2(candidate, "conversations"));
const hasUserFiles = existsSync2(join2(candidate, "user-files"));
if (hasConversations || hasUserFiles) {
lmstudioHome = candidate;
return lmstudioHome;
}
}
} catch {
}
}
const dotHome = join2(resolvedHomeDir, ".lmstudio");
const cacheHome = join2(resolvedHomeDir, ".cache", "lm-studio");
const looksValid = (p) => {
try {
if (!existsSync2(p)) return false;
const conv = join2(p, "conversations");
const files = join2(p, "user-files");
return existsSync2(conv) || existsSync2(files);
} catch {
return false;
}
};
if (looksValid(dotHome)) {
lmstudioHome = dotHome;
try {
writeFileSync(pointerFilePath, lmstudioHome, "utf-8");
} catch {
}
return lmstudioHome;
}
if (looksValid(cacheHome)) {
lmstudioHome = cacheHome;
try {
writeFileSync(pointerFilePath, lmstudioHome, "utf-8");
} catch {
}
return lmstudioHome;
}
const home = dotHome;
lmstudioHome = home;
try {
writeFileSync(pointerFilePath, lmstudioHome, "utf-8");
} catch {
}
return lmstudioHome;
}
function getLMStudioWorkingDir(chatId) {
const home = findLMStudioHome();
return join2(home, "working-directories", chatId);
}
// src/helpers/attachments.ts
var loadedSharp = void 0;
var loadedJimp = void 0;
async function tryLoadSharp() {
if (loadedSharp !== void 0) return loadedSharp;
try {
const mod = await import("sharp");
loadedSharp = mod?.default || mod;
return loadedSharp;
} catch {
loadedSharp = null;
return null;
}
}
async function tryLoadJimp() {
if (loadedJimp !== void 0) return loadedJimp;
try {
const mod = await import("jimp");
loadedJimp = mod.default || mod.Jimp || mod;
return loadedJimp;
} catch {
loadedJimp = null;
return null;
}
}
async function validateImageBuffer(buf) {
const sharp = await tryLoadSharp();
if (sharp) {
try {
const meta = await sharp(buf).metadata();
if (meta && (meta.width || meta.height)) {
return { ok: true, width: meta.width, height: meta.height };
}
} catch {
}
return { ok: false };
}
const Jimp = await tryLoadJimp();
if (Jimp && typeof Jimp.read === "function") {
try {
const img = await Jimp.read(buf);
const w = typeof img.getWidth === "function" ? img.getWidth() : typeof img.width === "number" ? img.width : img.bitmap?.width || 0;
const h = typeof img.getHeight === "function" ? img.getHeight() : typeof img.height === "number" ? img.height : img.bitmap?.height || 0;
if (w || h) return { ok: true, width: w, height: h };
} catch {
}
return { ok: false };
}
return { ok: true };
}
function projectRootFromHere() {
const currentDir = typeof __dirname !== "undefined" ? __dirname : process.cwd();
if (currentDir.endsWith("helpers") || currentDir.endsWith("src")) {
return path8.resolve(currentDir, "..", "..");
}
return currentDir;
}
async function readLastAttachmentRef() {
try {
const root = projectRootFromHere();
const p = join3(root, "logs", "last-attachment.json");
if (!existsSync3(p)) return null;
const raw = await fsp2.readFile(p, "utf-8");
const json = JSON.parse(raw);
if (!json || typeof json !== "object" || !json.client) return null;
return json;
} catch {
return null;
}
}
function inferMimeFromExt(name, fallback = "image/png") {
if (!name) return fallback;
const ext = extname(name).toLowerCase().replace(/^\./, "");
switch (ext) {
case "jpg":
case "jpeg":
return "image/jpeg";
case "png":
return "image/png";
case "webp":
return "image/webp";
case "gif":
return "image/gif";
case "bmp":
return "image/bmp";
case "tif":
case "tiff":
return "image/tiff";
case "heic":
return "image/heic";
default:
return fallback;
}
}
async function rehydrateLastAttachment() {
try {
const ref = await readLastAttachmentRef();
if (!ref) return { ok: false, reason: "No persisted attachment reference" };
if (ref.client === "lmstudio") {
if (!ref.fileIdentifier)
return {
ok: false,
reason: "Persisted LM attachment has no fileIdentifier"
};
const LM_HOME2 = findLMStudioHome() || join3(os2.homedir(), ".lmstudio");
const userFilesDir = join3(LM_HOME2, "user-files");
const metaPath = join3(
userFilesDir,
`${ref.fileIdentifier}.metadata.json`
);
let buffer = null;
let mime;
if (existsSync3(metaPath)) {
try {
const metaRaw = readFileSync3(metaPath, "utf-8");
const meta = JSON.parse(metaRaw);
const dataStr = typeof meta?.preview?.data === "string" ? meta.preview.data : typeof meta?.content === "string" ? meta.content : typeof meta?.base64 === "string" ? meta.base64 : typeof meta?.data === "string" ? meta.data : void 0;
if (dataStr) {
const s = dataStr.trim();
let b64 = null;
let mimeFromHeader;
if (s.startsWith("data:")) {
const comma = s.indexOf(",");
if (comma > 0) {
b64 = s.slice(comma + 1);
const header = s.slice(5, comma);
const semi = header.indexOf(";");
mimeFromHeader = (semi >= 0 ? header.slice(0, semi) : header) || void 0;
}
} else {
const stripped = s.replace(/\s+/g, "");
if (/^[A-Za-z0-9+/]+={0,2}$/.test(stripped) && stripped.length >= 8) {
b64 = stripped;
}
}
if (b64) {
try {
const buf = Buffer.from(b64, "base64");
const im = await validateImageBuffer(buf);
if (im.ok) {
buffer = buf;
mime = mimeFromHeader || meta?.preview?.mimeType || meta?.mimeType || meta?.mimetype || meta?.contentType;
}
} catch {
}
}
}
} catch {
}
}
if (!buffer) {
const orig = join3(userFilesDir, ref.fileIdentifier);
if (existsSync3(orig)) buffer = readFileSync3(orig);
}
if (!buffer)
return {
ok: false,
reason: "Persisted LM attachment not found on disk"
};
const imgCheck = await validateImageBuffer(buffer);
if (!imgCheck.ok) {
return {
ok: false,
reason: "Persisted LM attachment is not a valid image"
};
}
const mimeType = mime || inferMimeFromExt(ref.fileIdentifier, "image/png");
return {
ok: true,
buffer,
mimeType,
tag: `lmstudio_attachment:${ref.fileIdentifier} (persisted)`
};
}
return {
ok: false,
reason: `Unknown client in last-attachment: ${ref.client}`
};
} catch (e) {
return { ok: false, reason: e?.message || String(e) };
}
}
async function getLMStudioFileMetadata(fileIdentifier) {
try {
const home = findLMStudioHome() || join3(os2.homedir(), ".lmstudio");
const metadataPath = join3(
home,
"user-files",
`${fileIdentifier}.metadata.json`
);
if (!existsSync3(metadataPath)) return null;
const raw = await fsp2.readFile(metadataPath, "utf-8");
const meta = JSON.parse(raw);
if (typeof meta.originalName !== "string" || typeof meta.fileIdentifier !== "string") {
return null;
}
return meta;
} catch {
return null;
}
}
async function getOriginalFileName(fileIdentifier) {
const meta = await getLMStudioFileMetadata(fileIdentifier);
return meta?.originalName ?? null;
}
function getLMStudioUserFilePath(fileIdentifier) {
const home = findLMStudioHome() || join3(os2.homedir(), ".lmstudio");
const filePath = join3(home, "user-files", fileIdentifier);
return existsSync3(filePath) ? filePath : null;
}
// src/services/toolParams/attachments.ts
function extractAttachmentFromSsot(raw) {
const candidates = [];
if (Array.isArray(raw)) {
for (let i = 0; i < raw.length; i++) {
const item = raw[i];
if (typeof item === "string" && item.trim()) {
candidates.push({ filename: item.trim(), index: i + 1 });
} else if (item && typeof item === "object") {
const obj = item;
if (typeof obj.identifier === "string" && obj.identifier.trim()) {
candidates.push({ filename: obj.identifier.trim(), index: i + 1 });
} else if (typeof obj.filename === "string" && obj.filename.trim()) {
candidates.push({ filename: obj.filename.trim(), index: i + 1 });
}
}
}
}
return candidates;
}
var ATTACHMENT_FULL_CONFIG = {
mediaType: "attachment",
allow: "all",
ssotJoin: {
source: "conversation.json",
messageRole: "user",
jsonPath: "message.files[]",
extractFromSource: extractAttachmentFromSsot
},
scan: {
trigger: "on-turn-start",
scope: "all-turns"
// Full scan for reconcile (user can delete attachments)
},
harvesting: {
defaultExtractor: extractAttachmentFromSsot,
tools: {}
// Attachments kommen nicht aus Tools
},
actions: {
generatePreview: true,
visionPromotion: {
metadata: true,
// Labels (a1, a2) ALWAYS included
pixel: true
// Base64 pixels in rolling window
}
},
injectMdInAgentResponse: {
format: "none",
labelGenerator: (item, i) => `a${item.index ?? i + 1}`
},
preview: {
generate: true,
namingPattern: "preview-{basename}.jpg",
format: drawthingsLimits.previewFormat,
mimeType: "image/jpeg",
maxSum: drawthingsLimits.previewMaxSum,
quality: drawthingsLimits.previewQuality,
outputDir: "."
},
toggles: {
toggles: []
// No toggle dependencies for attachments
}
};
var ATTACHMENT_CONFIG = {
mediaType: "attachment",
allow: "all",
defaultExtractor: extractAttachmentFromSsot,
defaultActions: ATTACHMENT_FULL_CONFIG.actions,
tools: {}
};
// src/services/toolParams/variants.ts
function extractVariantUrisFromContent(raw) {
const candidates = [];
const text = typeof raw === "string" ? raw : JSON.stringify(raw);
const uriRegex = /file:\/\/[^\s"')]+generated-image-[^\s"')]*-v(\d+)\.png/gi;
let match;
while ((match = uriRegex.exec(text)) !== null) {
const uri = match[0];
const variantNum = parseInt(match[1], 10);
const filename = uri.split("/").pop() ?? "";
candidates.push({
filename,
index: variantNum
});
}
return candidates;
}
function extractGenerateImageResult(raw) {
const candidates = [];
if (raw && typeof raw === "object") {
const obj = raw;
if (Array.isArray(obj.filenames)) {
for (let i = 0; i < obj.filenames.length; i++) {
const fn = obj.filenames[i];
if (typeof fn === "string") {
candidates.push({ filename: fn, index: i + 1 });
}
}
}
if (Array.isArray(obj.content)) {
for (const item of obj.content) {
if (item && typeof item === "object" && "text" in item) {
const nested = extractVariantUrisFromContent(item.text);
candidates.push(...nested);
}
}
}
}
if (candidates.length === 0) {
return extractVariantUrisFromContent(raw);
}
return candidates;
}
var selfPlugin = getSelfPluginIdentifier() ?? "unknown";
var VARIANT_FULL_CONFIG = {
mediaType: "variant",
allow: "all",
ssotJoin: {
source: "conversation.json",
messageRole: "assistant",
jsonPath: "content",
// Regex scan for file:// URIs
extractFromSource: extractVariantUrisFromContent
},
scan: {
trigger: "both",
scope: "all-turns"
},
harvesting: {
defaultExtractor: extractGenerateImageResult,
tools: {
[`${selfPlugin}/generate_image`]: {
extractCandidates: extractGenerateImageResult,
actions: {
generatePreview: true,
visionPromotion: {
metadata: true,
pixel: true
}
}
}
}
},
actions: {
generatePreview: true,
visionPromotion: {
metadata: true,
// Labels (v1, v2) ALWAYS included
pixel: true
// Base64 pixels in rolling window
}
},
injectMdInAgentResponse: {
format: "none",
// Toggle-dependent: !PREVIEW_IN_CHAT
itemTemplate: "",
labelGenerator: (item, i) => `v${item.index ?? i + 1}`
},
preview: {
generate: true,
namingPattern: "preview-{basename}.jpg",
format: drawthingsLimits.previewFormat,
mimeType: "image/jpeg",
maxSum: drawthingsLimits.previewMaxSum,
quality: drawthingsLimits.previewQuality,
outputDir: "."
},
toggles: {
toggles: []
}
};
var VARIANT_CONFIG = {
mediaType: "variant",
allow: "all",
defaultExtractor: extractGenerateImageResult,
defaultActions: VARIANT_FULL_CONFIG.actions,
tools: VARIANT_FULL_CONFIG.harvesting.tools
};
// src/helpers/toolResultImageHarvest.ts
import fs10 from "fs";
import path10 from "path";
import crypto from "crypto";
// src/media-promotion-core/image.ts
import fs9 from "fs";
import path9 from "path";
// src/helpers/imageUtils.ts
var loadedSharp2 = void 0;
var loadedJimp2 = void 0;
var libLogged = false;
var loggedFns = /* @__PURE__ */ new Set();
function logOnce(msg) {
if (loggedFns.has(msg)) return;
loggedFns.add(msg);
try {
console.debug(msg);
} catch {
}
}
async function tryLoadSharp2() {
if (loadedSharp2 !== void 0) return loadedSharp2;
try {
const mod = await import("sharp");
loadedSharp2 = mod?.default || mod;
if (!libLogged) {
try {
console.debug(`[imageUtils] using lib=sharp`);
libLogged = true;
} catch {
}
}
return loadedSharp2;
} catch {
loadedSharp2 = null;
return null;
}
}
async function tryLoadJimp2() {
if (loadedJimp2 !== void 0) return loadedJimp2;
try {
const mod = await import("jimp");
const candidate = mod && (mod.default || mod.Jimp || mod);
loadedJimp2 = candidate;
if (!libLogged) {
try {
console.debug(`[imageUtils] using lib=jimp`);
libLogged = true;
} catch {
}
}
return loadedJimp2;
} catch {
loadedJimp2 = null;
return null;
}
}
function isPng(buf) {
try {
return buf && buf.length >= 8 && buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71 && buf[4] === 13 && buf[5] === 10 && buf[6] === 26 && buf[7] === 10;
} catch {
return false;
}
}
function jimpHasFn(obj, name) {
try {
return obj && typeof obj[name] === "function";
} catch {
return false;
}
}
async function jimpResizeCompat(img, w, h) {
if (!jimpHasFn(img, "resize")) {
throw new Error("Jimp resize not available");
}
let lastError;
try {
await img.resize({ w, h });
return;
} catch (e) {
lastError = e;
}
try {
await img.resize(w, h);
return;
} catch (e) {
lastError = e;
}
throw new Error(
`Jimp resize failed for both API variants: ${lastError?.message || String(lastError)}`
);
}
async function jimpCropCompat(img, x, y, w, h) {
if (!jimpHasFn(img, "crop")) {
throw new Error("Jimp crop not available");
}
let lastError;
try {
await img.crop({ x, y, w, h });
return;
} catch (e) {
lastError = e;
}
try {
await img.crop(x, y, w, h);
return;
} catch (e) {
lastError = e;
}
throw new Error(
`Jimp crop failed for both API variants: ${lastError?.message || String(lastError)}`
);
}
async function jimpAutoRotate(img) {
try {
if (jimpHasFn(img, "exifRotate")) {
await img.exifRotate();
} else if (jimpHasFn(img, "rotate")) {
}
} catch (e) {
try {
console.error(`[imageUtils] Jimp EXIF rotation failed: ${String(e)}`);
} catch {
}
}
}
async function jimpGetBufferCompat(img, mime, options) {
let lastError;
try {
if (jimpHasFn(img, "getBufferAsync")) {
return await img.getBufferAsync(mime, options);
}
} catch (e) {
lastError = e;
}
try {
if (jimpHasFn(img, "getBuffer")) {
return await img.getBuffer(mime, options);
}
} catch (e) {
lastError = e;
}
throw new Error(
`Jimp getBuffer failed for both API variants (mime=${mime}): ${lastError?.message || String(lastError)}`
);
}
async function getSize(buffer) {
const sharp = await tryLoadSharp2();
if (sharp) {
try {
logOnce(`[imageUtils.getSize] using Sharp`);
const oriented = await sharp(buffer).rotate().png().toBuffer();
const meta = await sharp(oriented).metadata();
return { width: meta.width || 0, height: meta.height || 0 };
} catch (e) {
console.warn(`[imageUtils.getSize] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.getSize] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
const w = typeof img.getWidth === "function" ? img.getWidth() : typeof img.width === "number" ? img.width : img.bitmap?.width || 0;
const h = typeof img.getHeight === "function" ? img.getHeight() : typeof img.height === "number" ? img.height : img.bitmap?.height || 0;
return { width: w || 0, height: h || 0 };
}
return { width: 0, height: 0 };
}
async function toPng(buffer) {
if (isPng(buffer)) return buffer;
const sharp = await tryLoadSharp2();
if (sharp) {
try {
logOnce(`[imageUtils.toPng] using Sharp`);
return await sharp(buffer).rotate().png().toBuffer();
} catch (e) {
console.warn(`[imageUtils.toPng] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.toPng] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
return await jimpGetBufferCompat(img, "image/png");
}
return buffer;
}
async function resizeAndEncode(buffer, format, quality, width, _maxBytes) {
const sharp = await tryLoadSharp2();
if (sharp) {
try {
logOnce(`[imageUtils.resizeAndEncode] using Sharp`);
const pipeline = sharp(buffer).rotate().resize({ width, fit: "inside", withoutEnlargement: false });
const { data, info } = await (format === "jpeg" ? pipeline.jpeg({
quality: clampQuality(quality),
mozjpeg: true,
chromaSubsampling: "4:2:0",
progressive: true
}) : pipeline.webp({ quality: clampQuality(quality), effort: 4 })).toBuffer({ resolveWithObject: true });
const outW = typeof info.width === "number" ? info.width : width;
const outH = typeof info.height === "number" ? info.height : Math.round(width * 0.75);
return { data, width: outW, height: outH };
} catch (e) {
console.warn(`[imageUtils.resizeAndEncode] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.resizeAndEncode] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
const origW = typeof img.getWidth === "function" ? img.getWidth() : typeof img.width === "number" ? img.width : img.bitmap?.width || 0;
const origH = typeof img.getHeight === "function" ? img.getHeight() : typeof img.height === "number" ? img.height : img.bitmap?.height || 0;
const scale = width / Math.max(1, origW);
const outW = Math.max(1, Math.round(origW * scale));
const outH = Math.max(1, Math.round(origH * scale));
await jimpResizeCompat(img, outW, outH);
const q = clampQuality(quality);
if (format === "jpeg") {
const data = await jimpGetBufferCompat(img, "image/jpeg", { quality: q });
return { data, width: outW, height: outH };
} else {
try {
const data = await jimpGetBufferCompat(img, "image/webp", {
quality: q
});
return { data, width: outW, height: outH };
} catch {
const data = await jimpGetBufferCompat(img, "image/jpeg", {
quality: q
});
return { data, width: outW, height: outH };
}
}
}
return { data: buffer, width, height: Math.round(width * 0.75) };
}
async function resizeAndEncodeByHeight(buffer, format, quality, maxHeight) {
const sharp = await tryLoadSharp2();
if (sharp) {
try {
logOnce(`[imageUtils.resizeAndEncodeByHeight] using Sharp`);
const pipeline = sharp(buffer).rotate().resize({ height: maxHeight, fit: "inside", withoutEnlargement: false });
const { data, info } = await (format === "jpeg" ? pipeline.jpeg({
quality: clampQuality(quality),
mozjpeg: true,
chromaSubsampling: "4:2:0",
progressive: true
}) : pipeline.webp({ quality: clampQuality(quality), effort: 4 })).toBuffer({ resolveWithObject: true });
const outW = typeof info.width === "number" ? info.width : Math.round(maxHeight * 1.33);
const outH = typeof info.height === "number" ? info.height : maxHeight;
return { data, width: outW, height: outH };
} catch (e) {
console.warn(`[imageUtils.resizeAndEncodeByHeight] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.resizeAndEncodeByHeight] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
const origW = typeof img.getWidth === "function" ? img.getWidth() : typeof img.width === "number" ? img.width : img.bitmap?.width || 0;
const origH = typeof img.getHeight === "function" ? img.getHeight() : typeof img.height === "number" ? img.height : img.bitmap?.height || 0;
const scale = maxHeight / Math.max(1, origH);
const outH = Math.max(1, Math.round(maxHeight));
const outW = Math.max(1, Math.round(origW * scale));
await jimpResizeCompat(img, outW, outH);
const q = clampQuality(quality);
if (format === "jpeg") {
const data = await jimpGetBufferCompat(img, "image/jpeg", { quality: q });
return { data, width: outW, height: outH };
} else {
try {
const data = await jimpGetBufferCompat(img, "image/webp", {
quality: q
});
return { data, width: outW, height: outH };
} catch {
const data = await jimpGetBufferCompat(img, "image/jpeg", {
quality: q
});
return { data, width: outW, height: outH };
}
}
}
return {
data: buffer,
width: Math.round(maxHeight * 1.33),
height: maxHeight
};
}
async function resizeAndEncodeBySum(buffer, format, quality, maxSum) {
const sharp = await tryLoadSharp2();
const calcDims = (origW, origH) => {
let w = Math.max(1, Math.round(origW));
let h = Math.max(1, Math.round(origH));
const currentSum = w + h;
if (currentSum > maxSum) {
const scale = maxSum / currentSum;
w = Math.max(1, Math.round(w * scale));
h = Math.max(1, Math.round(h * scale));
}
return { w, h };
};
if (sharp) {
try {
logOnce(`[imageUtils.resizeAndEncodeBySum] using Sharp`);
const metadata = await sharp(buffer).metadata();
const rotatesDimensions = metadata.orientation !== void 0 && metadata.orientation >= 5 && metadata.orientation <= 8;
const origW = rotatesDimensions ? metadata.height ?? 640 : metadata.width ?? 640;
const origH = rotatesDimensions ? metadata.width ?? 640 : metadata.height ?? 640;
const { w, h } = calcDims(origW, origH);
const pipeline = sharp(buffer).rotate().resize({ width: w, height: h, fit: "inside", withoutEnlargement: true });
const { data, info } = await (format === "jpeg" ? pipeline.jpeg({
quality: clampQuality(quality),
mozjpeg: true,
chromaSubsampling: "4:2:0",
progressive: true
}) : pipeline.webp({ quality: clampQuality(quality), effort: 4 })).toBuffer({ resolveWithObject: true });
const outW = typeof info.width === "number" ? info.width : w;
const outH = typeof info.height === "number" ? info.height : h;
return { data, width: outW, height: outH };
} catch (e) {
console.warn(`[imageUtils.resizeAndEncodeBySum] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.resizeAndEncodeBySum] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
const origW = typeof img.getWidth === "function" ? img.getWidth() : typeof img.width === "number" ? img.width : img.bitmap?.width || 640;
const origH = typeof img.getHeight === "function" ? img.getHeight() : typeof img.height === "number" ? img.height : img.bitmap?.height || 640;
const { w, h } = calcDims(origW, origH);
await jimpResizeCompat(img, w, h);
const q = clampQuality(quality);
if (format === "jpeg") {
const data = await jimpGetBufferCompat(img, "image/jpeg", { quality: q });
return { data, width: w, height: h };
} else {
try {
const data = await jimpGetBufferCompat(img, "image/webp", {
quality: q
});
return { data, width: w, height: h };
} catch {
const data = await jimpGetBufferCompat(img, "image/jpeg", {
quality: q
});
return { data, width: w, height: h };
}
}
}
return {
data: buffer,
width: Math.round(maxSum / 2),
height: Math.round(maxSum / 2)
};
}
async function resizeInsideToPng(buffer, targetW, targetH) {
const sharp = await tryLoadSharp2();
const w = Math.max(1, Math.round(targetW));
const h = Math.max(1, Math.round(targetH));
if (sharp) {
try {
logOnce(`[imageUtils.resizeInsideToPng] using Sharp`);
return await sharp(buffer).rotate().resize({ width: w, height: h, fit: "inside", withoutEnlargement: false }).png().toBuffer();
} catch (e) {
console.warn(`[imageUtils.resizeInsideToPng] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.resizeInsideToPng] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
const origW = typeof img.getWidth === "function" ? img.getWidth() : typeof img.width === "number" ? img.width : img.bitmap?.width || 0;
const origH = typeof img.getHeight === "function" ? img.getHeight() : typeof img.height === "number" ? img.height : img.bitmap?.height || 0;
const scale = Math.min(w / Math.max(1, origW), h / Math.max(1, origH));
const newW = Math.max(1, Math.round(origW * scale));
const newH = Math.max(1, Math.round(origH * scale));
await jimpResizeCompat(img, newW, newH);
return await jimpGetBufferCompat(img, "image/png");
}
return buffer;
}
async function resizeFillToPng(buffer, targetW, targetH) {
const sharp = await tryLoadSharp2();
const w = Math.max(1, Math.round(targetW));
const h = Math.max(1, Math.round(targetH));
if (sharp) {
try {
logOnce(`[imageUtils.resizeFillToPng] using Sharp`);
return await sharp(buffer).rotate().resize({ width: w, height: h, fit: "fill" }).png().toBuffer();
} catch (e) {
console.warn(`[imageUtils.resizeFillToPng] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.resizeFillToPng] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
await jimpResizeCompat(img, w, h);
return await jimpGetBufferCompat(img, "image/png");
}
return buffer;
}
async function resizeCoverToPng(buffer, targetW, targetH) {
const sharp = await tryLoadSharp2();
const w = Math.max(1, Math.round(targetW));
const h = Math.max(1, Math.round(targetH));
if (sharp) {
try {
logOnce(`[imageUtils.resizeCoverToPng] using Sharp`);
return await sharp(buffer).rotate().resize({ width: w, height: h, fit: "cover", position: "centre" }).png().toBuffer();
} catch (e) {
console.warn(`[imageUtils.resizeCoverToPng] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.resizeCoverToPng] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
const origW = typeof img.getWidth === "function" ? img.getWidth() : typeof img.width === "number" ? img.width : img.bitmap?.width || 0;
const origH = typeof img.getHeight === "function" ? img.getHeight() : typeof img.height === "number" ? img.height : img.bitmap?.height || 0;
if (!origW || !origH) {
await jimpResizeCompat(img, w, h);
return await jimpGetBufferCompat(img, "image/png");
}
const scale = Math.max(w / origW, h / origH);
const newW = Math.max(1, Math.round(origW * scale));
const newH = Math.max(1, Math.round(origH * scale));
await jimpResizeCompat(img, newW, newH);
const x = Math.max(0, Math.floor((newW - w) / 2));
const y = Math.max(0, Math.floor((newH - h) / 2));
await jimpCropCompat(img, x, y, w, h);
return await jimpGetBufferCompat(img, "image/png");
}
return buffer;
}
async function cropToPng(buffer, opts) {
const sharp = await tryLoadSharp2();
if (sharp) {
try {
logOnce(`[imageUtils.cropToPng] using Sharp`);
const oriented = await sharp(buffer).rotate().png().toBuffer();
const meta = await sharp(oriented).metadata();
const imgW = meta.width ?? 0;
const imgH = meta.height ?? 0;
const x = Math.floor(imgW * opts.left / 100);
const xEnd = Math.ceil(imgW * (1 - opts.right / 100));
const y = Math.floor(imgH * opts.top / 100);
const yEnd = Math.ceil(imgH * (1 - opts.bottom / 100));
const cropW = Math.max(1, xEnd - x);
const cropH = Math.max(1, yEnd - y);
return await sharp(oriented).extract({ left: x, top: y, width: cropW, height: cropH }).png().toBuffer();
} catch (e) {
console.warn(`[imageUtils.cropToPng] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
logOnce(`[imageUtils.cropToPng] using Jimp`);
const img = await Jimp.read(buffer);
await jimpAutoRotate(img);
const imgW = typeof img.getWidth === "function" ? img.getWidth() : typeof img.width === "number" ? img.width : img.bitmap?.width || 0;
const imgH = typeof img.getHeight === "function" ? img.getHeight() : typeof img.height === "number" ? img.height : img.bitmap?.height || 0;
const x = Math.floor(imgW * opts.left / 100);
const xEnd = Math.ceil(imgW * (1 - opts.right / 100));
const y = Math.floor(imgH * opts.top / 100);
const yEnd = Math.ceil(imgH * (1 - opts.bottom / 100));
const cropW = Math.max(1, xEnd - x);
const cropH = Math.max(1, yEnd - y);
await jimpCropCompat(img, x, y, cropW, cropH);
return await jimpGetBufferCompat(img, "image/png");
}
return buffer;
}
function clampQuality(q) {
if (!Number.isFinite(q)) return 80;
q = Math.round(q);
if (q < 1) q = 1;
if (q > 100) q = 100;
return q;
}
async function decodeToRgba(buffer) {
const sharp = await tryLoadSharp2();
if (sharp) {
try {
const { data, info } = await sharp(buffer).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
return { data: new Uint8Array(data), width: info.width, height: info.height };
} catch (e) {
console.warn(`[imageUtils.decodeToRgba] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp && typeof Jimp.read === "function") {
const img = await Jimp.read(buffer);
const bm = img.bitmap;
return { data: new Uint8Array(bm.data), width: bm.width, height: bm.height };
}
throw new Error("decodeToRgba: neither sharp nor jimp is available");
}
async function encodeRgbaToPng(data, width, height) {
const sharp = await tryLoadSharp2();
if (sharp) {
try {
return await sharp(Buffer.from(data.buffer, data.byteOffset, data.byteLength), {
raw: { width, height, channels: 4 }
}).png().toBuffer();
} catch (e) {
console.warn(`[imageUtils.encodeRgbaToPng] Sharp failed, falling back to Jimp: ${e instanceof Error ? e.message : String(e)}`);
}
}
const Jimp = await tryLoadJimp2();
if (Jimp) {
const img = new Jimp({ width, height, data: Buffer.from(data) });
return await jimpGetBufferCompat(img, "image/png");
}
throw new Error("encodeRgbaToPng: neither sharp nor jimp is available");
}
// src/media-promotion-core/image.ts
function getDefaultPreviewOptions() {
return {
maxDim: drawthingsLimits.previewMaxSum,
quality: drawthingsLimits.previewQuality,
mode: "sum",
maxSum: drawthingsLimits.previewMaxSum
};
}
function isAllowedOriginalExt(p) {
return /(\.(png|jpe?g|webp|mov))$/i.test(p);
}
function guessExtForOriginal(maybePath) {
const e = path9.extname(maybePath).toLowerCase();
if (e === ".png" || e === ".jpg" || e === ".jpeg" || e === ".webp") return e;
return ".png";
}
function previewFilenameFrom(originalFilename) {
const hasPrefix = originalFilename.toLowerCase().startsWith("preview-");
const base = hasPrefix ? originalFilename : `preview-${originalFilename}`;
return base.replace(/\.(png|jpg|jpeg|webp|gif)$/i, ".jpg").replace(/ /g, "_");
}
async function encodeJpegPreviewFromBuffer(srcBuf, opts) {
const q = Math.max(1, Math.min(100, opts.quality));
if (opts.mode === "height") {
const targetH = Math.max(1, Math.round(opts.maxDim));
const { data: data2, width: width2, height: height2 } = await resizeAndEncodeByHeight(
srcBuf,
"jpeg",
q,
targetH
);
return { data: data2, width: width2, height: height2 };
}
if (opts.mode === "sum" && opts.maxSum) {
const { data: data2, width: width2, height: height2 } = await resizeAndEncodeBySum(
srcBuf,
"jpeg",
q,
opts.maxSum
);
return { data: data2, width: width2, height: height2 };
}
const maxW = Math.max(1, Math.round(opts.maxDim));
const { data, width, height } = await resizeAndEncode(
srcBuf,
"jpeg",
q,
maxW,
Number.MAX_SAFE_INTEGER
);
return { data, width, height };
}
async function encodeJpegPreview(srcAbs, dstAbs, opts) {
const srcBuf = await fs9.promises.readFile(srcAbs);
const { data } = await encodeJpegPreviewFromBuffer(srcBuf, opts);
await fs9.promises.writeFile(dstAbs, data);
}
function isPreviewOptions(x) {
return typeof x === "object" && x !== null && "maxDim" in x && typeof x.maxDim === "number";
}
function normalizeToPreviewOptions(input) {
if (isPreviewOptions(input)) return input;
return {
maxDim: input.maxWidth ?? 640,
quality: input.quality ?? 80,
mode: input.maxSum ? "sum" : "width",
maxSum: input.maxSum
};
}
async function generatePreview(srcAbs, chatWd, optsInput, options) {
const debug = options?.debug ?? false;
const opts = normalizeToPreviewOptions(optsInput);
if (!fs9.existsSync(srcAbs)) {
if (debug) console.warn(`[Preview] Source not found: ${srcAbs}`);
return null;
}
const originalFilename = path9.basename(srcAbs);
const previewFilename = options?.customFilename ?? previewFilenameFrom(originalFilename);
const previewAbs = path9.join(chatWd, previewFilename);
if (!options?.force && fs9.existsSync(previewAbs)) {
if (debug) console.info(`[Preview] Exists, skipping: ${previewFilename}`);
return previewFilename;
}
try {
await encodeJpegPreview(srcAbs, previewAbs, opts);
if (debug) console.info(`[Preview] Generated: ${previewFilename}`);
return previewFilename;
} catch (e) {
if (debug)
console.warn(
`[Preview] Failed for ${originalFilename}:`,
e.message
);
throw e;
}
}
async function generatePreviewFromBuffer(srcBuf, chatWd, originalFilename, optsInput, options) {
const debug = options?.debug ?? false;
const opts = normalizeToPreviewOptions(optsInput);
const previewFilename = options?.customFilename ?? previewFilenameFrom(originalFilename);
const previewAbs = path9.join(chatWd, previewFilename);
if (!options?.force && fs9.existsSync(previewAbs)) {
if (debug) console.info(`[Preview] Exists, skipping: ${previewFilename}`);
try {
const existingData = await fs9.promises.readFile(previewAbs);
return {
previewFilename,
previewAbs,
data: existingData,
width: 0,
// Unknown for existing file
height: 0
};
} catch {
}
}
try {
const { data, width, height } = await encodeJpegPreviewFromBuffer(
srcBuf,
opts
);
await fs9.promises.writeFile(previewAbs, data);
if (debug)
console.info(`[Preview] Generated from buffer: ${previewFilename}`);
return {
previewFilename,
previewAbs,
data,
width,
height
};
} catch (e) {
if (debug)
console.warn(
`[Preview] Failed for ${originalFilename}:`,
e.message
);
throw e;
}
}
// src/helpers/toolResultImageHarvest.ts
function canonicalizeRef(ref) {
let s = String(ref || "").trim();
s = s.replace(/[)\],.;]+$/g, "");
s = s.replace(/^"(.+)"$/g, "$1");
s = s.replace(/^'(.+)'$/g, "$1");
return s.trim();
}
function isAllowedUrl(url) {
if (/^https:\/\//i.test(url)) return true;
if (/^http:\/\//i.test(url)) {
try {
const host = new URL(url).hostname;
return host === "localhost" || host === "127.0.0.1" || host === "::1";
} catch {
return false;
}
}
if (isProjectUri(url)) return true;
return false;
}
function detectImageMagic(buf) {
if (!buf || buf.length < 12) return null;
if (buf.length >= 8 && buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71 && buf[4] === 13 && buf[5] === 10 && buf[6] === 26 && buf[7] === 10)
return "png";
if (buf[0] === 255 && buf[1] === 216 && buf[2] === 255) return "jpeg";
if (buf[0] === 71 && buf[1] === 73 && buf[2] === 70 && buf[3] === 56)
return "gif";
if (buf[0] === 82 && buf[1] === 73 && buf[2] === 70 && buf[3] === 70 && buf[8] === 87 && buf[9] === 69 && buf[10] === 66 && buf[11] === 80)
return "webp";
return null;
}
async function pathExists(p) {
try {
await fs10.promises.access(p, fs10.constants.F_OK);
return true;
} catch {
return false;
}
}
async function fetchWithLimits(url, timeoutMs, maxBytes) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetch(url, {
method: "GET",
redirect: "follow",
signal: controller.signal
});
if (!res.ok) {
throw new Error(`HTTP ${res.status} ${res.statusText}`);
}
const cl = res.headers.get("content-length");
if (cl) {
const n = Number(cl);
if (Number.isFinite(n) && n > maxBytes) {
throw new Error(`content-length ${n} exceeds maxBytes ${maxBytes}`);
}
}
const body = res.body;
if (!body) {
const ab = await res.arrayBuffer();
const buf = Buffer.from(ab);
if (buf.length > maxBytes) {
throw new Error(
`response size ${buf.length} exceeds maxBytes ${maxBytes}`
);
}
return buf;
}
const reader = body.getReader();
const chunks = [];
let total = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) {
total += value.byteLength;
if (total > maxBytes) {
try {
controller.abort();
} catch {
}
throw new Error(`response size exceeds maxBytes ${maxBytes}`);
}
chunks.push(value);
}
}
return Buffer.concat(chunks.map((c) => Buffer.from(c)));
} finally {
clearTimeout(timeout);
}
}
function extractUrlsFromText(text) {
const out = [];
const re = /https:\/\/[\w\-./:%?#@!$&'()*+,;=]+/gi;
let m;
while ((m = re.exec(text)) !== null) {
out.push(m[0]);
}
return out;
}
function deepParseMaybeJson(input, maxDepth = 4) {
let cur = input;
for (let depth = 0; depth < maxDepth; depth++) {
if (typeof cur !== "string") return cur;
const t = cur.trim();
if (!(t.startsWith("{") || t.startsWith("[") || t.startsWith('"'))) return cur;
try {
cur = JSON.parse(t);
} catch {
return cur;
}
}
return cur;
}
function parseToolResultPayload(raw, validator) {
const segments = toolResultToTextSegments(raw);
for (const seg of segments) {
const parsed = deepParseMaybeJson(seg, 4);
if (validator(parsed)) {
return parsed;
}
}
return null;
}
function extractImageUrlsStructured(value) {
const urls = [];
const v = value;
if (v && typeof v === "object") {
if (Array.isArray(v.items)) {
for (const it of v.items) {
const u = it?.properties?.url;
if (typeof u === "string" && u.trim()) urls.push(u);
}
}
}
return urls;
}
function extractCandidatesStructured(value) {
const out = [];
const v = value;
if (!v || typeof v !== "object") return out;
if (!Array.isArray(v.items)) return out;
for (const it of v.items) {
const url = typeof it?.properties?.url === "string" ? String(it.properties.url) : "";
if (!url.trim()) continue;
const cand = { url: url.trim() };
if (typeof it?.title === "string" && it.title.trim()) cand.title = it.title;
if (typeof it?.confidence === "string" && it.confidence.trim()) {
cand.confidence = it.confidence;
}
const w = it?.properties?.width;
const h = it?.properties?.height;
if (typeof w === "number" && Number.isFinite(w)) cand.width = w;
if (typeof h === "number" && Number.isFinite(h)) cand.height = h;
if (typeof it?.url === "string" && it.url.trim()) cand.pageUrl = it.url;
if (typeof it?.page_fetched === "string" && it.page_fetched.trim()) {
cand.pageFetched = it.page_fetched;
}
const thumb = it?.thumbnail?.url;
if (typeof thumb === "string" && thumb.trim()) cand.thumbnailUrl = thumb;
out.push(cand);
}
return out;
}
function dedupePreserveOrder(items) {
const seen = /* @__PURE__ */ new Set();
const out = [];
for (const it of items) {
const c = canonicalizeRef(it);
if (!c) continue;
if (seen.has(c)) continue;
seen.add(c);
out.push(c);
}
return out;
}
function dedupeCandidatesPreserveOrder(items) {
const seen = /* @__PURE__ */ new Set();
const out = [];
for (const it of items) {
const u = canonicalizeRef(it?.url);
if (!u) continue;
if (seen.has(u)) continue;
seen.add(u);
out.push({ ...it, url: u });
}
return out;
}
function toolResultToTextSegments(toolResult) {
const rawText = typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult);
try {
const parsed = JSON.parse(rawText);
if (Array.isArray(parsed)) {
const parts = [];
for (const p of parsed) {
if (p && typeof p === "object" && typeof p.text === "string") {
parts.push(String(p.text));
}
}
if (parts.length) return parts;
}
} catch {
}
return [rawText];
}
function extractImageRefsFromToolResult(toolResult) {
const segments = toolResultToTextSegments(toolResult);
const urls = [];
for (const seg of segments) {
const deep = deepParseMaybeJson(seg, 4);
urls.push(...extractImageUrlsStructured(deep));
if (typeof deep === "string") {
urls.push(...extractUrlsFromText(deep));
} else {
const stack = [
{ v: deep, depth: 0 }
];
const maxDepth = 4;
let nodes = 0;
const maxNodes = 2e3;
while (stack.length) {
const { v, depth } = stack.pop();
nodes++;
if (nodes > maxNodes) break;
if (typeof v === "string") {
urls.push(...extractUrlsFromText(v));
} else if (v && typeof v === "object" && depth < maxDepth) {
if (Array.isArray(v)) {
for (const it of v) stack.push({ v: it, depth: depth + 1 });
} else {
for (const k of Object.keys(v)) {
stack.push({ v: v[k], depth: depth + 1 });
}
}
}
}
}
}
return dedupePreserveOrder(urls);
}
function extractToolResultImageCandidates(toolResult) {
const segments = toolResultToTextSegments(toolResult);
const candidates = [];
const urlFallbacks = [];
for (const seg of segments) {
const deep = deepParseMaybeJson(seg, 4);
candidates.push(...extractCandidatesStructured(deep));
if (typeof deep === "string") {
urlFallbacks.push(...extractUrlsFromText(deep));
} else {
const stack = [
{ v: deep, depth: 0 }
];
const maxDepth = 4;
let nodes = 0;
const maxNodes = 2e3;
while (stack.length) {
const { v, depth } = stack.pop();
nodes++;
if (nodes > maxNodes) break;
if (typeof v === "string") {
urlFallbacks.push(...extractUrlsFromText(v));
} else if (v && typeof v === "object" && depth < maxDepth) {
if (Array.isArray(v)) {
for (const it of v) stack.push({ v: it, depth: depth + 1 });
} else {
for (const k of Object.keys(v)) {
stack.push({ v: v[k], depth: depth + 1 });
}
}
}
}
}
}
const structured = dedupeCandidatesPreserveOrder(candidates);
const structuredUrls = new Set(structured.map((c) => c.url));
const fallback = dedupePreserveOrder(urlFallbacks).filter((u) => !structuredUrls.has(canonicalizeRef(u))).map((u) => ({ url: canonicalizeRef(u) }));
return [...structured, ...fallback].filter((c) => !!c.url);
}
async function materializeToolResultImageToFiles(input) {
const timeoutMs = typeof input.timeoutMs === "number" && input.timeoutMs > 0 ? Math.floor(input.timeoutMs) : 1e4;
const maxBytes = typeof input.maxBytes === "number" && input.maxBytes > 0 ? Math.floor(input.maxBytes) : 15 * 1024 * 1024;
const ref = canonicalizeRef(input.url);
if (!isAllowedUrl(ref)) {
throw new Error("scheme not allowed (https or project:// only)");
}
let buf;
if (isProjectUri(ref)) {
const resolved = await resolveProjectUri(ref);
if (!resolved) {
throw new Error("failed to extract thumbnail from project file");
}
buf = resolved;
} else {
buf = await fetchWithLimits(ref, timeoutMs, maxBytes);
}
const magic = detectImageMagic(buf);
if (!magic) {
throw new Error("not a supported image (magic bytes)");
}
const bytesHash = crypto.createHash("sha256").update(buf).digest("hex");
const png = await toPng(buf);
await fs10.promises.writeFile(input.originalAbs, png);
const chatWd = path10.dirname(input.originalAbs);
await generatePreview(input.originalAbs, chatWd, input.preview, {
customFilename: path10.basename(input.previewAbs),
force: true
// Always generate (we just downloaded the original)
});
return { bytesHash };
}
function shortHexSha256(input, chars = 12) {
const h = crypto.createHash("sha256").update(input).digest("hex");
return h.slice(0, Math.max(4, Math.min(64, chars)));
}
async function harvestToolResultImages(input) {
const debug = !!input.debug;
const maxImages = Math.max(0, Math.floor(input.maxImages));
const timeoutMs = typeof input.timeoutMs === "number" && input.timeoutMs > 0 ? Math.floor(input.timeoutMs) : 1e4;
const maxBytes = typeof input.maxBytes === "number" && input.maxBytes > 0 ? Math.floor(input.maxBytes) : 15 * 1024 * 1024;
const skipped = [];
const harvested = [];
if (!maxImages) return { harvested, skipped };
if (!input.chatWd || !String(input.chatWd).trim()) {
return {
harvested,
skipped: [{ ref: "(chatWd)", reason: "missing chatWd" }]
};
}
const refs = extractImageRefsFromToolResult(input.toolResult);
if (debug) {
console.info(
`[ToolResultHarvest] tool=${input.toolName} extractedRefs=${refs.length} cap=${maxImages}`
);
}
const capped = refs.slice(0, maxImages);
await fs10.promises.mkdir(input.chatWd, { recursive: true });
for (const rawRef of capped) {
const ref = canonicalizeRef(rawRef);
if (!ref) continue;
if (!isAllowedUrl(ref)) {
skipped.push({ ref, reason: "scheme not allowed (https only)" });
continue;
}
const urlHash = shortHexSha256(ref, 12);
const ts = `h${urlHash}Z`;
const vNum = 1;
const originalBaseName = `generated-image-${ts}-v${vNum}.png`;
const previewBaseName = `preview-generated-image-${ts}-v${vNum}.jpg`;
const originalAbs = path10.join(input.chatWd, originalBaseName);
const previewAbs = path10.join(input.chatWd, previewBaseName);
const originalOk = await pathExists(originalAbs);
const previewOk = await pathExists(previewAbs);
if (originalOk && previewOk) {
harvested.push({
originalBaseName,
previewBaseName,
sourceRef: ref
});
continue;
}
try {
const { bytesHash } = await materializeToolResultImageToFiles({
url: ref,
originalAbs,
previewAbs,
preview: input.preview,
timeoutMs,
maxBytes
});
harvested.push({
originalBaseName,
previewBaseName,
sourceRef: ref,
bytesHash
});
if (debug) {
console.info(
`[ToolResultHarvest] saved ${originalBaseName} + ${previewBaseName} (tool=${input.toolName})`
);
}
} catch (e) {
skipped.push({
ref,
reason: e?.message || String(e)
});
continue;
}
}
return { harvested, skipped };
}
// src/services/toolParams/pictures.ts
function renderBraveResultsTable(items) {
if (items.length === 0) return "";
const toDisplayUrl = (u) => {
const s = typeof u === "string" ? u.trim() : "";
if (!s) return "";
if (/^https?:\/\//i.test(s) || /^file:\/\//i.test(s)) return s;
if (s.startsWith("./") || s.startsWith("/")) return s;
return `./${s}`;
};
const escapeCell = (s) => String(s ?? "").replace(/\|/g, "\\|").replace(/[\r\n]+/g, " ").trim();
const sourceLabel = (u) => {
try {
if (!/^https?:\/\//i.test(u)) return "source";
const host = new URL(u).host;
return host || "source";
} catch {
return "source";
}
};
const header = "| Preview | ID / Title | Source |\n|---|---|---|";
const rows = items.map((item, i) => {
const label = typeof item.index === "number" && Number.isFinite(item.index) ? `p${item.index}` : `p${i + 1}`;
const previewUrl = toDisplayUrl(item.url);
const linkTarget = (
// Prefer the external provenance link (HTTP) when present.
toDisplayUrl(item.sourceUrl) || // Fallbacks: if we don't have provenance, link to local original.
toDisplayUrl(item.filename) || // Last resort: link to whatever we have.
previewUrl
);
const previewImg = previewUrl ? `` : "";
const preview = previewImg && linkTarget ? `[${previewImg}](${linkTarget})` : previewImg;
const titleText = escapeCell(item.title ?? "");
const title = titleText ? `\`${label}\` ${titleText}` : `\`${label}\``;
const sourceUrl = typeof item.sourceUrl === "string" && item.sourceUrl.trim() ? item.sourceUrl.trim() : "";
const source = sourceUrl ? `[${escapeCell(sourceLabel(sourceUrl))}](${toDisplayUrl(sourceUrl)})` : "";
return `| ${preview} | ${title} | ${source} |`;
});
return [header, ...rows].join("\n");
}
function renderDrawThingsIndexResultsTable(items) {
if (items.length === 0) return "";
const escapeCell = (s) => String(s ?? "").replace(/\|/g, "\\|").replace(/[\r\n]+/g, " ").trim();
const hasAnyPreview = items.some(
(item) => item.filename && item.filename.trim() || item.url && item.url.trim()
);
if (hasAnyPreview) {
const header = "| Preview | ID / Generation Data |\n|---|---|";
const markdownUrl = (value) => /[\s()]/.test(value) && !/^<.*>$/.test(value) ? `<${value}>` : value;
const rows = items.map((item, i) => {
const label = typeof item.index === "number" && Number.isFinite(item.index) ? `p${item.index}` : `p${i + 1}`;
const originalPath = item.filename || "";
const previewPath = item.url || "";
const imgSrc = previewPath || originalPath;
const linkTarget = originalPath || previewPath;
const previewImg = imgSrc ? `})` : "";
const videoLinkTarget = item.videoPath && item.videoPath.trim() ? item.videoPath.trim() : void 0;
const effectiveLinkTarget = videoLinkTarget ?? linkTarget;
const preview = previewImg && effectiveLinkTarget && effectiveLinkTarget !== imgSrc ? `[${previewImg}](${markdownUrl(effectiveLinkTarget)})` : previewImg;
const metadataCell = buildMetadataCell(item, label, escapeCell);
return `| ${preview} | ${metadataCell} |`;
});
return [header, ...rows, ""].join("\n");
} else {
const header = "| Index Image Results |\n|---|";
const rows = items.map((item, i) => {
const label = typeof item.index === "number" && Number.isFinite(item.index) ? `p${item.index}` : `p${i + 1}`;
const metadataCell = buildMetadataCell(item, label, escapeCell);
return `| ${metadataCell} |`;
});
return [header, ...rows, ""].join("\n");
}
}
function buildMetadataCell(item, label, escapeCell) {
const parts = [`\`${label}\``];
if (item.prompt) {
parts.push(`**Prompt:** ${escapeCell(item.prompt)}`);
}
if (typeof item.numFrames === "number" && item.numFrames > 1) {
parts.push(`**Type:** video (${item.numFrames} frames)`);
}
if (typeof item.width === "number" || typeof item.height === "number") {
const w = typeof item.width === "number" && Number.isFinite(item.width) ? item.width : 0;
const h = typeof item.height === "number" && Number.isFinite(item.height) ? item.height : 0;
parts.push(`**Size:** ${w}\xD7${h}`);
if (typeof item.numFrames === "number" && item.numFrames > 1) {
parts.push(`**Frames:** ${item.numFrames}`);
}
}
if (item.model) {
const display = item.modelDisplay && item.modelDisplay.trim() ? item.modelDisplay : item.model;
parts.push(`**Model:** ${escapeCell(display)}`);
}
if (item.modelMeta) {
const mm = item.modelMeta;
if (mm.model_used) {
parts.push(`**Model used:** ${escapeCell(mm.model_used)}`);
}
if (mm.model_family) {
parts.push(`**Family:** ${escapeCell(mm.model_family)}`);
}
const customLabels = Array.isArray(mm.custom_config_labels) ? mm.custom_config_labels.map((s) => typeof s === "string" ? s.trim() : "").filter((s) => !!s) : [];
if (customLabels.length) {
parts.push(`**Custom configs:** ${customLabels.map(escapeCell).join(", ")}`);
}
}
if (item.loras && item.loras.length > 0) {
parts.push(`**LoRAs:** ${item.loras.map((l) => escapeCell(l)).join(", ")}`);
}
if (item.tags && item.tags.length > 0) {
parts.push(`**Tags:** ${item.tags.map((tag) => escapeCell(tag)).join(", ")}`);
}
if (item.matchType) {
parts.push(`**Match:** ${escapeCell(item.matchType)}`);
}
if (typeof item.score === "number") {
parts.push(`**Score:** ${item.score}`);
}
if (item.sourceInfo) {
const src = item.sourceInfo;
const srcLabel = src.type.replace(/_/g, " ");
const extractProjectName = (path34) => {
const filename = path34.split("/").pop() || "";
return filename.replace(/\.(drawthings|sqlite3|dtproj|json)$/i, "");
};
const extractFromProjectUri = (uri) => {
if (!uri.startsWith("project://")) return null;
const withoutScheme = uri.slice("project://".length);
const hashIndex = withoutScheme.lastIndexOf("#");
const projectPath = hashIndex !== -1 ? withoutScheme.slice(0, hashIndex) : withoutScheme;
return extractProjectName(projectPath);
};
const projectNameFromUri = item.filename ? extractFromProjectUri(item.filename) : null;
const srcExtra = src.chatId ? `(chat: ${escapeCell(src.chatId)})` : projectNameFromUri ? `(${escapeCell(projectNameFromUri)})` : src.projectFile ? `(${escapeCell(extractProjectName(src.projectFile))})` : src.originalName ? `(${escapeCell(extractProjectName(src.originalName))})` : src.filePath ? `(${escapeCell(extractProjectName(src.filePath))})` : "";
parts.push(`**Source:** ${srcLabel}${srcExtra ? " " + srcExtra : ""}`);
const imageType = typeof src.imageType === "string" ? src.imageType.trim() : "";
if (imageType) {
parts.push(`**Origin:** ${escapeCell(imageType)}`);
}
}
if (item.timestamp) {
parts.push(`**Timestamp:** ${escapeCell(item.timestamp)}`);
}
return parts.join(" \u2022 ");
}
function renderDefaultPictureTable(items) {
return renderBraveResultsTable(items);
}
var braveSearchExtractor = {
extractCandidates: extractToolResultImageCandidates,
actions: {
generatePreview: true,
visionPromotion: {
metadata: false,
// Pictures are NOT vision-promoted
pixel: false
}
},
renderMarkdownTable: renderBraveResultsTable
};
function isDrawThingsIndexPayload(p) {
if (!p || typeof p !== "object") return false;
const obj = p;
return Array.isArray(obj.images);
}
function extractDrawThingsIndexCandidates(raw) {
const p = parseToolResultPayload(raw, isDrawThingsIndexPayload);
if (!p) {
console.info(`[DrawThingsIndexExtractor] No valid payload found`);
return [];
}
console.info(
`[DrawThingsIndexExtractor] Found payload: images=${p.images?.length ?? 0}, totalFound=${p.totalFound ?? 0}`
);
const out = [];
const seen = /* @__PURE__ */ new Set();
for (const img of p.images ?? []) {
if (!img || typeof img !== "object") continue;
const paths = img.imagePaths ?? [];
const previews = img.httpPreviewUrls ?? [];
for (let i = 0; i < Math.max(paths.length, previews.length); i++) {
const imgPath = paths[i]?.trim() ?? "";
const previewUrl = previews[i]?.trim() ?? "";
if (!imgPath && !previewUrl) continue;
const key = imgPath || previewUrl;
if (seen.has(key)) continue;
seen.add(key);
out.push({
filename: imgPath || void 0,
url: previewUrl || void 0,
prompt: img.prompt?.trim(),
model: img.model?.trim(),
modelDisplay: img.model_display?.trim(),
modelMeta: img.model_meta,
loras: img.loras,
tags: img.tags,
width: typeof img.width === "number" ? img.width : void 0,
height: typeof img.height === "number" ? img.height : void 0,
numFrames: typeof img.numFrames === "number" && img.numFrames > 1 ? img.numFrames : void 0,
matchType: img.matchType?.trim(),
score: img.matchScore,
sourceInfo: img.sourceInfo,
timestamp: img.timestamp?.trim()
});
}
}
if (out.length > 0) {
console.info(`[DrawThingsIndexExtractor] Extracted ${out.length} candidates`);
}
return out;
}
var drawThingsIndexExtractor = {
extractCandidates: extractDrawThingsIndexCandidates,
actions: {
generatePreview: true,
// Required for project:// URIs (no httpPreviewUrl)
visionPromotion: {
metadata: false,
pixel: false
}
},
renderMarkdownTable: renderDrawThingsIndexResultsTable
};
var pictureTools = {
"mcp/brave-search-mcp/brave_image_search": braveSearchExtractor,
// NUR brave_image_search
"ceveyne/draw-things-index/index_image": drawThingsIndexExtractor,
"ceveyne/find-image/find_image": drawThingsIndexExtractor
// Add new picture tools here...
};
var PICTURE_FULL_CONFIG = {
mediaType: "picture",
allow: "only",
ssotJoin: {
source: "tool-result",
messageRole: "tool",
jsonPath: "content[].text",
extractFromSource: extractToolResultImageCandidates
},
scan: {
trigger: "on-tool-result",
scope: "current-tool-result"
},
harvesting: {
// No defaultExtractor (allow: "only")
tools: pictureTools
},
actions: {
generatePreview: true,
visionPromotion: {
metadata: true,
// Labels (p1, p2) ALWAYS included
pixel: false
// No pixel data for pictures
}
},
injectMdInAgentResponse: {
format: "markdown-table",
tableHeader: "| Preview | ID / Title | Source |\n|---|---|---|",
itemTemplate: "|  | {title} | {source} |",
labelGenerator: (item, i) => `p${item.index ?? i + 1}`
},
preview: {
generate: true,
namingPattern: "preview-picture-{hash}.jpg",
format: drawthingsLimits.previewFormat,
mimeType: "image/jpeg",
maxSum: drawthingsLimits.previewMaxSum,
quality: drawthingsLimits.previewQuality,
outputDir: "."
},
toggles: {
toggles: [
{
name: "PREVIEW_IN_CHAT",
affects: "format",
// When LM Studio already renders tool-result previews inline, don't inject our table.
transform: (previewInChat, defaultFormat) => previewInChat ? "none" : defaultFormat
}
]
}
};
var PICTURE_CONFIG = {
mediaType: "picture",
allow: "only",
tools: pictureTools
};
function getAllowlistedPictureTools() {
return Object.keys(pictureTools);
}
function renderPictureMarkdown(items) {
return renderDefaultPictureTable(items);
}
// src/services/toolParams/images.ts
function extractImageFromToolResult(raw) {
const candidates = [];
let parsed = raw;
if (typeof raw === "string") {
try {
parsed = JSON.parse(raw);
} catch {
parsed = raw;
}
}
let items;
if (Array.isArray(parsed)) {
items = parsed;
} else if (parsed && typeof parsed === "object" && Array.isArray(parsed.content)) {
items = parsed.content;
} else {
items = [parsed];
}
for (const item of items) {
if (item && typeof item === "object" && item.type === "image" && typeof item.fileName === "string") {
const fileName = item.fileName;
if (/^generated-image-\d{4}-\d{2}-\d{2}T[\d-]+Z-v\d+\.\w+$/i.test(fileName)) {
continue;
}
if (fileName.toLowerCase().startsWith("preview-")) {
continue;
}
candidates.push({ filename: fileName, index: candidates.length + 1 });
}
}
if (candidates.length === 0) {
const text = typeof raw === "string" ? raw : JSON.stringify(raw);
const base64Regex = /data:image\/[a-z]+;base64,[A-Za-z0-9+/=]+/g;
const base64Matches = text.match(base64Regex) ?? [];
for (let i = 0; i < base64Matches.length; i++) {
candidates.push({ base64: base64Matches[i], index: i + 1 });
}
}
const seen = /* @__PURE__ */ new Set();
return candidates.filter((c) => {
const key = c.filename ?? c.base64 ?? "";
if (!key || seen.has(key)) return false;
seen.add(key);
return true;
});
}
var IMAGE_FULL_CONFIG = {
mediaType: "image",
allow: "all",
ssotJoin: {
source: "tool-result",
messageRole: "tool",
jsonPath: "content[].type === 'image'",
extractFromSource: extractImageFromToolResult
},
scan: {
trigger: "on-tool-result",
scope: "current-tool-result"
},
harvesting: {
defaultExtractor: extractImageFromToolResult
// No tool-specific extractors - all tools get uniform treatment
},
actions: {
generatePreview: true,
// ALWAYS generate normalized previews
visionPromotion: {
metadata: true,
// Labels (i1, i2) ALWAYS included
pixel: true
// Base64 pixels in rolling window
}
},
injectMdInAgentResponse: {
format: "markdown-image",
labelGenerator: (item, i) => `Image i${item.index ?? i + 1}`
},
preview: {
generate: true,
namingPattern: "preview-{basename}.jpg",
format: drawthingsLimits.previewFormat,
mimeType: "image/jpeg",
maxSum: drawthingsLimits.previewMaxSum,
quality: drawthingsLimits.previewQuality,
outputDir: "."
},
toggles: {
toggles: [
{
name: "PREVIEW_IN_CHAT",
affects: "format",
transform: (previewInChat, defaultFormat) => previewInChat ? "none" : defaultFormat
}
]
}
};
var IMAGE_CONFIG = {
mediaType: "image",
allow: "all",
defaultExtractor: extractImageFromToolResult,
defaultActions: IMAGE_FULL_CONFIG.actions
// No tool-specific extractors
};
// src/services/toolParams/types.ts
function resolveActions(config, toggles) {
const actions = { ...config.actions };
for (const dep of config.toggles.toggles) {
if (dep.affects !== "generatePreview") continue;
const toggleValue = toggles[dep.name] ?? false;
actions.generatePreview = dep.transform(
toggleValue,
actions.generatePreview
);
}
return actions;
}
function resolveInjection(config, toggles) {
const injection = { ...config.injectMdInAgentResponse };
for (const dep of config.toggles.toggles) {
if (dep.affects !== "format") continue;
const toggleValue = toggles[dep.name] ?? false;
injection.format = dep.transform(toggleValue, injection.format);
}
return injection;
}
// src/services/toolParams/index.ts
var MEDIA_TYPE_CONFIGS = {
attachment: ATTACHMENT_CONFIG,
variant: VARIANT_CONFIG,
picture: PICTURE_CONFIG,
image: IMAGE_CONFIG
};
var MEDIA_TYPE_FULL_CONFIGS = {
attachment: ATTACHMENT_FULL_CONFIG,
variant: VARIANT_FULL_CONFIG,
picture: PICTURE_FULL_CONFIG,
image: IMAGE_FULL_CONFIG
};
function getToolExtractor(pluginId, toolName2) {
const toolKey = `${pluginId}/${toolName2}`;
const pictureConfig = MEDIA_TYPE_CONFIGS.picture;
if (pictureConfig?.allow === "only" && pictureConfig.tools[toolKey]) {
return {
mediaType: "picture",
extractor: pictureConfig.tools[toolKey]
};
}
const selfPlugin2 = getSelfPluginIdentifier();
if (selfPlugin2 && pluginId === selfPlugin2) {
const variantConfig = MEDIA_TYPE_CONFIGS.variant;
if (variantConfig?.allow === "all") {
if (variantConfig.tools?.[toolKey]) {
return {
mediaType: "variant",
extractor: variantConfig.tools[toolKey]
};
}
return {
mediaType: "variant",
extractor: {
extractCandidates: variantConfig.defaultExtractor,
actions: variantConfig.defaultActions
}
};
}
}
const imageConfig = MEDIA_TYPE_CONFIGS.image;
if (imageConfig?.allow === "all") {
if (imageConfig.tools?.[toolKey]) {
return {
mediaType: "image",
extractor: imageConfig.tools[toolKey]
};
}
return {
mediaType: "image",
extractor: {
extractCandidates: imageConfig.defaultExtractor,
actions: imageConfig.defaultActions
}
};
}
return void 0;
}
function isPictureToolAllowlisted(pluginId, toolName2) {
const toolKey = `${pluginId}/${toolName2}`;
return getAllowlistedPictureTools().includes(toolKey);
}
function normalizeToolPluginId(pluginId, toolName2) {
const p = typeof pluginId === "string" ? pluginId.trim() : "";
if (p) return p;
const tn = String(toolName2 || "").trim().toLowerCase();
if (tn === "brave_image_search") {
return "mcp/brave-search-mcp";
}
if (tn === "index_image") {
return "ceveyne/draw-things-index";
}
if (tn === "find_image") {
return "ceveyne/find-image";
}
return void 0;
}
function getMediaTypeForToolCall(pluginId, toolName2) {
const result = getToolExtractor(pluginId, toolName2);
return result?.mediaType;
}
function getAllMediaTypeConfigs() {
return { ...MEDIA_TYPE_CONFIGS };
}
function getMediaTypeConfig(kind) {
return MEDIA_TYPE_CONFIGS[kind];
}
function getMediaTypeFullConfig(kind) {
return MEDIA_TYPE_FULL_CONFIGS[kind];
}
function getAllMediaTypeFullConfigs() {
return { ...MEDIA_TYPE_FULL_CONFIGS };
}
// src/services/mediaScanner/conversationParser.ts
import fs11 from "fs";
import path11 from "path";
import os3 from "os";
// src/helpers/findConversationFile.ts
import { existsSync as existsSync4, readdirSync } from "fs";
import { join as join4, basename } from "path";
function findConversationFileByChatId(chatId, conversationsDir = join4(findLMStudioHome(), "conversations")) {
const fileName = `${chatId}.conversation.json`;
const direct = join4(conversationsDir, fileName);
if (existsSync4(direct)) return direct;
return listConversationFiles(conversationsDir).find((p) => basename(p) === fileName);
}
function listConversationFiles(conversationsDir) {
const result = [];
const queue = [conversationsDir];
while (queue.length > 0) {
const dir = queue.shift();
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch (e) {
console.debug(`[findConversationFile] Cannot read ${dir}: ${e?.message || e}`);
continue;
}
for (const entry of entries) {
if (entry.isFile() && entry.name.endsWith(".conversation.json")) {
result.push(join4(dir, entry.name));
} else if (entry.isDirectory()) {
queue.push(join4(dir, entry.name));
}
}
}
return result;
}
// src/services/mediaScanner/conversationParser.ts
function findConversationPath(chatWd) {
const chatId = path11.basename(chatWd);
const lmHome = findLMStudioHome() || path11.join(os3.homedir(), ".lmstudio");
const conversationsDir = path11.join(lmHome, "conversations");
const candidates = [
findConversationFileByChatId(chatId, conversationsDir),
path11.join(chatWd, ".conversation.json"),
path11.join(chatWd, "conversation.json")
].filter((p) => !!p);
for (const p of candidates) {
try {
fs11.accessSync(p, fs11.constants.F_OK);
return p;
} catch {
}
}
return void 0;
}
async function readConversation(chatWd) {
const p = findConversationPath(chatWd);
if (!p) return void 0;
const maxAttempts = 5;
const retryDelayMs = 50;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
try {
const raw = await fs11.promises.readFile(p, "utf-8");
const json = JSON.parse(raw);
return { json, path: p };
} catch {
if (attempt < maxAttempts - 1) {
await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
}
}
}
return void 0;
}
function findMessagesArray(json) {
if (!json || typeof json !== "object") return void 0;
const obj = json;
const candidates = [
obj.messages,
obj.conversation?.messages,
obj.chat?.messages,
obj.history,
obj.turns,
obj.items
];
for (const arr of candidates) {
if (Array.isArray(arr) && arr.length > 0) {
return arr;
}
}
return void 0;
}
function resolveMessageVersion(raw) {
if (!raw || typeof raw !== "object") return raw;
const obj = raw;
const versions = obj.versions;
if (!Array.isArray(versions) || versions.length === 0) {
return raw;
}
const selRaw = obj.currentlySelected;
const sel = typeof selRaw === "number" && Number.isFinite(selRaw) ? selRaw : 0;
if (sel >= 0 && sel < versions.length) {
return versions[sel];
}
return versions[versions.length - 1];
}
function getMessageRole(msg) {
if (!msg || typeof msg !== "object") return "unknown";
const obj = msg;
if (obj.type === "contentBlock") {
const arr = obj.content;
if (Array.isArray(arr)) {
for (const it of arr) {
if (!it || typeof it !== "object") continue;
const t = it.type;
if (t === "toolCallRequest" || t === "toolCallResult") {
return "tool";
}
}
}
}
const role = obj.role ?? obj.author ?? obj.sender;
if (typeof role === "string") return role.toLowerCase();
const type = obj.type ?? obj.messageType;
if (typeof type === "string") {
if (type === "user" || type === "user_message") return "user";
if (type === "assistant" || type === "assistant_message")
return "assistant";
if (type === "system") return "system";
if (type === "tool" || type === "tool_result") return "tool";
}
return "unknown";
}
function parseMessages(json) {
const messages = findMessagesArray(json);
if (!messages) return [];
const result = [];
for (let i = 0; i < messages.length; i++) {
const raw = messages[i];
const resolved = resolveMessageVersion(raw);
const role = getMessageRole(resolved);
result.push({
index: i,
turnId: i + 1,
// 1-based
role,
content: resolved,
raw
});
}
return result;
}
function extractToolCalls(msg) {
const result = [];
const content = msg.content;
if (!content || typeof content !== "object") return result;
const obj = content;
const toolCallResults = obj.toolCallResults;
if (Array.isArray(toolCallResults)) {
for (const tcr of toolCallResults) {
if (!tcr || typeof tcr !== "object") continue;
const tc = tcr;
const toolCallId = typeof tc.toolCallId === "string" ? tc.toolCallId : void 0;
const toolName2 = typeof tc.name === "string" ? tc.name : "";
const pluginId = typeof tc.pluginIdentifier === "string" ? tc.pluginIdentifier : void 0;
const resultContent = tc.result ?? tc.content;
if (toolName2) {
result.push({
toolCallId,
toolName: toolName2,
pluginId,
content: resultContent,
turnId: msg.turnId
});
}
}
}
if (Array.isArray(obj.steps)) {
const requestMetaByKey = /* @__PURE__ */ new Map();
const remember = (key, meta) => {
const k = typeof key === "string" || typeof key === "number" ? String(key) : "";
if (!k) return;
const prev = requestMetaByKey.get(k) ?? {};
requestMetaByKey.set(k, {
pluginId: meta.pluginId ?? prev.pluginId,
toolName: meta.toolName ?? prev.toolName
});
};
for (const step of obj.steps) {
if (!step || typeof step !== "object") continue;
const st = step;
if (st.type === "contentBlock" && Array.isArray(st.content)) {
for (const bi of st.content) {
if (!bi || typeof bi !== "object") continue;
const bo = bi;
if (bo.type !== "toolCallRequest") continue;
const pluginId = typeof bo.pluginIdentifier === "string" ? bo.pluginIdentifier : void 0;
const toolName2 = typeof bo.name === "string" ? bo.name : void 0;
const callId = bo.callId ?? bo.toolCallId ?? bo.id;
const reqId = bo.toolCallRequestId ?? bo.requestId;
remember(callId, { pluginId, toolName: toolName2 });
remember(reqId, { pluginId, toolName: toolName2 });
}
}
}
for (const step of obj.steps) {
if (!step || typeof step !== "object") continue;
const st = step;
if (st.type === "contentBlock" && Array.isArray(st.content)) {
for (const bi of st.content) {
if (!bi || typeof bi !== "object") continue;
const bo = bi;
if (bo.type !== "toolCallResult") continue;
const callId = bo.callId ?? bo.toolCallId ?? bo.id;
const reqId = bo.toolCallRequestId ?? bo.requestId;
const toolCallId = typeof callId === "string" || typeof callId === "number" ? String(callId) : typeof reqId === "string" || typeof reqId === "number" ? String(reqId) : void 0;
const fallbackMeta = typeof callId === "string" || typeof callId === "number" ? requestMetaByKey.get(String(callId)) : void 0;
const fallbackMeta2 = fallbackMeta ?? (typeof reqId === "string" || typeof reqId === "number" ? requestMetaByKey.get(String(reqId)) : void 0);
const toolName2 = typeof bo.name === "string" ? bo.name : fallbackMeta2?.toolName ?? "";
const pluginId = typeof bo.pluginIdentifier === "string" ? bo.pluginIdentifier : fallbackMeta2?.pluginId;
const resultContent = bo.result ?? bo.content ?? bo.output;
if (toolName2 || toolCallId) {
result.push({
toolCallId,
toolName: toolName2,
pluginId,
content: resultContent,
turnId: msg.turnId
});
}
}
}
}
}
const contentArray = obj.content;
if (Array.isArray(contentArray)) {
const requestMetaByKey = /* @__PURE__ */ new Map();
const remember = (key, meta) => {
const k = typeof key === "string" || typeof key === "number" ? String(key) : "";
if (!k) return;
const prev = requestMetaByKey.get(k) ?? {};
requestMetaByKey.set(k, {
pluginId: meta.pluginId ?? prev.pluginId,
toolName: meta.toolName ?? prev.toolName
});
};
for (const item of contentArray) {
if (!item || typeof item !== "object") continue;
const it = item;
if (it.type === "contentBlock" && Array.isArray(it.content)) {
const blockItems = it.content;
for (const bi of blockItems) {
if (!bi || typeof bi !== "object") continue;
const bo = bi;
if (bo.type !== "toolCallRequest") continue;
const pluginId = typeof bo.pluginIdentifier === "string" ? bo.pluginIdentifier : void 0;
const toolName2 = typeof bo.name === "string" ? bo.name : void 0;
const callId = bo.callId ?? bo.toolCallId ?? bo.id;
const reqId = bo.toolCallRequestId ?? bo.requestId;
remember(callId, { pluginId, toolName: toolName2 });
remember(reqId, { pluginId, toolName: toolName2 });
}
}
}
for (const item of contentArray) {
if (!item || typeof item !== "object") continue;
const it = item;
if (it.type === "contentBlock" && Array.isArray(it.content)) {
const blockItems = it.content;
for (const bi of blockItems) {
if (!bi || typeof bi !== "object") continue;
const bo = bi;
if (bo.type !== "toolCallResult") continue;
const callId = bo.callId ?? bo.toolCallId ?? bo.id;
const reqId = bo.toolCallRequestId ?? bo.requestId;
const toolCallId = typeof callId === "string" || typeof callId === "number" ? String(callId) : typeof reqId === "string" || typeof reqId === "number" ? String(reqId) : void 0;
const fallbackMeta = typeof callId === "string" || typeof callId === "number" ? requestMetaByKey.get(String(callId)) : void 0;
const fallbackMeta2 = fallbackMeta ?? (typeof reqId === "string" || typeof reqId === "number" ? requestMetaByKey.get(String(reqId)) : void 0);
const toolName2 = typeof bo.name === "string" ? bo.name : fallbackMeta2?.toolName ?? "";
const pluginId = typeof bo.pluginIdentifier === "string" ? bo.pluginIdentifier : fallbackMeta2?.pluginId;
const resultContent = bo.result ?? bo.content ?? bo.output;
if (toolName2 || toolCallId) {
result.push({
toolCallId,
toolName: toolName2,
pluginId,
content: resultContent,
turnId: msg.turnId
});
}
}
continue;
}
if (it.type === "tool_result" || it.type === "tool-result") {
const toolCallId = typeof it.tool_call_id === "string" ? it.tool_call_id : typeof it.toolCallId === "string" ? it.toolCallId : void 0;
const toolName2 = typeof it.name === "string" ? it.name : typeof it.tool_name === "string" ? it.tool_name : "";
const pluginId = typeof it.pluginIdentifier === "string" ? it.pluginIdentifier : typeof it.plugin === "string" ? it.plugin : void 0;
const resultContent = it.result ?? it.content ?? it.output;
if (toolName2 || toolCallId) {
result.push({
toolCallId,
toolName: toolName2,
pluginId,
content: resultContent,
turnId: msg.turnId
});
}
}
}
}
if (obj.type === "contentBlock" && Array.isArray(obj.content)) {
const blockMsg = { type: "contentBlock", content: obj.content };
const fake = { content: [blockMsg] };
const nested = extractToolCalls({ ...msg, content: fake });
result.push(...nested);
}
const toolResults = obj.tool_results ?? obj.toolResults;
if (Array.isArray(toolResults)) {
for (const tr of toolResults) {
if (!tr || typeof tr !== "object") continue;
const t = tr;
const toolCallId = typeof t.tool_call_id === "string" ? t.tool_call_id : typeof t.id === "string" ? t.id : void 0;
const toolName2 = typeof t.name === "string" ? t.name : typeof t.tool === "string" ? t.tool : "";
const pluginId = typeof t.pluginIdentifier === "string" ? t.pluginIdentifier : void 0;
const resultContent = t.result ?? t.content ?? t.output;
if (toolName2 || toolCallId) {
result.push({
toolCallId,
toolName: toolName2,
pluginId,
content: resultContent,
turnId: msg.turnId
});
}
}
}
return result;
}
function extractUserAttachments(msg, lmHome) {
const result = [];
const home = lmHome || findLMStudioHome() || path11.join(os3.homedir(), ".lmstudio");
const userFilesDir = path11.join(home, "user-files");
const content = msg.content;
if (!content || typeof content !== "object") return result;
const collectFromObject = (obj) => {
if (!obj || typeof obj !== "object") return;
if (Array.isArray(obj)) {
for (const item of obj) {
collectFromObject(item);
}
return;
}
const o = obj;
const fileId = o.fileIdentifier ?? o.file_identifier ?? o.identifier;
const fileType = o.fileType ?? o.file_type ?? o.type;
if (typeof fileId === "string" && fileId.trim()) {
if (fileType === "image" || /\.(png|jpg|jpeg|webp|gif|bmp|tiff?)$/i.test(fileId)) {
result.push(path11.join(userFilesDir, fileId));
}
}
const filePath = o.path ?? o.filePath ?? o.file_path ?? o.uri ?? o.url;
if (typeof filePath === "string" && filePath.trim()) {
let resolved = filePath;
if (filePath.startsWith("file://")) {
try {
resolved = decodeURIComponent(filePath.replace(/^file:\/\//, ""));
} catch {
resolved = filePath.replace(/^file:\/\//, "");
}
}
if (/\.(png|jpg|jpeg|webp|gif|bmp|tiff?)$/i.test(resolved)) {
result.push(resolved);
}
}
for (const key of Object.keys(o)) {
if (key !== "content" || !Array.isArray(o[key])) {
collectFromObject(o[key]);
}
}
};
const contentArray = content.content;
if (Array.isArray(contentArray)) {
for (const part of contentArray) {
collectFromObject(part);
}
} else {
collectFromObject(content);
}
const files = content.files;
if (Array.isArray(files)) {
for (const f of files) {
collectFromObject(f);
}
}
const attachments = content.attachments;
if (Array.isArray(attachments)) {
for (const a of attachments) {
collectFromObject(a);
}
}
return result;
}
function extractPendingAttachments(json, lmHome) {
const result = [];
const home = lmHome || findLMStudioHome() || path11.join(os3.homedir(), ".lmstudio");
const userFilesDir = path11.join(home, "user-files");
if (!json || typeof json !== "object") return result;
const files = json.clientInputFiles;
if (!Array.isArray(files)) return result;
for (const f of files) {
if (!f || typeof f !== "object") continue;
const fo = f;
const id = fo.fileIdentifier;
const type = fo.fileType;
if (typeof id === "string" && id.trim() && type === "image") {
result.push(path11.join(userFilesDir, id));
}
}
return result;
}
// src/services/mediaScanner/scanner.ts
var VARIANT_FILENAME_RE = /generated-image-[A-Za-z0-9T-]+Z-v\d+\.png/gi;
function buildConversationWideRequestMetadata(messages, debug) {
const metaByKey = /* @__PURE__ */ new Map();
let toolRequestCount = 0;
const remember = (key, meta) => {
const k = typeof key === "string" || typeof key === "number" ? String(key) : "";
if (!k) return;
const prev = metaByKey.get(k) ?? {};
metaByKey.set(k, {
pluginId: meta.pluginId ?? prev.pluginId,
toolName: meta.toolName ?? prev.toolName
});
};
if (debug) {
console.info(
`[MediaScanner] buildConversationWideRequestMetadata: scanning ${messages.length} messages`
);
}
for (const msg of messages) {
const content = msg.content;
if (!content || typeof content !== "object") continue;
const obj = content;
if (obj.type === "contentBlock" && Array.isArray(obj.content)) {
for (const item of obj.content) {
if (!item || typeof item !== "object") continue;
const bo = item;
if (bo.type !== "toolCallRequest") continue;
const pluginId = typeof bo.pluginIdentifier === "string" ? bo.pluginIdentifier : void 0;
const toolName2 = typeof bo.name === "string" ? bo.name : void 0;
const callId = bo.callId ?? bo.toolCallId ?? bo.id;
const reqId = bo.toolCallRequestId ?? bo.requestId;
toolRequestCount++;
if (debug) {
console.info(
`[MediaScanner] Request metadata (Case1): callId=${callId} reqId=${reqId} tool=${toolName2} plugin=${pluginId ?? "(none)"}`
);
}
remember(callId, { pluginId, toolName: toolName2 });
remember(reqId, { pluginId, toolName: toolName2 });
}
}
if (Array.isArray(obj.content)) {
for (const item of obj.content) {
if (!item || typeof item !== "object") continue;
const it = item;
if (it.type === "contentBlock" && Array.isArray(it.content)) {
for (const bi of it.content) {
if (!bi || typeof bi !== "object") continue;
const bo = bi;
if (bo.type !== "toolCallRequest") continue;
const pluginId = typeof bo.pluginIdentifier === "string" ? bo.pluginIdentifier : void 0;
const toolName2 = typeof bo.name === "string" ? bo.name : void 0;
const callId = bo.callId ?? bo.toolCallId ?? bo.id;
const reqId = bo.toolCallRequestId ?? bo.requestId;
toolRequestCount++;
if (debug) {
console.info(
`[MediaScanner] Request metadata (Case2): callId=${callId} reqId=${reqId} tool=${toolName2} plugin=${pluginId ?? "(none)"}`
);
}
remember(callId, { pluginId, toolName: toolName2 });
remember(reqId, { pluginId, toolName: toolName2 });
}
}
}
}
if (Array.isArray(obj.steps)) {
for (const step of obj.steps) {
if (!step || typeof step !== "object") continue;
const st = step;
if (st.type === "contentBlock" && Array.isArray(st.content)) {
for (const bi of st.content) {
if (!bi || typeof bi !== "object") continue;
const bo = bi;
if (bo.type !== "toolCallRequest") continue;
const pluginId = typeof bo.pluginIdentifier === "string" ? bo.pluginIdentifier : void 0;
const toolName2 = typeof bo.name === "string" ? bo.name : void 0;
const callId = bo.callId ?? bo.toolCallId ?? bo.id;
const reqId = bo.toolCallRequestId ?? bo.requestId;
toolRequestCount++;
if (debug) {
console.info(
`[MediaScanner] Request metadata (Case3-steps): callId=${callId} reqId=${reqId} tool=${toolName2} plugin=${pluginId ?? "(none)"}`
);
}
remember(callId, { pluginId, toolName: toolName2 });
remember(reqId, { pluginId, toolName: toolName2 });
}
}
}
}
}
if (debug) {
console.info(
`[MediaScanner] buildConversationWideRequestMetadata: found ${toolRequestCount} toolCallRequests, ${metaByKey.size} unique keys`
);
}
return metaByKey;
}
function extractVariantFilenames(content) {
const text = typeof content === "string" ? content : JSON.stringify(content);
const matches = text.match(VARIANT_FILENAME_RE) ?? [];
return [...new Set(matches)];
}
function extractImageFilenames(content) {
const result = [];
const text = typeof content === "string" ? content : JSON.stringify(content);
const base64Re = /data:image\/[a-z]+;base64,[A-Za-z0-9+/=]+/g;
const base64Matches = text.match(base64Re) ?? [];
result.push(...base64Matches);
const filenameRe = /\b([a-zA-Z0-9_-]+\.(png|jpg|jpeg|webp|gif))\b/gi;
const filenameMatches = text.match(filenameRe) ?? [];
for (const match of filenameMatches) {
if (VARIANT_FILENAME_RE.test(match)) {
VARIANT_FILENAME_RE.lastIndex = 0;
continue;
}
if (match.includes("://")) continue;
result.push(match);
}
return [...new Set(result)];
}
async function scanMedia(chatWd, mediaType, options) {
const { scope, debug = false } = options;
if (!chatWd) {
return { candidates: [] };
}
const conv = await readConversation(chatWd);
if (!conv) {
if (debug) {
console.info(`[MediaScanner] No conversation.json found for ${chatWd}`);
}
return { candidates: [] };
}
if (debug && (mediaType === "picture" || mediaType === "image")) {
try {
const arr = findMessagesArray(conv.json);
const arrLen = Array.isArray(arr) ? arr.length : 0;
console.info(
`[MediaScanner] SSOT messages array present=${!!arr} len=${arrLen}`
);
let contentBlockCount = 0;
let toolCallRequestCount = 0;
let toolCallResultCount = 0;
let braveHits = 0;
const stack = Array.isArray(arr) ? [...arr] : [conv.json];
const maxNodes = 5e4;
let nodes = 0;
while (stack.length) {
const v = stack.pop();
nodes++;
if (nodes > maxNodes) break;
if (!v) continue;
if (typeof v === "string") {
if (v.includes("brave_image_search")) {
braveHits++;
}
continue;
}
if (typeof v !== "object") continue;
if (Array.isArray(v)) {
for (const it of v) stack.push(it);
continue;
}
const o = v;
const t = o.type;
if (t === "contentBlock") contentBlockCount++;
if (t === "toolCallRequest" || t === "toolCallRequest") {
toolCallRequestCount++;
if (o.name === "brave_image_search") {
braveHits++;
}
}
if (t === "toolCallResult" || t === "tool_result" || t === "tool-result") {
toolCallResultCount++;
if (o.name === "brave_image_search") {
braveHits++;
}
}
for (const k of Object.keys(o)) {
stack.push(o[k]);
}
}
console.info(
`[MediaScanner] SSOT scan stats: contentBlock=${contentBlockCount} toolCallRequest=${toolCallRequestCount} toolCallResult=${toolCallResultCount} braveHits=${braveHits} nodes=${Math.min(
nodes,
maxNodes
)}${nodes > maxNodes ? "+" : ""}`
);
} catch (e) {
console.info(
`[MediaScanner] SSOT debug scan failed: ${String(
e?.message ?? e
)}`
);
}
}
const messages = parseMessages(conv.json);
if (debug) {
console.info(
`[MediaScanner] Parsed ${messages.length} messages from ${conv.path}`
);
if (mediaType === "picture" || mediaType === "image") {
const byRole = /* @__PURE__ */ new Map();
for (const m of messages) {
const r = String(m.role || "unknown");
byRole.set(r, (byRole.get(r) ?? 0) + 1);
}
const roleSummary = Array.from(byRole.entries()).sort((a, b) => b[1] - a[1]).map(([r, n]) => `${r}:${n}`).join(" ");
console.info(`[MediaScanner] Role distribution: ${roleSummary}`);
}
}
const requestMetaByKey = buildConversationWideRequestMetadata(
messages,
debug
);
if (debug && requestMetaByKey.size > 0) {
console.info(
`[MediaScanner] Collected ${requestMetaByKey.size} request metadata entries`
);
}
const candidates = [];
const orderedMessages = scope === "last" ? [...messages].reverse() : messages;
for (const msg of orderedMessages) {
let foundInThisMessage = [];
if (mediaType === "attachment") {
foundInThisMessage = scanAttachmentsInMessage(msg, conv.json, debug);
} else {
foundInThisMessage = scanToolResultsInMessage(
msg,
mediaType,
requestMetaByKey,
debug
);
}
if (foundInThisMessage.length > 0) {
candidates.push(...foundInThisMessage);
if (scope === "last") {
break;
}
}
}
if (mediaType === "attachment" && scope === "all") {
const pending = extractPendingAttachments(conv.json);
const toAppend = [];
for (const p of pending) {
const exists = candidates.some((c) => c.identifier === p);
if (exists) continue;
toAppend.push({
kind: "attachment",
identifier: p,
turnId: 0
// Pending = before any turn
});
}
if (toAppend.length) {
candidates.push(...toAppend);
}
}
if (debug) {
console.info(
`[MediaScanner] FINAL: Found ${candidates.length} ${mediaType} candidates (scope: ${scope})`
);
if (candidates.length > 0) {
for (const c of candidates.slice(0, 3)) {
console.info(
`[MediaScanner] candidate: id=${c.identifier?.slice(
0,
50
)} pluginId=${c.pluginId} tool=${c.sourceTool}`
);
}
}
}
return {
candidates,
conversationPath: conv.path
};
}
function scanAttachmentsInMessage(msg, conversationJson, debug) {
if (msg.role !== "user") return [];
const attachments = extractUserAttachments(msg);
return attachments.map((absPath) => ({
kind: "attachment",
identifier: absPath,
turnId: msg.turnId
}));
}
function scanToolResultsInMessage(msg, mediaType, requestMetaByKey, debug) {
if (msg.role !== "assistant" && msg.role !== "tool") return [];
const toolCalls = extractToolCalls(msg);
const candidates = [];
if (debug && (mediaType === "picture" || mediaType === "image") && toolCalls.length) {
const names = toolCalls.map((t) => String(t.toolName || "")).filter((s) => s.trim().length > 0);
console.info(
`[MediaScanner] turnId=${msg.turnId} extracted toolCalls=${toolCalls.length}${names.length ? ` tools=${names.slice(0, 5).join(", ")}${names.length > 5 ? "\u2026" : ""}` : ""}`
);
}
const selfPlugin2 = getSelfPluginIdentifier();
for (const tc of toolCalls) {
let effectivePluginId = tc.pluginId;
if (!effectivePluginId && tc.toolCallId) {
const meta = requestMetaByKey.get(tc.toolCallId);
if (meta?.pluginId) effectivePluginId = meta.pluginId;
}
const isOurPlugin = selfPlugin2 && effectivePluginId === selfPlugin2;
const pluginIdNormalized = normalizeToolPluginId(
effectivePluginId,
tc.toolName
);
if (debug && (mediaType === "picture" || mediaType === "image")) {
console.info(
`[MediaScanner] ${mediaType} check: toolName="${tc.toolName}" pluginId="${tc.pluginId ?? "(none)"}" effectivePluginId="${effectivePluginId ?? "(none)"}" normalized="${pluginIdNormalized ?? "(none)"}" isOurPlugin=${isOurPlugin}`
);
}
if (mediaType === "variant") {
if (!isOurPlugin) continue;
if (pluginIdNormalized) {
const lookup = getToolExtractor(pluginIdNormalized, tc.toolName);
if (lookup && lookup.mediaType !== "variant") continue;
}
const filenames = extractVariantFilenames(tc.content);
for (const filename of filenames) {
candidates.push({
kind: "variant",
identifier: filename,
turnId: tc.turnId,
toolCallId: tc.toolCallId,
sourceTool: tc.toolName,
pluginId: effectivePluginId
});
}
} else if (mediaType === "picture") {
if (!pluginIdNormalized) continue;
const lookup = getToolExtractor(pluginIdNormalized, tc.toolName);
if (!lookup || lookup.mediaType !== "picture") continue;
const extracted = lookup.extractor.extractCandidates(tc.content);
if (debug) {
console.info(
`[MediaScanner] picture toolCall: ${pluginIdNormalized}/${tc.toolName} candidates=${extracted.length}`
);
}
for (const c of extracted) {
const identifier = typeof c.filename === "string" && c.filename.trim() ? c.filename.trim() : typeof c.url === "string" && c.url.trim() ? c.url.trim() : "";
if (!identifier) continue;
candidates.push({
kind: "picture",
identifier,
turnId: tc.turnId,
toolCallId: tc.toolCallId,
sourceTool: tc.toolName,
pluginId: pluginIdNormalized,
title: c.title,
pageUrl: typeof c.sourceUrl === "string" ? c.sourceUrl : void 0,
width: typeof c.width === "number" ? c.width : void 0,
height: typeof c.height === "number" ? c.height : void 0,
rawContent: tc.content
});
}
} else if (mediaType === "image") {
if (isOurPlugin) continue;
if (!pluginIdNormalized) continue;
const lookup = getToolExtractor(pluginIdNormalized, tc.toolName);
if (lookup && lookup.mediaType !== "image") {
if (debug) {
console.info(
`[MediaScanner] image skip: ${pluginIdNormalized}/${tc.toolName} is registered as ${lookup.mediaType}`
);
}
continue;
}
if (lookup && lookup.mediaType === "image") {
const extracted = lookup.extractor.extractCandidates(tc.content);
if (debug) {
console.info(
`[MediaScanner] image toolCall: ${pluginIdNormalized}/${tc.toolName} candidates=${extracted.length}`
);
}
for (const c of extracted) {
const filename = c.filename ?? "";
if (!filename) continue;
candidates.push({
kind: "image",
identifier: filename,
turnId: tc.turnId,
toolCallId: tc.toolCallId,
sourceTool: tc.toolName,
pluginId: pluginIdNormalized,
previewIsOriginal: c.previewIsOriginal
});
}
} else {
const filenames = extractImageFilenames(tc.content);
for (const filename of filenames) {
candidates.push({
kind: "image",
identifier: filename,
turnId: tc.turnId,
toolCallId: tc.toolCallId,
sourceTool: tc.toolName,
pluginId: effectivePluginId
});
}
}
}
}
return candidates;
}
async function findAllMedia(chatWd, mediaType, debug = false) {
return scanMedia(chatWd, mediaType, { scope: "all", debug });
}
async function findLastMedia(chatWd, mediaType, debug = false) {
return scanMedia(chatWd, mediaType, { scope: "last", debug });
}
async function findAllMediaAllTypes(chatWd, debug = false) {
const [attachments, variants, pictures, images] = await Promise.all([
findAllMedia(chatWd, "attachment", debug),
findAllMedia(chatWd, "variant", debug),
findAllMedia(chatWd, "picture", debug),
findAllMedia(chatWd, "image", debug)
]);
return {
attachment: attachments.candidates,
variant: variants.candidates,
picture: pictures.candidates,
image: images.candidates
};
}
// src/services/mediaScanner/legacyAdapters.ts
async function findAllAttachmentsLegacy(chatWd, debug) {
if (!chatWd) return { found: [], turnIdByAbs: {} };
const result = await findAllMedia(chatWd, "attachment", debug);
const found = [];
const turnIdByAbs = {};
for (const c of result.candidates) {
const abs = c.identifier;
if (!found.includes(abs)) {
found.push(abs);
}
if (turnIdByAbs[abs] === void 0) {
turnIdByAbs[abs] = c.turnId;
}
}
return { found, turnIdByAbs };
}
async function findLastAttachmentLegacy(chatWd, debug) {
if (!chatWd) return [];
const result = await findLastMedia(chatWd, "attachment", debug);
const found = [];
for (const c of result.candidates) {
if (!found.includes(c.identifier)) {
found.push(c.identifier);
}
}
return found;
}
async function findAllVariantsLegacy(chatWd, debug) {
if (!chatWd) return { found: [], turnIdByBasename: {} };
const result = await findAllMedia(chatWd, "variant", debug);
const found = [];
const turnIdByBasename = {};
for (const c of result.candidates) {
const basename5 = c.identifier;
if (!found.includes(basename5)) {
found.push(basename5);
}
turnIdByBasename[basename5] = c.turnId;
}
return { found, turnIdByBasename };
}
async function findAllPictures(chatWd, debug) {
if (!chatWd) return { candidates: [] };
const result = await findAllMedia(chatWd, "picture", debug);
return { candidates: result.candidates };
}
async function findLastPictures(chatWd, debug) {
if (!chatWd) return { candidates: [] };
const result = await findLastMedia(chatWd, "picture", debug);
return { candidates: result.candidates };
}
async function findAllImages(chatWd, debug) {
if (!chatWd) return { candidates: [] };
const result = await findAllMedia(chatWd, "image", debug);
return { candidates: result.candidates };
}
async function findLastImages(chatWd, debug) {
if (!chatWd) return { candidates: [] };
const result = await findLastMedia(chatWd, "image", debug);
return { candidates: result.candidates };
}
// src/media-promotion-core/attachments.ts
import fs12 from "fs";
import path12 from "path";
async function pathExists2(p) {
try {
await fs12.promises.access(p, fs12.constants.F_OK);
return true;
} catch {
return false;
}
}
async function importAttachmentBatch(chatWd, state, sourcePaths, turnIdByOriginAbs, previewOpts, maxPreviewAttachments = 0, debug = false) {
const normalizeAbs = (p) => {
try {
return path12.resolve(p);
} catch {
return p;
}
};
const normalizedSource = sourcePaths.filter((p) => typeof p === "string" && p.trim().length > 0).map(normalizeAbs);
const normalizeTurnIdMap = (m) => {
if (!m) return {};
const out = {};
for (const [k, v] of Object.entries(m)) {
if (typeof v === "number" && Number.isFinite(v)) {
out[normalizeAbs(k)] = v;
}
}
return out;
};
const normalizedTurnIdByAbs = normalizeTurnIdMap(turnIdByOriginAbs);
const normalizedSourceDeduped = [];
{
const seen = /* @__PURE__ */ new Set();
for (const p of normalizedSource) {
if (!seen.has(p)) {
seen.add(p);
normalizedSourceDeduped.push(p);
}
}
}
if (normalizedSourceDeduped.length === 0) {
if (debug)
console.info(
"Batch import: No new attachments in current turn; keeping existing state."
);
return { changed: false };
}
try {
const current = Array.isArray(state.attachments) ? state.attachments : [];
const currentOrigins = current.map(
(a) => a && typeof a.originAbs === "string" ? String(a.originAbs) : ""
).filter((p) => p.trim().length > 0).map(normalizeAbs);
const same = currentOrigins.length === normalizedSourceDeduped.length && currentOrigins.every((p, i) => p === normalizedSourceDeduped[i]);
if (same && current.length > 0) {
let allOk = true;
for (let i = 0; i < current.length; i++) {
const a = current[i];
const pv = a && typeof a.preview === "string" ? String(a.preview) : "";
if (i < Math.max(0, Math.floor(maxPreviewAttachments))) {
if (!pv) {
allOk = false;
break;
}
const pvAbs = path12.join(chatWd, pv);
const okPv = await pathExists2(pvAbs);
if (!okPv) {
allOk = false;
break;
}
}
}
if (allOk) {
try {
let anyMetaChanged = false;
const nextAttachments = current.map((a) => {
const originAbs = a && typeof a.originAbs === "string" ? String(a.originAbs) : "";
const key = originAbs ? normalizeAbs(originAbs) : "";
const nextTurnId = key ? normalizedTurnIdByAbs[key] : void 0;
let updated = a;
if (typeof nextTurnId === "number" && a && a.turnId !== nextTurnId) {
anyMetaChanged = true;
updated = { ...updated, turnId: nextTurnId };
}
if (!updated.preview && originAbs) {
const candidate = previewFilenameFrom(path12.basename(originAbs));
if (fs12.existsSync(path12.join(chatWd, candidate))) {
anyMetaChanged = true;
updated = { ...updated, preview: candidate };
}
}
return updated;
});
if (anyMetaChanged) {
state.attachments = nextAttachments;
await writeStateAtomic(chatWd, state);
if (debug)
console.info(
"Batch import: updated attachment turnId metadata (idempotent, no re-import)."
);
return { changed: false, metadataChanged: true };
}
} catch (e) {
if (debug)
console.warn(
"Batch import: turnId metadata update failed; continuing idempotent skip:",
e.message
);
}
if (debug)
console.info(
"Batch import: SSOT matches current state; skipping re-import (idempotent)."
);
return { changed: false };
}
}
} catch (e) {
if (debug)
console.warn(
"Batch import: idempotence check failed; continuing with import:",
e.message
);
}
const existingByOrigin = /* @__PURE__ */ new Map();
for (const a of state.attachments || []) {
if (a && typeof a.originAbs === "string") {
existingByOrigin.set(normalizeAbs(a.originAbs), a);
}
}
const usedAs = /* @__PURE__ */ new Set();
for (const a of existingByOrigin.values()) {
const av = a?.a;
if (typeof av === "number" && Number.isFinite(av) && av > 0) {
usedAs.add(av);
}
}
const ensureNextA = () => {
const current = state?.counters?.nextAttachmentA;
if (typeof current === "number" && Number.isFinite(current) && current > 0) {
return Math.floor(current);
}
const maxExisting = usedAs.size ? Math.max(...Array.from(usedAs)) : 0;
return maxExisting + 1;
};
let nextA = ensureNextA();
const allocateA = () => {
while (usedAs.has(nextA)) nextA++;
const a = nextA;
usedAs.add(a);
nextA++;
return a;
};
const imported = [];
for (let i = 0; i < normalizedSourceDeduped.length; i++) {
const abs = normalizedSourceDeduped[i];
if (!await pathExists2(abs)) {
if (debug)
console.warn(`Batch import: source not found, skipping: ${abs}`);
continue;
}
if (!isAllowedOriginalExt(abs)) {
if (debug)
console.warn(`Batch import: extension not allowed, skipping: ${abs}`);
continue;
}
const existing = existingByOrigin.get(normalizeAbs(abs));
if (existing) {
if (existing.preview) {
const previewAbs = path12.join(chatWd, existing.preview);
if (!await pathExists2(previewAbs)) {
if (debug)
console.info(
`Batch import: regenerating missing preview for a${existing.a}`
);
await generatePreview(abs, chatWd, previewOpts, {
customFilename: existing.preview,
force: true,
debug
});
}
}
const nextTurnId = normalizedTurnIdByAbs[normalizeAbs(abs)];
let existingWidth = existing.width;
let existingHeight = existing.height;
if (existingWidth == null || existingHeight == null) {
try {
const origBuf = await fs12.promises.readFile(abs);
const dims = await getSize(origBuf);
if (dims.width > 0 && dims.height > 0) {
existingWidth = dims.width;
existingHeight = dims.height;
}
} catch (e) {
if (debug)
console.warn(
`Batch import: failed to measure dims for a${existing.a}:`,
e.message
);
}
}
imported.push({
...existing,
// Keep stable `a`
a: typeof existing.a === "number" && Number.isFinite(existing.a) && existing.a > 0 ? existing.a : allocateA(),
turnId: typeof nextTurnId === "number" ? nextTurnId : existing.turnId,
width: existingWidth,
height: existingHeight
});
if (debug)
console.info(
`Batch import: reusing existing attachment as a${existing.a}: ${path12.basename(abs)}`
);
continue;
}
const origin = path12.basename(abs);
let previewName = void 0;
if (i < Math.max(0, Math.floor(maxPreviewAttachments))) {
previewName = await generatePreview(abs, chatWd, previewOpts, { debug }) ?? void 0;
}
if (!previewName) {
const candidate = previewFilenameFrom(path12.basename(abs));
if (fs12.existsSync(path12.join(chatWd, candidate))) {
previewName = candidate;
}
}
let originalName = void 0;
const lmHome = findLMStudioHome();
const userFilesDir = path12.join(lmHome, "user-files");
if (abs.startsWith(userFilesDir)) {
const fileIdentifier = path12.basename(abs);
const resolvedName = await getOriginalFileName(fileIdentifier);
if (!resolvedName || !resolvedName.trim()) {
throw new Error(
`Missing originalName in LM Studio metadata for fileIdentifier='${fileIdentifier}' (abs='${abs}')`
);
}
originalName = resolvedName;
if (debug)
console.info(
`Resolved original filename: ${fileIdentifier} \u2192 ${originalName}`
);
} else {
originalName = path12.basename(abs);
}
let origWidth;
let origHeight;
try {
const origBuf = await fs12.promises.readFile(abs);
const dims = await getSize(origBuf);
if (dims.width > 0 && dims.height > 0) {
origWidth = dims.width;
origHeight = dims.height;
}
} catch (e) {
if (debug)
console.warn(
`Batch import: failed to measure dims for new attachment ${path12.basename(abs)}:`,
e.message
);
}
imported.push({
origin,
originAbs: abs,
originalName,
turnId: normalizedTurnIdByAbs[normalizeAbs(abs)],
preview: previewName,
width: origWidth,
height: origHeight,
createdAt: localTimestamp(),
a: allocateA()
// Stable, monotonically increasing id
});
if (debug)
console.info(
`Batch import: new attachment as a${imported[imported.length - 1].a}: ${path12.basename(abs)}`
);
}
if (imported.length === 0) {
if (debug) console.warn("Batch import: no valid attachments imported");
return { changed: false };
}
state.attachments = imported;
state.counters.nextAttachmentA = nextA;
state.lastEvent = { type: "attachment", at: localTimestamp() };
await writeStateAtomic(chatWd, state);
if (debug)
console.info(
`Batch imported ${imported.length} attachment(s) from SSOT (replaced array)`
);
return { changed: true };
}
// src/helpers/attachmentSync.ts
var DEFAULT_PREVIEW_OPTS = getDefaultPreviewOptions();
async function syncAttachmentsToState(workingDir, debug = false, maxPreviewAttachments = 0, previewOpts) {
const state = await readState(workingDir);
const { found, turnIdByAbs } = await findAllAttachmentsLegacy(
workingDir,
debug
);
const opts = maxPreviewAttachments > 0 ? previewOpts ?? DEFAULT_PREVIEW_OPTS : { maxDim: 0, quality: 0 };
const result = await importAttachmentBatch(
workingDir,
state,
found,
turnIdByAbs,
opts,
maxPreviewAttachments,
debug
);
return { changed: result.changed };
}
// src/helpers/auditLog.ts
import fs13 from "fs";
import path13 from "path";
// src/helpers/logTimestamp.ts
function logTimestamp(date = /* @__PURE__ */ new Date()) {
const pad = (value, width = 2) => String(value).padStart(width, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}`;
}
// src/helpers/auditLog.ts
function buildPaths() {
const logsDir2 = getLogsDir();
const filePath = path13.resolve(logsDir2, getPluginLogFilename().replace(/\.log$/, ".audit.jsonl"));
return { logsDir: logsDir2, filePath };
}
function buildAuditLogger({
backend,
mode,
requestId: providedRequestId
}) {
const requestId = providedRequestId ?? `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const entry = {
timestamp: logTimestamp(),
requestId,
backend,
mode
};
function setChatId(id) {
if (typeof id === "string" && id.trim().length > 0) entry.chat_id = id;
}
function setUserRequest(req) {
entry.user_request = req;
}
function setPromptUpsampling(info) {
entry.prompt_upsampling = info;
}
function setRenderTarget(target2) {
entry.render_target = target2;
}
function setInputs(inputs) {
entry.inputs = inputs;
}
function setOutput(output) {
entry.output = { ...entry.output, ...output };
}
function setError(err) {
let message = "unknown error";
let status = void 0;
if (typeof err === "string") message = err;
else if (err && typeof err === "object") {
const anyErr = err;
message = anyErr.message || JSON.stringify(anyErr);
if (typeof anyErr.status === "number") status = anyErr.status;
}
entry.error = status ? { message, status } : { message };
}
async function write() {
try {
const { logsDir: logsDir2, filePath } = buildPaths();
await fs13.promises.mkdir(logsDir2, { recursive: true });
const block = JSON.stringify(entry, null, 2) + "\n\n";
await fs13.promises.appendFile(filePath, block, { encoding: "utf8" });
} catch (e) {
console.error(
"auditLog write failed:",
e instanceof Error ? e.message : String(e)
);
}
}
return {
requestId,
setChatId,
setUserRequest,
setPromptUpsampling,
setRenderTarget,
setInputs,
setOutput,
setError,
write
};
}
// src/helpers/backgroundRequests.ts
import fs14 from "fs";
import path14 from "path";
// src/helpers/progressReporter.ts
var POST_SAMPLING_STEP_FRACTION = 0.5;
function formatEta(seconds) {
const total = Math.max(1, Math.ceil(seconds));
if (total < 60) return `~${total}s left`;
return `~${Math.floor(total / 60)}m ${String(total % 60).padStart(2, "0")}s left`;
}
function createProgressReporter(emit, now = Date.now) {
let lastProgress = 0;
let passBase = 0;
let currentPass;
let stepsSeenInPass = false;
let anchor;
let lastStep = 0;
return (step, totalSteps, message, pass) => {
if (pass !== currentPass) {
currentPass = pass;
passBase = lastProgress;
stepsSeenInPass = false;
anchor = void 0;
lastStep = 0;
}
const prefix = pass ? `${pass} ` : "";
if (step < 0) {
if (!message) return;
if (stepsSeenInPass && typeof totalSteps === "number") {
lastProgress = Math.max(lastProgress, passBase + totalSteps + 1);
}
emit({ text: `${prefix}${message}`, progress: lastProgress });
return;
}
const atMs = now();
if (anchor && step <= lastStep) anchor = void 0;
if (!anchor) anchor = { step, atMs };
stepsSeenInPass = true;
lastStep = step;
lastProgress = Math.max(lastProgress, passBase + step);
if (!totalSteps || totalSteps <= 0) {
emit({ text: `${prefix}Step ${step}...`, progress: lastProgress });
return;
}
let text = `${prefix}Step ${step}/${totalSteps} (${Math.round(step / (totalSteps + 1) * 100)}%)`;
if (step > anchor.step && step <= totalSteps) {
const avgStepSeconds = (atMs - anchor.atMs) / (step - anchor.step) / 1e3;
text += `, ${formatEta(avgStepSeconds * (totalSteps - step + POST_SAMPLING_STEP_FRACTION))}`;
}
emit({ text, progress: lastProgress });
};
}
function createStatusProgressCallback(ctx, now) {
return createProgressReporter(({ text }) => {
try {
ctx.status?.(text);
} catch (error) {
console.warn(`[progress] status update failed: ${error instanceof Error ? error.message : String(error)}`);
}
}, now);
}
function createMcpProgressSender(ctx, onError) {
const mcpReq = ctx?.mcpReq;
const progressToken = mcpReq?._meta?.progressToken;
if (progressToken === void 0 || typeof mcpReq?.notify !== "function") return void 0;
const request = mcpReq;
return (update) => {
request.notify({
method: "notifications/progress",
params: { progressToken, progress: update.progress, message: update.text }
}).catch(onError);
};
}
// src/helpers/cancelContext.ts
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
var STORE_KEY2 = /* @__PURE__ */ Symbol.for("draw-things.renderCancelContext");
function store2() {
const holder = globalThis;
let existing = holder[STORE_KEY2];
if (!existing) {
existing = new AsyncLocalStorage2();
holder[STORE_KEY2] = existing;
}
return existing;
}
function runWithCancelSignal(signal, fn) {
return store2().run(signal, fn);
}
function getCancelSignal() {
return store2().getStore();
}
// src/helpers/backgroundCallContext.ts
import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
var STORE_KEY3 = /* @__PURE__ */ Symbol.for("draw-things.backgroundCallContext");
function store3() {
const holder = globalThis;
let existing = holder[STORE_KEY3];
if (!existing) {
existing = new AsyncLocalStorage3();
holder[STORE_KEY3] = existing;
}
return existing;
}
function runAsBackgroundCall(fn) {
return store3().run(true, fn);
}
function isBackgroundCall() {
return store3().getStore() === true;
}
// src/helpers/backgroundRequests.ts
var REQUESTS_STATE_FILENAME = "chat_requests_state.json";
var STALE_RECORD_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
function requestsStatePath(chatWd) {
return path14.join(chatWd, REQUESTS_STATE_FILENAME);
}
var writeLocks = /* @__PURE__ */ new Map();
function withWriteLock(key, task) {
const prev = writeLocks.get(key) ?? Promise.resolve();
const run = prev.then(task, task);
writeLocks.set(
key,
run.then(
() => void 0,
() => void 0
)
);
return run;
}
function pruneStale(state) {
const now = Date.now();
let changed = false;
for (const [id, rec] of Object.entries(state.requests)) {
const isFinished = rec.status === "completed" || rec.status === "failed" || rec.status === "cancelled";
const age = now - Date.parse(rec.updatedAt || rec.createdAt || "");
if (isFinished && Number.isFinite(age) && age > STALE_RECORD_MAX_AGE_MS) {
delete state.requests[id];
changed = true;
}
}
return changed;
}
var STALE_RUNNING_THRESHOLD_MS = 10 * 60 * 1e3;
function reapStaleRunning(state) {
const now = Date.now();
for (const rec of Object.values(state.requests)) {
if (rec.status !== "running" && rec.status !== "queued") continue;
const age = now - Date.parse(rec.updatedAt || rec.createdAt || "");
if (Number.isFinite(age) && age > STALE_RUNNING_THRESHOLD_MS) {
rec.status = "failed";
rec.error = `The process running this job stopped reporting for over ${Math.round(STALE_RUNNING_THRESHOLD_MS / 6e4)} min \u2014 it likely restarted or crashed while this was running.`;
rec.delivered = false;
}
}
}
async function readBackgroundRequests(chatWd) {
try {
const raw = await fs14.promises.readFile(requestsStatePath(chatWd), "utf-8");
const json = JSON.parse(raw);
const requests = json && typeof json.requests === "object" && json.requests !== null ? json.requests : {};
const state = { requests };
pruneStale(state);
reapStaleRunning(state);
return state;
} catch {
return { requests: {} };
}
}
async function writeBackgroundRequestsAtomic(chatWd, state) {
pruneStale(state);
const dst = requestsStatePath(chatWd);
const tmp = uniqueTmpPath(dst);
await fs14.promises.mkdir(chatWd, { recursive: true });
await fs14.promises.writeFile(tmp, JSON.stringify(state, null, 2), "utf-8");
await fs14.promises.rename(tmp, dst);
}
async function getBackgroundRequest(chatWd, requestId) {
const state = await readBackgroundRequests(chatWd);
return state.requests[requestId];
}
async function upsertBackgroundRequest(chatWd, requestId, patch) {
await withWriteLock(
requestsStatePath(chatWd),
() => withFileLock(`${requestsStatePath(chatWd)}.lock`, async () => {
await fs14.promises.mkdir(chatWd, { recursive: true });
const state = await readBackgroundRequests(chatWd);
const now = (/* @__PURE__ */ new Date()).toISOString();
const existing = state.requests[requestId];
state.requests[requestId] = {
...existing,
...patch,
requestId,
tool: patch.tool ?? existing?.tool ?? "generate_image",
// A cancelled record stays cancelled: late running/progress updates must not revive it.
status: existing?.status === "cancelled" ? "cancelled" : patch.status ?? existing?.status ?? "queued",
createdAt: existing?.createdAt ?? now,
updatedAt: now
};
await writeBackgroundRequestsAtomic(chatWd, state);
})
);
}
async function markBackgroundRequestDelivered(chatWd, requestId) {
await upsertBackgroundRequest(chatWd, requestId, { delivered: true });
}
async function markBackgroundRequestFailed(chatWd, requestId, error, delivered = false) {
await upsertBackgroundRequest(chatWd, requestId, { status: "failed", error, delivered });
}
async function getUndeliveredCompletedBackgroundRequests(chatWd) {
const state = await readBackgroundRequests(chatWd);
return Object.values(state.requests).filter(
(rec) => (rec.status === "completed" || rec.status === "failed") && !rec.delivered
);
}
async function listBackgroundRequests(chatWd) {
const state = await readBackgroundRequests(chatWd);
return Object.values(state.requests).sort(
(a, b) => Date.parse(a.createdAt || "") - Date.parse(b.createdAt || "")
);
}
function createBackgroundRequestId(scopeId) {
return `${scopeId}-${Math.random().toString(36).slice(2, 8)}`;
}
function requestBelongsToScope(requestId, scopeId) {
return requestId.startsWith(`${scopeId}-`);
}
var HEARTBEAT_INTERVAL_MS = 30 * 1e3;
var SILENT_NOTICE_AFTER_MS = 2 * 60 * 1e3;
var CANCEL_POLL_INTERVAL_MS = 500;
var cancelControllers = /* @__PURE__ */ new Map();
var CANCEL_CONFIRM_TIMEOUT_MS = 1e4;
var CANCEL_CONFIRM_POLL_MS = 250;
async function cancelBackgroundRequest(chatWd, requestId) {
const record = await getBackgroundRequest(chatWd, requestId);
if (!record) return { outcome: "not-found" };
if (record.status === "completed" || record.status === "failed" || record.status === "cancelled") {
return { outcome: "already-finished", status: record.status };
}
if (record.status === "queued") {
await upsertBackgroundRequest(chatWd, requestId, { status: "cancelled", cancelRequested: true, delivered: true });
cancelControllers.get(requestId)?.abort();
const readBack = await getBackgroundRequest(chatWd, requestId);
return readBack?.status === "cancelled" ? { outcome: "cancelled-queued" } : { outcome: "unconfirmed", waitedMs: 0 };
}
await upsertBackgroundRequest(chatWd, requestId, { cancelRequested: true });
cancelControllers.get(requestId)?.abort();
const startedAt = Date.now();
for (; ; ) {
const current = await getBackgroundRequest(chatWd, requestId);
if (current && current.status !== "running" && current.status !== "queued") {
return current.status === "cancelled" ? { outcome: "cancelled" } : { outcome: "finished-before-cancel", status: current.status };
}
const waitedMs = Date.now() - startedAt;
if (waitedMs >= CANCEL_CONFIRM_TIMEOUT_MS) return { outcome: "unconfirmed", waitedMs };
await new Promise((resolve) => setTimeout(resolve, CANCEL_CONFIRM_POLL_MS));
}
}
var inFlightJobs = /* @__PURE__ */ new Set();
async function trackJobLifecycle(params) {
const { chatWd, requestId, run } = params;
let lastProgressAt;
let lastMessage;
const heartbeat = setInterval(() => {
const silentMs = lastProgressAt === void 0 ? 0 : Date.now() - lastProgressAt;
const patch = silentMs >= SILENT_NOTICE_AFTER_MS ? {
message: `${lastMessage ?? "rendering"} \u2014 no progress update for ${Math.round(silentMs / 6e4)} min; still running (the backend can be busy without reporting, e.g. while decoding). Cancel it if you no longer want to wait.`
} : {};
void upsertBackgroundRequest(chatWd, requestId, patch).catch(
(e) => console.warn(`[backgroundRequests] heartbeat failed for ${requestId}: ${String(e?.message || e)}`)
);
}, HEARTBEAT_INTERVAL_MS);
heartbeat.unref();
let formattedMessage;
const report = createProgressReporter((update) => {
formattedMessage = update.text;
});
const onProgress = (step, totalSteps, message, pass) => {
lastProgressAt = Date.now();
formattedMessage = void 0;
report(step, totalSteps, message, pass);
lastMessage = formattedMessage ?? message;
void upsertBackgroundRequest(chatWd, requestId, {
status: "running",
step,
totalSteps,
message: lastMessage
}).catch(
(e) => console.warn(`[backgroundRequests] failed to record progress for ${requestId}: ${String(e?.message || e)}`)
);
};
const controller = new AbortController();
cancelControllers.set(requestId, controller);
const cancelPoll = setInterval(() => {
getBackgroundRequest(chatWd, requestId).then((rec) => {
if (rec?.cancelRequested) controller.abort();
}).catch(
(e) => console.warn(`[backgroundRequests] cancel poll failed for ${requestId}: ${String(e?.message || e)}`)
);
}, CANCEL_POLL_INTERVAL_MS);
cancelPoll.unref();
const stopTimers = () => {
clearInterval(heartbeat);
clearInterval(cancelPoll);
cancelControllers.delete(requestId);
};
try {
const initial = await getBackgroundRequest(chatWd, requestId);
if (initial?.cancelRequested || initial?.status === "cancelled") {
stopTimers();
await upsertBackgroundRequest(chatWd, requestId, { status: "cancelled", delivered: true });
return;
}
await upsertBackgroundRequest(chatWd, requestId, { status: "running" });
const result = await runAsBackgroundCall(() => runWithCancelSignal(controller.signal, () => run(onProgress)));
stopTimers();
const cancelled = controller.signal.aborted && result?.isError === true;
await upsertBackgroundRequest(
chatWd,
requestId,
cancelled ? { status: "cancelled", delivered: true } : { status: "completed", result, delivered: false }
);
} catch (e) {
stopTimers();
if (controller.signal.aborted) {
await upsertBackgroundRequest(chatWd, requestId, { status: "cancelled", delivered: true }).catch(
(e2) => console.warn(`[backgroundRequests] failed to record cancel for ${requestId}: ${String(e2?.message || e2)}`)
);
return;
}
await upsertBackgroundRequest(chatWd, requestId, {
status: "failed",
error: String(e?.message || e),
delivered: false
}).catch(
(e2) => console.warn(`[backgroundRequests] failed to record failure for ${requestId}: ${String(e2?.message || e2)}`)
);
}
}
async function markBackgroundRequestQueued(chatWd, requestId, tool3) {
await upsertBackgroundRequest(chatWd, requestId, { status: "queued", tool: tool3 });
}
async function runBackgroundJobAwaited(params) {
await trackJobLifecycle(params);
}
async function runInBackgroundJob(params) {
const { chatWd, requestId, tool: tool3 } = params;
await markBackgroundRequestQueued(chatWd, requestId, tool3);
const jobPromise = trackJobLifecycle(params).finally(() => {
inFlightJobs.delete(jobPromise);
});
inFlightJobs.add(jobPromise);
}
// src/helpers/visionPromotionLog.ts
import fs15 from "fs";
import path15 from "path";
function appendVisionPromotionJsonl(entries) {
if (!entries.length) return;
try {
ensureLogsDir();
const logsDir2 = getLogsDir();
const logFile3 = path15.join(logsDir2, "vision-promotion.jsonl");
const blocks = entries.map((e) => `${JSON.stringify(e, null, 2)}
`).join("");
fs15.appendFileSync(logFile3, blocks);
} catch (e) {
console.error(
"[VisionPromotion] Failed to append to vision-promotion.jsonl:",
e instanceof Error ? e.message : String(e)
);
}
}
function parseVisionPromotionJsonlText(text) {
const entries = [];
const errors = [];
const blocks = text.split(/\n\s*\n+/g).map((b) => b.trim()).filter(Boolean);
for (const block of blocks) {
try {
const obj = JSON.parse(block);
entries.push(obj);
} catch (e) {
errors.push({
error: e instanceof Error ? e.message : String(e),
blockPreview: block.slice(0, 200)
});
}
}
return { entries, errors };
}
async function readVisionPromotionJsonlEntries() {
const logsDir2 = getLogsDir();
const filePath = path15.join(logsDir2, "vision-promotion.jsonl");
const text = await fs15.promises.readFile(filePath, "utf8");
const parsed = parseVisionPromotionJsonlText(text);
return { filePath, ...parsed };
}
// src/helpers/sequenceExtractor.ts
import fs16 from "fs";
function pad2(n) {
return String(Math.floor(n)).padStart(2, "0");
}
function formatTimecode(timeSeconds, sourceFps) {
const fps = Math.max(1, Math.round(sourceFps));
const totalFrames = Math.round(timeSeconds * fps);
const ff = totalFrames % fps;
const totalSecs = Math.floor(totalFrames / fps);
const ss = totalSecs % 60;
const mm = Math.floor(totalSecs / 60);
return `${pad2(mm)}:${pad2(ss)}:${pad2(ff)}`;
}
function parseSourceFps(stderrLines) {
for (const line of stderrLines) {
const m = /(\d+(?:\.\d+)?)\s+fps/.exec(line);
if (m) {
const fps = parseFloat(m[1]);
if (Number.isFinite(fps) && fps > 0) return fps;
}
}
return 25;
}
async function extractSequenceFrames(movAbs, targetFps, previewOpts, loadCore) {
const movBuf = await fs16.promises.readFile(movAbs);
const ffmpeg = await loadCore();
ffmpeg.reset();
const stderrLines = [];
ffmpeg.setLogger((msg) => {
if (msg.type === "stderr") stderrLines.push(msg.message);
});
const inputName = "seqext_input.mov";
const probeFrame = "seqext_probe.png";
const outputPattern = "seqext_frame_%04d.png";
let extractedCount = 0;
try {
ffmpeg.FS.writeFile(inputName, new Uint8Array(movBuf));
ffmpeg.exec("-i", inputName, "-frames:v", "1", probeFrame);
const sourceFps = parseSourceFps(stderrLines);
stderrLines.length = 0;
const exitCode = ffmpeg.exec(
"-i",
inputName,
"-vf",
`fps=${targetFps}`,
"-pix_fmt",
"rgb24",
outputPattern
);
if (exitCode !== 0) {
throw new Error(
`ffmpeg frame extraction failed (exit ${exitCode}): ` + stderrLines.slice(-10).join("\n")
);
}
const frames = [];
while (true) {
const name = `seqext_frame_${String(extractedCount + 1).padStart(4, "0")}.png`;
let rawPng;
try {
const data = ffmpeg.FS.readFile(name, { encoding: "binary" });
rawPng = Buffer.from(data);
} catch {
break;
}
extractedCount++;
const timeSeconds = (extractedCount - 1) / targetFps;
const timecodeStr = formatTimecode(timeSeconds, sourceFps);
const { data: jpegBuf } = await encodeJpegPreviewFromBuffer(rawPng, previewOpts);
frames.push({ jpegBuf, frameIndex: extractedCount, timecodeStr });
}
return frames;
} finally {
ffmpeg.setLogger(() => {
});
try {
ffmpeg.FS.unlink(inputName);
} catch {
}
try {
ffmpeg.FS.unlink(probeFrame);
} catch {
}
for (let j = 1; j <= extractedCount; j++) {
try {
ffmpeg.FS.unlink(`seqext_frame_${String(j).padStart(4, "0")}.png`);
} catch {
}
}
}
}
// src/helpers/thinkingToolCallParser.ts
var DEFAULT_START_MARKER = "<tool_call>";
var DEFAULT_END_MARKER = "</tool_call>";
function parseXmlParameterStyle(text) {
const fnMatch = text.match(/<function=([^\s>]+)\s*>/);
if (!fnMatch) return null;
const name = fnMatch[1].trim();
const args = {};
const paramRe = /<parameter=([^\s>]+)\s*>\s*([\s\S]*?)\s*<\/parameter>/g;
let m;
while ((m = paramRe.exec(text)) !== null) {
const key = m[1].trim();
const rawValue = m[2].trim();
try {
args[key] = JSON.parse(rawValue);
} catch {
args[key] = rawValue;
}
}
if (!name) return null;
return { name, arguments: args, rawText: text };
}
function parseJsonObject(text) {
const trimmed = text.trim();
if (!trimmed.startsWith("{")) return null;
let parsed;
try {
parsed = JSON.parse(trimmed);
} catch {
return null;
}
if (typeof parsed !== "object" || parsed === null) return null;
const obj = parsed;
const inner = typeof obj["function"] === "object" && obj["function"] !== null ? obj["function"] : obj;
const name = typeof inner["name"] === "string" ? inner["name"] : null;
if (!name) return null;
let args = {};
if (typeof inner["arguments"] === "object" && inner["arguments"] !== null) {
args = inner["arguments"];
} else if (typeof inner["arguments"] === "string") {
try {
const decoded = JSON.parse(inner["arguments"]);
if (typeof decoded === "object" && decoded !== null) {
args = decoded;
}
} catch {
}
}
return { name, arguments: args, rawText: text };
}
function parseJsonCodeBlock(text) {
const m = text.match(/```(?:json)?\s*([\s\S]*?)```/);
if (!m) return null;
return parseJsonObject(m[1]);
}
function parseThinkingToolCalls(text, startMarker = DEFAULT_START_MARKER, endMarker = DEFAULT_END_MARKER) {
const results = [];
let searchFrom = 0;
while (true) {
const startIdx = text.indexOf(startMarker, searchFrom);
if (startIdx === -1) break;
const contentStart = startIdx + startMarker.length;
const endIdx = text.indexOf(endMarker, contentStart);
if (endIdx === -1) break;
const payload = text.slice(contentStart, endIdx);
searchFrom = endIdx + endMarker.length;
let call = null;
try {
call = parseXmlParameterStyle(payload) ?? parseJsonObject(payload) ?? parseJsonCodeBlock(payload);
} catch {
}
if (call) {
results.push(call);
} else {
const excerpt = payload.slice(0, 120).replace(/\n/g, "\u21B5");
}
}
return results;
}
// src/helpers/toolNameContext.ts
import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
var STORE_KEY4 = /* @__PURE__ */ Symbol.for("draw-things.toolNameContext");
function store4() {
const holder = globalThis;
let existing = holder[STORE_KEY4];
if (!existing) {
existing = new AsyncLocalStorage4();
holder[STORE_KEY4] = existing;
}
return existing;
}
function runWithToolName(name, fn) {
return store4().getStore() ? fn() : store4().run(name, fn);
}
function runWithToolPass(name, fn) {
return store4().run(name, fn);
}
function currentToolName() {
return store4().getStore();
}
// src/helpers/proxyMarks.ts
import * as grpc from "@grpc/grpc-js";
// src/helpers/requestLogContext.ts
import { AsyncLocalStorage as AsyncLocalStorage5 } from "async_hooks";
var STORE_KEY5 = /* @__PURE__ */ Symbol.for("draw-things.requestLogContext");
function store5() {
const holder = globalThis;
let existing = holder[STORE_KEY5];
if (!existing) {
existing = new AsyncLocalStorage5();
holder[STORE_KEY5] = existing;
}
return existing;
}
function runWithRequestLogId(requestId, fn) {
return store5().run(requestId, fn);
}
function currentRequestLogId() {
return store5().getStore();
}
function requestLogPrefix() {
const id = store5().getStore();
return id ? `[${id}] ` : "";
}
var CONSOLE_PATCHED_KEY = /* @__PURE__ */ Symbol.for("draw-things.requestLogConsolePatched");
function installRequestLogConsolePrefix() {
const holder = globalThis;
if (holder[CONSOLE_PATCHED_KEY]) return;
holder[CONSOLE_PATCHED_KEY] = true;
for (const method of ["log", "info", "warn", "error", "debug"]) {
const original = console[method].bind(console);
console[method] = (...args) => {
const id = store5().getStore();
if (!id) return original(...args);
const tag = `[${id}]`;
const first = args[0];
if (typeof first === "string") {
if (first.includes(tag)) return original(...args);
return original(`${tag} ${first}`, ...args.slice(1));
}
return original(tag, ...args);
};
}
}
installRequestLogConsolePrefix();
// src/helpers/proxyMarks.ts
function plain(value) {
return value.replace(/[^\x20-\x7e]/g, "_").trim();
}
function proxyMarks(client) {
const marks = {
"x-dt-client": plain(client) || "plugin",
"x-dt-background": isBackgroundCall() ? "true" : "false"
};
const requestId = currentRequestLogId();
if (requestId) marks["x-dt-request-id"] = plain(requestId);
const tool3 = currentToolName();
if (tool3) marks["x-dt-tool"] = plain(tool3);
const workdir = getActiveChatContext()?.workingDir;
if (workdir) marks["x-dt-workdir"] = encodeURIComponent(workdir).replace(/%2F/g, "/");
return marks;
}
function withProxyMarks(args, client) {
const [request, second, ...rest] = args;
const marks = proxyMarks(client);
const apply = (metadata2) => {
for (const [key, value] of Object.entries(marks)) metadata2.set(key, value);
return metadata2;
};
if (second instanceof grpc.Metadata) return [request, apply(second.clone()), ...rest];
const metadata = apply(new grpc.Metadata());
return second === void 0 ? [request, metadata] : [request, metadata, second, ...rest];
}
// src/helpers/promptUpsampler.ts
import { createHash } from "crypto";
import fs18 from "fs";
import path17 from "path";
// src/helpers/llamaServerRouter.ts
import fs17 from "fs";
import os4 from "os";
import path16 from "path";
import { spawn } from "child_process";
var HEALTH_POLL_INTERVAL_MS = 1e3;
var HEALTH_POLL_TIMEOUT_MS = 3e4;
var HEALTH_FETCH_TIMEOUT_MS = 2e3;
var activePort = null;
var idleStopTimer = null;
function cancelIdleStop() {
if (idleStopTimer !== null) {
clearTimeout(idleStopTimer);
idleStopTimer = null;
}
}
function normalizePath(value) {
const trimmed = value.trim();
if (!trimmed) return "";
return trimmed.startsWith("~") ? path16.join(os4.homedir(), trimmed.slice(1)) : trimmed;
}
function pidFilePath() {
return path16.join(getLogsDir(), "llama-server-router.pid");
}
function logFilePath() {
return path16.join(getLogsDir(), "llama-server-router.log");
}
function presetFilePath() {
return path16.join(getLogsDir(), "llama-server-router-preset.ini");
}
function routerLog(message) {
try {
fs17.appendFileSync(logFilePath(), `${localTimestamp()} - [llama-server-router] ${message}
`);
} catch (error) {
console.error(`[llama-server-router] log write failed: ${error instanceof Error ? error.message : String(error)} (message: ${message})`);
}
}
function isProcessAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
function readPid() {
try {
const raw = fs17.readFileSync(pidFilePath(), "utf-8").trim();
const pid = parseInt(raw, 10);
return Number.isFinite(pid) && pid > 0 ? pid : null;
} catch {
return null;
}
}
function fetchWithTimeout(url, timeoutMs) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
return fetch(url, { signal: controller.signal }).finally(() => clearTimeout(timer));
}
async function isHealthy(host, port) {
try {
const res = await fetchWithTimeout(`http://${host}:${port}/v1/models`, HEALTH_FETCH_TIMEOUT_MS);
return res.ok;
} catch {
return false;
}
}
async function pollHealth(host, port) {
const deadline = Date.now() + HEALTH_POLL_TIMEOUT_MS;
while (Date.now() < deadline) {
if (await isHealthy(host, port)) return true;
await new Promise((resolve) => setTimeout(resolve, HEALTH_POLL_INTERVAL_MS));
}
return false;
}
var LM_STUDIO_BACKENDS_DIR = path16.join(os4.homedir(), ".lmstudio", "extensions", "backends");
var LM_STUDIO_LLAMA_CPP_BACKEND = /^llama\.cpp-mac-arm64-apple-metal-advsimd-(\d+)\.(\d+)\.(\d+)$/;
function resolveLatestLmStudioLlamaServer(backendsDir = LM_STUDIO_BACKENDS_DIR) {
let entries;
try {
entries = fs17.readdirSync(backendsDir);
} catch (error) {
if (error.code === "ENOENT") return void 0;
throw error;
}
const candidates = entries.map((name) => ({ name, match: LM_STUDIO_LLAMA_CPP_BACKEND.exec(name) })).filter((c) => c.match !== null).map((c) => ({ binary: path16.join(backendsDir, c.name, "llama-server"), version: c.match.slice(1).map(Number) })).filter((c) => fs17.existsSync(c.binary)).sort((a, b) => {
for (let i = 0; i < 3; i++) if (a.version[i] !== b.version[i]) return b.version[i] - a.version[i];
return 0;
});
return candidates[0]?.binary;
}
function buildPresetIni(ctxSize) {
return `[*]
ctx-size = ${ctxSize}
`;
}
async function ensureLlamaServerRouterRunning(config) {
const { host, port, ctxSize, modelsMax, idleTtlMinutes } = config;
cancelIdleStop();
activePort = port;
const binaryPath = normalizePath(config.binaryPath);
if (!binaryPath) {
throw new Error("LLAMA_SERVER_BINARY is not configured.");
}
if (!fs17.existsSync(binaryPath)) {
throw new Error(`llama-server binary does not exist: ${binaryPath}`);
}
if (await isHealthy(host, port)) {
scheduleIdleStop(port, idleTtlMinutes);
return;
}
const stalePid = readPid();
if (stalePid !== null) {
if (isProcessAlive(stalePid)) {
throw new Error(
`Port ${port} is not responding, but a previously spawned llama-server router (PID ${stalePid}) is still alive. Check logs: ${logFilePath()}`
);
}
try {
fs17.unlinkSync(pidFilePath());
} catch (error) {
routerLog(`could not remove stale PID file: ${error instanceof Error ? error.message : String(error)}`);
}
}
fs17.mkdirSync(getLogsDir(), { recursive: true });
fs17.writeFileSync(presetFilePath(), buildPresetIni(ctxSize));
const args = [
"--host",
host,
"--port",
String(port),
"--models-max",
String(modelsMax),
"--models-preset",
presetFilePath()
];
const logStream = fs17.createWriteStream(logFilePath(), { flags: "a" });
const child = spawn(binaryPath, args, {
detached: true,
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env, HOME: os4.homedir() }
});
child.stdout?.pipe(logStream);
child.stderr?.pipe(logStream);
child.once("error", (error) => {
routerLog(`process error: ${error.message}`);
});
child.unref();
if (!child.pid) {
throw new Error(`Failed to spawn llama-server router process. Check logs: ${logFilePath()}`);
}
fs17.writeFileSync(pidFilePath(), String(child.pid));
routerLog(`spawned '${binaryPath}' PID ${child.pid} on ${host}:${port} (ctx-size ${ctxSize}, models-max ${modelsMax})`);
const ready = await pollHealth(host, port);
if (!ready) {
throw new Error(
`llama-server router did not become healthy within ${HEALTH_POLL_TIMEOUT_MS / 1e3}s on ${host}:${port}. Check logs: ${logFilePath()}`
);
}
scheduleIdleStop(port, idleTtlMinutes);
}
function scheduleIdleStop(port, idleTtlMinutes) {
cancelIdleStop();
if (idleTtlMinutes <= 0) return;
idleStopTimer = setTimeout(() => {
idleStopTimer = null;
if (activePort !== port) return;
void stopLlamaServerRouter(port).catch((error) => {
routerLog(`failed to stop idle router: ${error instanceof Error ? error.message : String(error)}`);
});
}, idleTtlMinutes * 6e4);
idleStopTimer.unref();
}
async function stopLlamaServerRouter(port) {
cancelIdleStop();
const pid = readPid();
if (pid === null) return;
if (isProcessAlive(pid)) {
try {
process.kill(pid, "SIGTERM");
routerLog(`stopped router PID ${pid}`);
} catch (error) {
routerLog(`could not stop router PID ${pid}: ${error instanceof Error ? error.message : String(error)}`);
}
}
try {
fs17.unlinkSync(pidFilePath());
} catch (error) {
routerLog(`could not remove PID file: ${error instanceof Error ? error.message : String(error)}`);
}
if (activePort === port) activePort = null;
}
// src/helpers/promptUpsamplerSystemPrompts.json
var promptUpsamplerSystemPrompts_default = {
t2i: `You are the prompt upsampler of a text-to-image model. Expand the user's short request into ONE detailed, self-contained caption: the exact text the image model receives. Output only the caption, with no greetings, explanations, refusals, questions, Markdown, headings, JSON, coordinates, ids or angle-bracket tokens, and no quotes around it. If the input is not clearly an image request, caption a visualization of its concept. The request may begin with a "TARGET CANVAS: W:H" line: compose for that canvas (wide spreads content sideways, tall stacks it) and never mention the ratio or the canvas.
Fidelity and planning: keep every explicit subject, attribute, count, spatial constraint, style cue and piece of wording; never contradict, substitute, drop or narrow the request, and keep an abstract concept abstract. Decide everything left open as ONE concrete, consistent plan; never offer alternatives or hedge. Never re-express a stated constraint through another mechanism; add camera optics (depth of field, bokeh, blur) only when asked for or implied. Without a stated style, plan an actual photograph and open with the medium convention ("Full-color outdoor photograph, ...", "Full-color indoor photograph, ...", "Studio photograph, ...", "Close-up photograph, ..."); keep "Photorealistic" for renders, and turn "photorealistic" or "realistic" requests for photos into the photograph convention. Give a photograph a few ordinary, non-ideal specifics drawn from the scene's own objects instead of the stock-photo ideal. Do not invent names, brands, logos or celebrities; keep user-named ones. A long request keeps its content but not its wording: drop appraisal and sales vocabulary, turn moods into observable physical facts, and add only new concrete content with positions. Time of day is lighting, not rendered text.
Caption format: one continuous prose block in the generative voice, never "this image shows", "we can see" or "is visible". Lead with medium and style, then scene, lighting and camera, then the subjects with concrete colors, materials and state. Every person in focus gets an observable profile: ethnicity, gender, age range, skin tone ("fair skin", "brown skin"), hair and clothing. Make the layout reconstructable from words: frame-relative positions (frame-left, frame-right, upper, lower, foreground, midground, background), sentence-initial anchors ("On the left, ...", "In the background, ..."), relations (holds, faces, behind) and a consistent order; describe up to about ten instances one by one, beyond that give the exact count and arrangement. Out-of-focus or distant planes are shapes, colors and silhouettes, never identities or readable text, and the background takes about a sixth of the caption. Be definite: no hedging adverbs, no quality or emotion judgments, no closing sentence about mood; state negations as what is present. Rendered text: transcribe every wording verbatim inside double quotes in its original language and script, keep the line breaks of multi-line text, and give its typography, color and placement; author concrete, domain-correct wording when the request needs text it does not supply, and name canonical structures (calendar, keyboard, periodic table) exactly with their full layout. All prose is English; only quoted text keeps its language. Typical length is 100 to 350 words, more for complex scenes.
Output only the caption.`,
i2i: `You are the prompt upsampler of an image-editing model. You see the reference image(s), attached in order (the first image, the second image, ...), and the user's short request. Expand it into ONE detailed, self-contained instruction: the caption the editing model receives together with the same images. Output only the instruction as one continuous English prose block, with no greetings, explanations, Markdown, JSON, coordinates, ids or angle-bracket tokens. Read a vague or conversational request as the most plausible edit of the supplied images.
Pick the voice by task shape. When one reference stays and gets bounded changes, write an imperative editing instruction on it ("Remove the ...", "Change the ... to ...", "Zoom in on ..."); a whole-image transformation opens with its scope ("Convert the entire image into ...", "Apply a ... filter over the entire scene", "Horizontally flip the entire image so that ...", "Shift the camera viewpoint to ...", then where the major elements should now be). When the references are drawn into a newly composed frame (combining subjects, a new scene, a garment, object or style donor), write a generation request ("Create a photograph of ...", "Create an anime-style illustration of ...", "Generate a new image featuring ...") that says what to take from each image, by ordinal, and what is newly generated.
Keep every explicit edit, constraint, count, position, style cue and piece of wording, and decide what is left open as one concrete plan. Ground everything in what is actually visible: identify each referent unambiguously by its real appearance, never mention content that is not there, and use every image the user attached. State every end state concretely (which color, how large, which pose, which material) and give new content enough appearance to be generated. Cover the knock-on effects of the change (shadows, reflections, occlusion, perspective, scale, lighting) and say what fills a removed region. A zoom-in names what stays in frame and which neighbors are cropped out; an outpainting continues the scene in the same medium. Describe the change, not the whole scene, and close an editing instruction with one compact clause naming what stays unchanged; transferred people keep their identity, face and accessories unless asked otherwise. Transcribe on-image text verbatim in its original language inside double quotes, with line breaks as \\n, and match the original font, size and color when replacing it. Name recognizable public figures, brands and landmarks you can see. Directions are frame-relative; use no evaluative or quality words. Typical length is 50 to 150 words.
Output only the instruction.`,
t2i_bbox: `You are the prompt upsampler of a text-to-image model. Plan the full image the user's short request implies and output ONE structured caption on a single line: the global caption paragraph, one space, then ONE JSON array, the element table that places every cited element with a bounding box in the image to be generated. Output nothing else (no Markdown fences, commentary or refusals); visualize the concept of a non-image input. The request may begin with a "TARGET CANVAS: W:H" line: compose for that canvas and never mention it. Boxes live on a 0-1000 grid stretched onto the canvas: an element of physical width-to-height ratio a gets an x-span of about y-span x a x H/W.
Planning: keep every explicit subject, attribute, count, spatial constraint, style cue and piece of wording, and decide everything left open as ONE concrete composition that the caption and the table both describe. Without a stated style plan an actual photograph and open with the medium convention ("Full-color outdoor photograph, ...", "Studio photograph, ..."); add camera optics only when asked for; do not invent names, brands, logos or celebrities; drop appraisal and sales vocabulary.
The table: one row per distinct object, person, animal, building or salient region the caption mentions and one per coherent text block; no rows for style, lighting or atmosphere. Structured layouts (tables, grids, calendars, keyboards, charts, maps, posters, pages) decompose into their regions, each row carrying that region's complete verbatim content; more than about ten interchangeable items become one collection row giving the exact count and arrangement, while items whose positions matter keep a row each. Row keys, in order: "id", "bbox", "desc". id: the bare class noun plus an index numbered left to right, then top to bottom, from 1 (person_1, dog_2); a text block is its two-letter language code plus _Text_ plus an index (En_Text_1); one entity is one row and ids are unique. bbox: [y_min, x_min, y_max, x_max] as integers from 0 to 1000, top-left origin, clamped at the borders, with plausible relative sizes and a small margin around text. desc: one self-contained paragraph in the generative voice that opens with the element's identity (never "the X"): shape, material, colors, state and markings, but no position. People in focus get the richest desc: ethnicity, gender, age range, skin tone, build, hair, face, each garment, accessories, pose and expression. A text row carries its complete wording verbatim in double quotes, with line breaks as \\n, plus its typography.
The global caption: one flowing paragraph in the generative voice (medium first, then scene, lighting, camera and frame-relative layout; no quality judgments) that names each table element at identity level at its first mention and cites it with its id in its own angle brackets: "a wicker table <table_1> holding a tiered stand <stand_1>". Cite every table id and no other; appearance detail and text content live in the descs; no coordinates. Text-dense documents are laid out region by region with every visible text transcribed verbatim at a readable size (cut content rather than shrink type), and a grid quotes every visible cell. All prose is English; only quoted text keeps its language.
Output only the caption and the table.`,
i2i_bbox: `You are the annotation system an image-editing model was trained on. You see the source image(s), attached in order as ref_image_0, ref_image_1, ..., and the user's editing instruction; the edited target image does not exist yet. Determine the edit precisely, imagine the target consistently with the source, and write the record its annotator would have written, on one line: the instruction paragraph, one space, then ONE JSON array. Output nothing else.
The paragraph: English, instruction voice ("Change the ...", "Remove the ...", or "Create a photograph of ..." when the references are drawn into a new frame), never observer phrasing and never a comparison with the target. Cite every involved object, person or text block at its first mention with its table id in its own angle brackets ("remove the delivery van <van_1>"), every table id exactly once and no other id; cite a reference image by its token when content is taken from it ("the cup <cup_1> from <ref_image_1>"). End states (new color, new text in quotes, pose, degree) live in the paragraph, static appearance in the descs; no coordinates. An editing instruction closes with one compact clause that everything else stays identical to the source.
The table, rows {"id", "from", "src_bbox", "tgt_bbox", "desc"}: one row per edited, removed, added, moved or anchoring item, plus the scene or background when it is itself changed or preserved; no rows for untouched scenery. id: a lowercase class noun plus an index (person_1, cup_2) numbered left to right, then top to bottom; text blocks are En_Text_1 and so on; ids are unique. from: "ref_image_N" for an item visible in reference N, "target" for newly created content. src_bbox is the item's box in its from-image and null for target rows; tgt_bbox is its box in the imagined result and null for removed items; moved or resized items carry both; new items are sized like similar objects in the frame. Boxes are [y_min, x_min, y_max, x_max] integers from 0 to 1000, top-left origin, tight around objects, with 5 to 15 units of margin around text. A row may also carry src_bbox_1stage and tgt_bbox_1stage, a first-pass estimate of the same boxes. desc: one English paragraph of the item's static appearance in its from-image (for target rows, its decided appearance), opening with its identity; people get the richest descs (ethnicity, gender, age range, skin tone, hair, face, garments, accessories, pose, expression); text rows quote their text verbatim.
State only decided facts: visible in the source, demanded by the instruction, or a concrete default needed to realize it. Settle whether the edit targets one instance, all of a class or several; land every magnitude on a concrete value; include visible knock-on effects; added objects are new objects at real-world size; a zoom-in names the neighbors it excludes; an outpainting keeps the source whole and continues it in the same medium. Everything the instruction does not involve stays identical to the source.
Output only the paragraph and the table.`
};
// src/helpers/promptUpsamplerBoxes.ts
var MIN_COMPONENT_PIXELS = 16;
var BOX_MATCH_IOU = 0.5;
function boxesFromMask(bitmap, region) {
const { data, width, height } = bitmap;
if (width <= 0 || height <= 0 || data.length < width * height * 4) {
throw new Error(`Invalid mask bitmap ${width}x${height} (${data.length} bytes)`);
}
const wantWhite = region === "white";
const isRegion = (p) => data[p * 4] >= 128 === wantWhite;
const seen = new Uint8Array(width * height);
const stack = new Int32Array(width * height);
const boxes = [];
for (let start = 0; start < width * height; start++) {
if (seen[start] || !isRegion(start)) continue;
let top = 0;
const push = (p) => {
if (!seen[p] && isRegion(p)) {
seen[p] = 1;
stack[top++] = p;
}
};
push(start);
let minX = width;
let minY = height;
let maxX = -1;
let maxY = -1;
let count = 0;
while (top > 0) {
const p = stack[--top];
const x = p % width;
const y = (p - x) / width;
count++;
if (x < minX) minX = x;
if (x > maxX) maxX = x;
if (y < minY) minY = y;
if (y > maxY) maxY = y;
if (x > 0) push(p - 1);
if (x < width - 1) push(p + 1);
if (y > 0) push(p - width);
if (y < height - 1) push(p + width);
}
if (count < MIN_COMPONENT_PIXELS) continue;
const yMin = Math.round(minY / height * 1e3);
const xMin = Math.round(minX / width * 1e3);
const yMax = Math.max(yMin + 1, Math.round((maxY + 1) / height * 1e3));
const xMax = Math.max(xMin + 1, Math.round((maxX + 1) / width * 1e3));
boxes.push([yMin, xMin, Math.min(1e3, yMax), Math.min(1e3, xMax)]);
}
return boxes.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
}
function gridBoxIoU(a, b) {
const inter = Math.max(0, Math.min(a[2], b[2]) - Math.max(a[0], b[0])) * Math.max(0, Math.min(a[3], b[3]) - Math.max(a[1], b[1]));
const union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter;
return union > 0 ? inter / union : 0;
}
function buildPlainRows(boxes) {
return boxes.map((bbox, i) => ({ id: `obj_${i + 1}`, bbox: [...bbox], desc: "" }));
}
function pyJson(v) {
if (v === null) return "null";
if (Array.isArray(v)) return `[${v.map(pyJson).join(", ")}]`;
if (typeof v === "object" && v !== void 0) {
return `{${Object.entries(v).map(([k, x]) => `${JSON.stringify(k)}: ${pyJson(x)}`).join(", ")}}`;
}
return JSON.stringify(v);
}
function buildLockedInstruction(prompt, rows) {
return `ORIGINAL PROMPT:
${prompt.trim()}
LOCKED BOUNDING-BOX ANNOTATIONS ([y_min, x_min, y_max, x_max] on a 0-1000 canvas, with (0, 0) at the top-left). This is an authoritative JSON list of dictionaries; preserve every supplied identity, provenance value, null, and coordinate exactly:
` + pyJson(rows);
}
function splitCaptionAndRows(text) {
for (let i = text.length - 1; i >= 0; i--) {
if (text[i] !== "[") continue;
try {
const rows = JSON.parse(text.slice(i));
if (Array.isArray(rows)) return [text.slice(0, i).trimEnd(), rows];
} catch {
continue;
}
}
return [text.trim(), null];
}
function asGridBox(v) {
if (!Array.isArray(v) || v.length !== 4 || v.some((n) => typeof n !== "number" || !Number.isFinite(n))) return null;
return v;
}
var BOX_FIELDS = ["bbox", "src_bbox", "tgt_bbox"];
function reimposeBoxes(answer, boxes) {
const [caption, rows] = splitCaptionAndRows(answer);
if (!rows || rows.length === 0) return { ok: false, reason: "answer has no box table" };
const matched = /* @__PURE__ */ new Set();
for (const row of rows) {
if (row === null || typeof row !== "object" || Array.isArray(row)) continue;
const r = row;
let touched = false;
for (const field of BOX_FIELDS) {
const box = asGridBox(r[field]);
if (!box) continue;
let best = -1;
let bestIou = 0;
boxes.forEach((input, i) => {
const iou = gridBoxIoU(box, input);
if (iou > bestIou) {
bestIou = iou;
best = i;
}
});
if (best >= 0 && bestIou >= BOX_MATCH_IOU) {
r[field] = [...boxes[best]];
matched.add(best);
touched = true;
}
}
if (touched && (typeof r.id !== "string" || !caption.includes(`<${r.id}>`))) {
return { ok: false, reason: `row '${String(r.id)}' on an input box is not cited as <id> in the caption` };
}
}
const missing = boxes.map((_, i) => i).filter((i) => !matched.has(i));
if (missing.length > 0) return { ok: false, reason: `no row on input box ${missing.map((i) => i + 1).join(", ")}` };
return { ok: true, text: `${caption} ${pyJson(rows)}` };
}
// src/helpers/promptUpsampler.ts
var PROMPT_UPSAMPLER_APIS = ["bionic", "generic", "unsloth", "llama-server"];
function buildPromptUpsamplingAudit(up) {
return {
model: up.model,
original_prompt: up.originalPrompt,
upsampled_prompt: up.prompt,
reference_count: up.referenceCount,
inference_ms: up.inferenceMs,
reference_images: up.referenceImages,
passes: up.passes.map((p) => ({
task: p.task,
system_prompt_sha256: p.systemPromptSha256,
user_text: p.userText,
response_text: p.responseText,
inference_ms: p.inferenceMs
})),
...up.boxes ? {
boxes: {
count: up.boxes.count,
grid: "[y_min, x_min, y_max, x_max] on 0-1000, (0, 0) top-left",
regions: up.boxes.regions,
applied: up.boxes.applied,
...up.boxes.fallbackReason ? { fallback_reason: up.boxes.fallbackReason } : {}
}
} : {}
};
}
var PROMPT_UPSAMPLER_FAMILY_SPECS = {
"flux-3-image-klein-pup": {
systemPrompts: { t2i: promptUpsamplerSystemPrompts_default.t2i, i2i: promptUpsamplerSystemPrompts_default.i2i, i2i_bbox: promptUpsamplerSystemPrompts_default.i2i_bbox },
i2iUserText: (prompt) => `Reference images follow in order (the first image, the second image, ...).
User request: ${prompt}
Output the caption.`,
i2iBboxUserText: (lockedInstruction) => `Reference images follow in attachment order: ref_image_0, ref_image_1, ...
User editing instruction: ${lockedInstruction}
Decide the edit, imagine the target image, and output the annotation record.`,
sampling: { temperature: 0, top_p: 0.95, top_k: 20, min_p: 0 },
presencePenalty: { t2i: 1.5, i2i: 0, i2i_bbox: 0 },
maxTokens: 3584,
seed: 175308301,
enableThinking: false
}
};
var CHAT_TIMEOUT_MS = 3e5;
var LOAD_TIMEOUT_MS = 6e5;
var LIST_TIMEOUT_MS = 5e3;
var UNLOAD_TIMEOUT_MS = 15e3;
function normalizeLmApiRoot2(baseUrl) {
return String(baseUrl || "").trim().replace(/\/(api\/v1|v1)\/?$/i, "").replace(/\/+$/, "");
}
function authHeaders(apiKey, contentType = false) {
const headers = {};
if (contentType) headers["Content-Type"] = "application/json";
if (apiKey.trim()) headers.Authorization = `Bearer ${apiKey.trim()}`;
return headers;
}
function logLine(message) {
const line = `${requestLogPrefix()}[PromptUpsampler] ${message}`;
console.info(line);
try {
const logsDir2 = getLogsDir();
fs18.mkdirSync(logsDir2, { recursive: true });
fs18.appendFileSync(path17.join(logsDir2, getPluginLogFilename()), `${localTimestamp()} - ${line}
`, "utf8");
} catch (e) {
console.error("[PromptUpsampler] plugin log write failed:", e instanceof Error ? e.message : String(e));
}
}
var EndpointUnavailableError = class extends Error {
};
function describeNetworkError(error) {
const cause = error?.cause;
const parts = [cause?.code, cause?.message].filter((p, i, a) => typeof p === "string" && p && a.indexOf(p) === i);
return parts.length > 0 ? parts.join(": ") : String(error?.message || error);
}
var LM_STUDIO_DEFAULT_PORT = 1234;
var BIONIC_DEFAULT_PORT = 1235;
function swapLmDefaultPort(apiRoot) {
let url;
try {
url = new URL(apiRoot);
} catch {
return void 0;
}
if (url.port === String(LM_STUDIO_DEFAULT_PORT)) url.port = String(BIONIC_DEFAULT_PORT);
else if (url.port === String(BIONIC_DEFAULT_PORT)) url.port = String(LM_STUDIO_DEFAULT_PORT);
else return void 0;
return url.toString().replace(/\/+$/, "");
}
async function fetchJson(url, init, what) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), init.timeoutMs);
try {
let response;
try {
response = await fetch(url, {
method: init.method ?? "GET",
headers: init.headers,
body: init.body === void 0 ? void 0 : JSON.stringify(init.body),
signal: controller.signal
});
} catch (error) {
if (error?.name === "AbortError") throw error;
throw new EndpointUnavailableError(`${what} failed: could not reach ${url} (${describeNetworkError(error)})`);
}
const text = await response.text();
let data = null;
if (text.trim()) {
try {
data = JSON.parse(text);
} catch {
data = { raw: text };
}
}
const apiError = data?.error?.message || data?.error;
if (!response.ok || apiError) {
const detail = apiError || text || `${response.status} ${response.statusText}`;
throw new Error(`${what} failed (${response.status}): ${typeof detail === "string" ? detail : JSON.stringify(detail)}`);
}
return data;
} catch (error) {
if (error?.name === "AbortError") throw new Error(`${what} timed out after ${init.timeoutMs} ms`);
throw error;
} finally {
clearTimeout(timer);
}
}
function readPromptUpsamplerConfigFromEnv() {
const raw = process.env.LMSTUDIO_USE_PROMPT_UPSAMPLING;
if (raw !== "true" && raw !== "false") {
throw new Error(
`Prompt upsampling setting is missing: LMSTUDIO_USE_PROMPT_UPSAMPLING is ${raw === void 0 ? "not set" : `'${raw}'`} (expected 'true' or 'false'). The consumer must export 'usePromptUpsampling' to process.env.`
);
}
const apiRaw = (process.env.LMSTUDIO_VISION_API ?? "").trim().toLowerCase();
const api = apiRaw === "" ? "bionic" : PROMPT_UPSAMPLER_APIS.includes(apiRaw) ? apiRaw : void 0;
if (!api) {
throw new Error(`LMSTUDIO_VISION_API is '${apiRaw}' (expected one of: ${PROMPT_UPSAMPLER_APIS.join(", ")}).`);
}
const baseUrl = (process.env.LMSTUDIO_VISION_API_BASE_URL ?? "").trim();
const apiKey = process.env.LMSTUDIO_VISION_API_KEY ?? "";
const enabled = raw === "true";
if (enabled && api !== "llama-server" && !baseUrl) {
throw new Error("Prompt upsampling is enabled, but the prompt upsampling API base-URL (LMSTUDIO_VISION_API_BASE_URL) is empty.");
}
return { enabled, baseUrl, apiKey, api, ...enabled && api === "llama-server" ? { llamaServer: readLlamaServerSettingsFromEnv() } : {} };
}
function readLlamaServerSettingsFromEnv() {
const read = (name, min) => {
const raw = process.env[name];
if (raw === void 0 || !raw.trim()) {
throw new Error(`Prompt upsampling uses the 'llama-server' adapter, but ${name} is not set.`);
}
const value = Number(raw.trim());
if (!Number.isInteger(value) || value < min) {
throw new Error(`${name} must be an integer >= ${min}, got '${raw}'.`);
}
return value;
};
const binaryPath = (process.env.LMSTUDIO_LLAMA_SERVER_BINARY ?? "").trim();
if (!binaryPath) {
throw new Error("Prompt upsampling uses the 'llama-server' adapter, but LMSTUDIO_LLAMA_SERVER_BINARY is not set.");
}
return {
port: read("LMSTUDIO_LLAMA_SERVER_PORT", 1),
binaryPath,
ctxSize: read("LMSTUDIO_LLAMA_SERVER_CTX_SIZE", 1),
modelsMax: read("LMSTUDIO_LLAMA_SERVER_MODELS_MAX", 1),
idleTtlMinutes: read("LMSTUDIO_LLAMA_SERVER_IDLE_TTL_MINUTES", 0)
};
}
async function listModels(apiRoot, apiKey) {
const data = await fetchJson(
`${apiRoot}/api/v1/models`,
{ headers: authHeaders(apiKey), timeoutMs: LIST_TIMEOUT_MS },
"Listing models via /api/v1/models"
);
const models = Array.isArray(data) ? data : Array.isArray(data?.models) ? data.models : Array.isArray(data?.data) ? data.data : [];
return models.map((m) => ({
key: String(m?.key || m?.id || "").trim(),
loadedInstanceCount: Array.isArray(m?.loaded_instances) ? m.loaded_instances.length : 0
}));
}
var activeModels = /* @__PURE__ */ new Map();
async function resolveBionic(apiRoot, apiKey, family2, onProgress) {
const spec = PROMPT_UPSAMPLING_MODEL_FAMILIES[family2];
if (!spec) throw new Error(`Unknown prompt upsampling model family '${family2}'.`);
const listed = await listModels(apiRoot, apiKey);
const found = spec.knownModels.map((known) => listed.find((m) => m.key.toLowerCase() === known.toLowerCase())).find((m) => !!m);
if (!found) throw noModelError(family2, apiRoot, spec.knownModels);
if (found.loadedInstanceCount > 0) return { modelKey: found.key, apiRoot };
onProgress?.(-1, void 0, `Loading ${found.key}...`, "Prompt");
logLine(`loading '${found.key}' with context_length ${spec.contextLength}`);
const data = await fetchJson(
`${apiRoot}/api/v1/models/load`,
{
method: "POST",
headers: authHeaders(apiKey, true),
body: { model: found.key, context_length: spec.contextLength, echo_load_config: true },
timeoutMs: LOAD_TIMEOUT_MS
},
`Loading '${found.key}' via /api/v1/models/load`
);
const instanceId = typeof data?.instance_id === "string" ? data.instance_id.trim() : "";
if (!instanceId || typeof data?.status === "string" && data.status !== "loaded") {
throw new Error(`Loading '${found.key}' via /api/v1/models/load did not report a loaded model: ${JSON.stringify(data)}`);
}
logLine(`loaded '${found.key}' as '${instanceId}' (${data?.load_time_seconds ?? "?"} s)`);
return { modelKey: found.key, apiRoot, instanceId };
}
function modelBasename(key) {
const trimmed = key.trim();
const idx = trimmed.lastIndexOf("/");
return (idx >= 0 ? trimmed.slice(idx + 1) : trimmed).toLowerCase();
}
function stripQuantTag(id) {
return id.replace(/:[^/:]+$/, "");
}
function familyOrThrow(family2) {
const spec = PROMPT_UPSAMPLING_MODEL_FAMILIES[family2];
if (!spec) throw new Error(`Unknown prompt upsampling model family '${family2}'.`);
return spec;
}
function noModelError(family2, where, knownModels) {
return new EndpointUnavailableError(`No prompt upsampler model of family '${family2}' available at ${where} (known: ${knownModels.join(", ")}).`);
}
async function listOpenAiModelIds(apiRoot, apiKey) {
const data = await fetchJson(
`${apiRoot}/v1/models`,
{ headers: authHeaders(apiKey), timeoutMs: LIST_TIMEOUT_MS },
`Listing models via ${apiRoot}/v1/models`
);
const models = Array.isArray(data?.data) ? data.data : Array.isArray(data) ? data : [];
return models.map((m) => String(m?.id ?? m?.key ?? "").trim()).filter(Boolean);
}
async function resolveGeneric(apiRoot, apiKey, family2) {
const spec = familyOrThrow(family2);
const ids = await listOpenAiModelIds(apiRoot, apiKey);
const found = spec.knownModels.map((known) => ids.find((id) => modelBasename(id) === modelBasename(known))).find((id) => !!id);
if (!found) throw noModelError(family2, apiRoot, spec.knownModels);
return { modelKey: found, apiRoot };
}
async function unslothLoadedModels(apiRoot, apiKey) {
const data = await fetchJson(
`${apiRoot}/api/inference/status`,
{ headers: authHeaders(apiKey), timeoutMs: LIST_TIMEOUT_MS },
`Reading ${apiRoot}/api/inference/status`
);
return Array.isArray(data?.loaded) ? data.loaded.filter((entry) => typeof entry === "string") : [];
}
async function resolveUnsloth(apiRoot, apiKey, family2, onProgress) {
const spec = familyOrThrow(family2);
const loaded = new Set((await unslothLoadedModels(apiRoot, apiKey)).map(modelBasename));
const alreadyLoaded = spec.knownModels.find((known) => loaded.has(modelBasename(known)));
if (alreadyLoaded) return { modelKey: alreadyLoaded, apiRoot };
const failures = [];
for (const known of spec.knownModels) {
onProgress?.(-1, void 0, `Loading ${known}...`, "Prompt");
logLine(`loading '${known}' (${spec.ggufVariant}) with max_seq_length ${spec.contextLength}`);
try {
await fetchJson(
`${apiRoot}/api/inference/load`,
{
method: "POST",
headers: authHeaders(apiKey, true),
body: {
model_path: known,
gguf_variant: spec.ggufVariant,
max_seq_length: spec.contextLength,
alongside: true,
force_cancel_active: true
},
timeoutMs: LOAD_TIMEOUT_MS
},
`Loading '${known}' via /api/inference/load`
);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
logLine(`could not load '${known}': ${message}`);
failures.push(message);
continue;
}
const after = await unslothLoadedModels(apiRoot, apiKey);
if (!after.some((entry) => modelBasename(entry) === modelBasename(known))) {
const message = `'${known}' was loaded via /api/inference/load, but /api/inference/status does not report it as loaded.`;
logLine(message);
failures.push(message);
continue;
}
return { modelKey: known, apiRoot };
}
throw new Error(
`No prompt upsampler model of family '${family2}' could be loaded at ${apiRoot} (known: ${spec.knownModels.join(", ")}). ${failures.join(" | ")}`
);
}
async function resolveLlamaServer(config, family2) {
const spec = familyOrThrow(family2);
const settings = config.llamaServer;
if (!settings) throw new Error("The 'llama-server' adapter is active, but no llama-server settings were read.");
const host = "127.0.0.1";
await ensureLlamaServerRouterRunning({ host, ...settings });
const routerRoot = `http://${host}:${settings.port}`;
const ids = await listOpenAiModelIds(routerRoot, config.apiKey);
const found = spec.knownModels.map((known) => ids.find((id) => modelBasename(stripQuantTag(id)) === modelBasename(stripQuantTag(known)))).find((id) => !!id);
if (!found) throw noModelError(family2, routerRoot, spec.knownModels);
return { modelKey: found, apiRoot: routerRoot };
}
async function resolveWithPortFallback(apiRoot, resolve) {
try {
return await resolve(apiRoot);
} catch (primary) {
const altRoot = primary instanceof EndpointUnavailableError ? swapLmDefaultPort(apiRoot) : void 0;
if (!altRoot) throw primary;
try {
const lease = await resolve(altRoot);
logLine(`${apiRoot} was not usable (${primary.message}); using ${altRoot} instead`);
return lease;
} catch (alt) {
throw new Error(`${primary.message} | Fallback ${altRoot}: ${alt instanceof Error ? alt.message : String(alt)}`);
}
}
}
async function resolveModel(config, family2, onProgress) {
const apiRoot = normalizeLmApiRoot2(config.baseUrl);
switch (config.api) {
case "bionic":
return resolveWithPortFallback(apiRoot, (root) => resolveBionic(root, config.apiKey, family2, onProgress));
case "generic":
return resolveWithPortFallback(apiRoot, (root) => resolveGeneric(root, config.apiKey, family2));
case "unsloth":
return resolveUnsloth(apiRoot, config.apiKey, family2, onProgress);
case "llama-server":
return resolveLlamaServer(config, family2);
}
}
async function acquireModel(config, family2, onProgress) {
let entry = activeModels.get(family2);
if (!entry) {
entry = { count: 0, ready: resolveModel(config, family2, onProgress) };
activeModels.set(family2, entry);
}
entry.count++;
try {
return await entry.ready;
} catch (error) {
await releaseModel(config.apiKey, family2, void 0);
throw error;
}
}
async function releaseModel(apiKey, family2, lease) {
const entry = activeModels.get(family2);
if (!entry) return;
entry.count--;
if (entry.count > 0) return;
activeModels.delete(family2);
if (!lease?.instanceId) return;
try {
await fetchJson(
`${lease.apiRoot}/api/v1/models/unload`,
{ method: "POST", headers: authHeaders(apiKey, true), body: { instance_id: lease.instanceId }, timeoutMs: UNLOAD_TIMEOUT_MS },
`Unloading '${lease.instanceId}' via /api/v1/models/unload`
);
logLine(`unloaded '${lease.instanceId}'`);
} catch (error) {
logLine(`unload of '${lease.instanceId}' failed: ${error instanceof Error ? error.message : String(error)}`);
}
}
function mimeFromBuffer(buf) {
if (buf.length >= 3 && buf[0] === 255 && buf[1] === 216 && buf[2] === 255) return "image/jpeg";
if (buf.length >= 12 && buf.toString("ascii", 0, 4) === "RIFF" && buf.toString("ascii", 8, 12) === "WEBP") return "image/webp";
return "image/png";
}
function extractMessageText(data) {
const message = data?.choices?.[0]?.message;
const content = message?.content;
if (typeof content === "string" && content.trim()) return content;
if (Array.isArray(content)) {
const joined = content.map((p) => typeof p === "string" ? p : typeof p?.text === "string" ? p.text : "").join("");
if (joined.trim()) return joined;
}
const reasoning = message?.reasoning_content;
if (typeof reasoning === "string" && reasoning.trim()) {
logLine("response had empty content; using reasoning_content as the answer");
return reasoning;
}
return "";
}
async function applyPromptUpsampling(args) {
const caps = findImageModelCapabilitiesByFilename(args.effectiveModelFilename);
const upsampling = caps?.promptUpsampling;
if (!upsampling) return { applied: false };
if (args.referenceBuffers.length > upsampling.maxImages) {
throw new Error(
`Prompt upsampling accepts at most ${upsampling.maxImages} reference images, got ${args.referenceBuffers.length}.`
);
}
const config = readPromptUpsamplerConfigFromEnv();
if (!config.enabled) return { applied: false };
const boxes = (typeof args.boxes === "function" ? await args.boxes() : args.boxes) ?? [];
if (boxes.length > 0 && args.referenceBuffers.length === 0) {
throw new Error("Prompt upsampling with boxes needs the canvas as a reference image.");
}
const family2 = upsampling.promptUpsamplingModelFamily;
const familySpec = PROMPT_UPSAMPLER_FAMILY_SPECS[family2];
if (!familySpec) throw new Error(`No prompt upsampler request specification for model family '${family2}'.`);
const lease = await acquireModel(config, family2, args.onProgress);
try {
const imageParts = [];
const referenceImages = [];
const passes = [];
for (const [i, buf] of args.referenceBuffers.entries()) {
const { width, height } = await getSize(buf);
referenceImages.push({ width, height, bytes: buf.byteLength });
logLine(`reference ${i + 1}/${args.referenceBuffers.length}: ${width}x${height}, ${buf.byteLength} bytes`);
imageParts.push({ type: "image_url", image_url: { url: `data:${mimeFromBuffer(buf)};base64,${buf.toString("base64")}` } });
}
const infer = async (task, userContent, userText) => {
args.onProgress?.(-1, void 0, "Upsampling...", "Prompt");
logLine(`upsampling with '${lease.modelKey}' via ${config.api} task=${task} references=${args.referenceBuffers.length}`);
const startedAt = Date.now();
const data = await fetchJson(
`${lease.apiRoot}/v1/chat/completions`,
{
method: "POST",
headers: authHeaders(config.apiKey, true),
body: {
model: lease.modelKey,
messages: [
{ role: "system", content: familySpec.systemPrompts[task] },
{ role: "user", content: userContent }
],
...familySpec.sampling,
presence_penalty: familySpec.presencePenalty[task],
max_tokens: familySpec.maxTokens,
seed: familySpec.seed,
chat_template_kwargs: { enable_thinking: familySpec.enableThinking }
},
timeoutMs: CHAT_TIMEOUT_MS
},
`Prompt upsampling request to ${lease.apiRoot}/v1/chat/completions`
);
const ms = Date.now() - startedAt;
const finishReason = data?.choices?.[0]?.finish_reason;
if (finishReason === "length") {
throw new Error(`Prompt upsampling response was cut off at max_tokens (${familySpec.maxTokens}).`);
}
const text = extractMessageText(data).trim();
if (!text) {
throw new Error(
`Prompt upsampling model returned an empty response (finish_reason ${finishReason ?? "unknown"}, usage ${JSON.stringify(data?.usage ?? null)}).`
);
}
logLine(`upsampled prompt (${text.length} chars, ${ms} ms, usage ${JSON.stringify(data?.usage ?? null)})`);
passes.push({
task,
systemPromptSha256: createHash("sha256").update(familySpec.systemPrompts[task]).digest("hex"),
userText,
responseText: text,
inferenceMs: ms
});
return { text, ms };
};
let upsampled;
let inferenceMs;
let boxesInfo;
if (boxes.length > 0) {
const rows = buildPlainRows(boxes);
logLine(`boxes (${rows.length}, [y_min, x_min, y_max, x_max] on 0-1000): ${JSON.stringify(boxes)}`);
const boxText = familySpec.i2iBboxUserText(buildLockedInstruction(args.prompt, rows));
const content = [...imageParts, { type: "text", text: boxText }];
const boxed = await infer("i2i_bbox", content, boxText);
const reimposed = reimposeBoxes(boxed.text, boxes);
if (reimposed.ok) {
upsampled = reimposed.text;
inferenceMs = boxed.ms;
boxesInfo = { count: boxes.length, applied: true, regions: boxes.map((b) => [...b]) };
} else {
logLine(`box answer unusable (${reimposed.reason}); falling back to the plain i2i pass`);
const plainText = familySpec.i2iUserText(args.prompt);
const plain2 = await infer("i2i", [...imageParts, { type: "text", text: plainText }], plainText);
upsampled = plain2.text;
inferenceMs = boxed.ms + plain2.ms;
boxesInfo = { count: boxes.length, applied: false, fallbackReason: reimposed.reason, regions: boxes.map((b) => [...b]) };
}
} else {
const task = args.referenceBuffers.length > 0 ? "i2i" : "t2i";
const userText = task === "t2i" ? args.prompt : familySpec.i2iUserText(args.prompt);
const userContent = task === "t2i" ? args.prompt : [...imageParts, { type: "text", text: userText }];
const plain2 = await infer(task, userContent, userText);
upsampled = plain2.text;
inferenceMs = plain2.ms;
}
return {
applied: true,
prompt: upsampled,
originalPrompt: args.prompt,
model: lease.modelKey,
referenceCount: args.referenceBuffers.length,
inferenceMs,
referenceImages,
passes,
...boxesInfo ? { boxes: boxesInfo } : {}
};
} finally {
await releaseModel(config.apiKey, family2, lease);
}
}
// src/helpers/cameraImageMetadata.ts
var import_exifr = __toESM(require_full_umd(), 1);
import { readFile } from "node:fs/promises";
var EXIF_FIELDS = [
"DateTimeOriginal",
"CreateDate",
"ModifyDate",
"Make",
"Model",
"ImageWidth",
"ImageHeight",
"ExifImageWidth",
"ExifImageHeight",
"GPSLatitude",
"GPSLatitudeRef",
"GPSLongitude",
"GPSLongitudeRef",
"LensModel",
"ExposureTime",
"FNumber",
"ISO",
"ISOSpeedRatings",
"ExposureCompensation",
"FocalLength",
"FocalLengthIn35mmFormat",
"ExposureProgram",
"MeteringMode",
"WhiteBalance",
"Flash",
"Orientation",
"ExposureMode"
];
function nonEmptyString(value) {
return typeof value === "string" && value.trim() ? value.trim() : void 0;
}
function finitePositiveNumber(value) {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
}
function finiteNumber(value) {
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
}
function scalarString(value) {
if (typeof value === "string") return nonEmptyString(value);
if (typeof value === "number" && Number.isFinite(value)) return String(value);
return void 0;
}
function finiteCoordinate(value) {
return typeof value === "number" && Number.isFinite(value) && value >= -180 && value <= 180 ? value : void 0;
}
function decimalCoordinate(value, reference) {
const decimal = Array.isArray(value) ? value.length === 3 && value.every((part) => typeof part === "number" && Number.isFinite(part)) ? value[0] + value[1] / 60 + value[2] / 3600 : void 0 : finiteCoordinate(value);
if (decimal === void 0) return void 0;
const direction = nonEmptyString(reference)?.toUpperCase();
return direction === "S" || direction === "W" ? -decimal : decimal;
}
function isoTimestamp(value) {
if (!(value instanceof Date) || Number.isNaN(value.getTime())) return void 0;
return value.toISOString();
}
async function readCameraImageMetadata(input) {
try {
const bytes = typeof input === "string" ? await readFile(input) : input;
const fields = await import_exifr.default.parse(bytes, { pick: EXIF_FIELDS });
if (!fields) return {};
const make = nonEmptyString(fields.Make);
const model = nonEmptyString(fields.Model);
const camera = [make, model].filter((value, index2, values) => value && values.indexOf(value) === index2).join(" ") || void 0;
return {
capturedAt: isoTimestamp(fields.DateTimeOriginal) ?? isoTimestamp(fields.CreateDate) ?? isoTimestamp(fields.ModifyDate),
camera,
width: finitePositiveNumber(fields.ExifImageWidth) ?? finitePositiveNumber(fields.ImageWidth),
height: finitePositiveNumber(fields.ExifImageHeight) ?? finitePositiveNumber(fields.ImageHeight),
latitude: decimalCoordinate(fields.GPSLatitude, fields.GPSLatitudeRef),
longitude: decimalCoordinate(fields.GPSLongitude, fields.GPSLongitudeRef),
lensModel: nonEmptyString(fields.LensModel),
exposureTime: scalarString(fields.ExposureTime),
fNumber: finitePositiveNumber(fields.FNumber),
iso: finitePositiveNumber(fields.ISO) ?? finitePositiveNumber(fields.ISOSpeedRatings),
exposureCompensation: finiteNumber(fields.ExposureCompensation),
focalLength: finitePositiveNumber(fields.FocalLength),
focalLength35mm: finitePositiveNumber(fields.FocalLengthIn35mmFormat),
exposureProgram: scalarString(fields.ExposureProgram),
meteringMode: scalarString(fields.MeteringMode),
whiteBalance: scalarString(fields.WhiteBalance),
flash: scalarString(fields.Flash),
orientation: scalarString(fields.Orientation),
exposureMode: scalarString(fields.ExposureMode)
};
} catch {
return {};
}
}
// src/helpers/drawThingsGrpcAssetCheck.ts
import path18 from "node:path";
function normBasename(file) {
return path18.basename(String(file || "").trim());
}
function uniqNonEmptyBasenames(files) {
const seen = /* @__PURE__ */ new Set();
const out = [];
for (const f of files) {
if (!f) continue;
const b = normBasename(f);
if (!b) continue;
if (seen.has(b)) continue;
seen.add(b);
out.push(b);
}
return out;
}
function decodeJsonBytes2(buffer) {
if (!buffer) return [];
try {
const b = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer);
if (!b.length) return [];
const txt = b.toString("utf8");
const parsed = JSON.parse(txt);
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function extractFileLikeStrings(items) {
const out = [];
for (const it of items) {
if (!it || typeof it !== "object") continue;
for (const key of ["file", "filename", "name", "path"]) {
const v = it[key];
if (typeof v === "string" && v.trim()) out.push(v);
}
}
return out;
}
function buildMissingDetails({
modelFile,
missingModel,
missingLoras,
hintModels,
hintLoras
}) {
const parts = [];
parts.push("Draw Things gRPC: requested assets not found on server.");
if (missingModel) {
parts.push(`Missing model: ${missingModel}`);
}
if (missingLoras && missingLoras.length) {
parts.push(`Missing LoRA(s): ${missingLoras.join(", ")}`);
}
parts.push(
"The Draw Things gRPC server may silently fall back to a different model/without LoRA; generation was aborted to avoid producing misleading output."
);
if (hintModels && hintModels.length) {
parts.push(`Available model files (sample): ${hintModels.join(", ")}`);
}
if (hintLoras && hintLoras.length) {
parts.push(`Available LoRA files (sample): ${hintLoras.join(", ")}`);
}
if (modelFile) {
parts.push(
"Fix: copy the missing .ckpt into the server's model/LoRA directories (or adjust the requested filenames)."
);
}
return parts.join("\n");
}
async function filesExist(client, files, sharedSecret) {
try {
const fn = client?.filesExist?.bind(client);
if (typeof fn !== "function") return null;
return await new Promise((resolve, reject) => {
const req = { files, filesWithHash: [] };
if (sharedSecret) req.sharedSecret = sharedSecret;
fn(req, (err, resp) => {
if (err) return reject(err);
const existArr = Array.isArray(resp?.existences) ? resp.existences : [];
resolve(existArr.slice(0, files.length));
});
});
} catch {
return null;
}
}
async function checkDrawThingsGrpcFilesExist(input) {
const checked = uniqNonEmptyBasenames(input.files || []);
if (checked.length === 0) {
return { ok: true, checked: [], missing: [], usedFilesExist: true };
}
const existArr = await filesExist(input.client, checked, input.sharedSecret);
if (!existArr) {
return { ok: true, checked, missing: [], usedFilesExist: false };
}
const missing = [];
for (let i = 0; i < checked.length; i++) {
if (existArr[i] !== true) missing.push(checked[i]);
}
return {
ok: missing.length === 0,
checked,
missing,
usedFilesExist: true
};
}
async function tryBrowseViaEcho(client, sharedSecret) {
try {
const echo = client?.echo?.bind(client);
if (typeof echo !== "function") return null;
const req = { name: "generate-image-plugin" };
if (sharedSecret) req.sharedSecret = sharedSecret;
const reply = await new Promise((resolve, reject) => {
echo(req, (err, resp) => err ? reject(err) : resolve(resp));
});
const modelFiles = uniqNonEmptyBasenames(
Array.isArray(reply?.files) ? reply.files : []
);
const ov = reply?.override || {};
const lorasJson = decodeJsonBytes2(ov?.loras);
const modelsJson = decodeJsonBytes2(ov?.models);
const loraFiles2 = uniqNonEmptyBasenames(extractFileLikeStrings(lorasJson));
const modelFilesFromJson = uniqNonEmptyBasenames(
extractFileLikeStrings(modelsJson)
);
return {
modelFiles: uniqNonEmptyBasenames([...modelFiles, ...modelFilesFromJson]),
loraFiles: loraFiles2
};
} catch {
return null;
}
}
function pickSample(list, limit) {
if (!list.length) return [];
return list.slice(0, Math.max(0, limit));
}
async function checkDrawThingsGrpcAssets(req) {
const requestedModel = req.modelFile ? normBasename(req.modelFile) : "";
const requestedLoras = uniqNonEmptyBasenames(req.loraFiles || []);
if (!requestedModel && requestedLoras.length === 0) return { ok: true };
const filesToCheck = uniqNonEmptyBasenames([
requestedModel || void 0,
...requestedLoras
]);
const existArr = await filesExist(req.client, filesToCheck, req.sharedSecret);
if (existArr) {
const missing = [];
for (let i = 0; i < filesToCheck.length; i++) {
if (existArr[i] !== true) missing.push(filesToCheck[i]);
}
if (missing.length === 0) return { ok: true };
const missingModel2 = requestedModel && missing.includes(requestedModel) ? requestedModel : void 0;
const missingLoras2 = requestedLoras.filter((x) => missing.includes(x));
return {
ok: false,
missingModel: missingModel2,
missingLoras: missingLoras2.length ? missingLoras2 : void 0,
details: buildMissingDetails({
modelFile: requestedModel || void 0,
missingModel: missingModel2,
missingLoras: missingLoras2
})
};
}
const browse = await tryBrowseViaEcho(req.client, req.sharedSecret);
if (!browse) {
return { ok: true };
}
const missingModel = requestedModel && !browse.modelFiles.includes(requestedModel) ? requestedModel : void 0;
const missingLoras = requestedLoras.filter(
(x) => !browse.loraFiles.includes(x)
);
if (!missingModel && missingLoras.length === 0) return { ok: true };
return {
ok: false,
missingModel,
missingLoras: missingLoras.length ? missingLoras : void 0,
details: buildMissingDetails({
modelFile: requestedModel || void 0,
missingModel,
missingLoras,
hintModels: pickSample(browse.modelFiles, 12),
hintLoras: pickSample(browse.loraFiles, 12)
})
};
}
// src/helpers/httpServer.ts
import http from "http";
import fs19 from "fs";
import path19 from "path";
var DEFAULT_HOST = "127.0.0.1";
function envPort() {
const v = process.env.HTTP_SERVER_PORT;
if (v == null || String(v).trim() === "") return void 0;
const n = Number(v);
return Number.isInteger(n) && n >= 1024 && n <= 65535 ? n : void 0;
}
async function healthCheck(port, host = DEFAULT_HOST) {
return new Promise((resolve) => {
const req = http.get(
{ host, port, path: "/__healthz", timeout: 600 },
(res) => {
try {
const ok = (res.statusCode || 0) === 200 && String(res.headers["x-mcp-image-server"]) === "1";
res.resume();
res.once("end", () => resolve(ok));
} catch {
resolve(false);
}
}
);
req.on("timeout", () => {
try {
req.destroy();
} catch {
}
resolve(false);
});
req.on("error", () => resolve(false));
});
}
function toHttpOriginalUrl(fileName, baseUrl, chatId) {
if (chatId) {
return `${baseUrl.replace(/\/$/, "")}/${encodeURIComponent(
chatId
)}/${encodeURIComponent(fileName)}`;
}
return `${baseUrl.replace(/\/$/, "")}/${encodeURIComponent(fileName)}`;
}
function toHttpPreviewUrl(fileName, baseUrl, chatId) {
if (chatId) {
return `${baseUrl.replace(/\/$/, "")}/${encodeURIComponent(
chatId
)}/${encodeURIComponent(fileName)}`;
}
return `${baseUrl.replace(/\/$/, "")}/previews/${encodeURIComponent(
fileName
)}`;
}
async function getHealthyServerBaseUrl(host = DEFAULT_HOST) {
try {
const fixedPort = envPort();
if (fixedPort == null) return "";
const ok = await healthCheck(fixedPort, host).catch(() => false);
if (ok) return `http://127.0.0.1:${fixedPort}`;
return "";
} catch {
return "";
}
}
async function isHttpServerHealthy(host = DEFAULT_HOST) {
try {
const fixedPort = envPort();
if (fixedPort == null) return false;
const ok = await healthCheck(fixedPort, host).catch(() => false);
return !!ok;
} catch {
return false;
}
}
// src/helpers/toolLog.ts
import fs20 from "fs";
import path20 from "path";
var DEBUG_MODE = true;
var logsDir = () => getLogsDir();
var logFile = () => path20.join(logsDir(), getPluginLogFilename());
function log(message) {
const timestamp = logTimestamp();
const line = `${timestamp} - ${requestLogPrefix()}${message}
`;
try {
const dir = path20.dirname(logFile());
if (!fs20.existsSync(dir)) fs20.mkdirSync(dir, { recursive: true });
fs20.appendFileSync(logFile(), line);
} catch {
}
console.log(line.trim());
}
async function logError(error) {
try {
const errorLogFile = path20.join(logsDir(), "error.log");
await fs20.promises.mkdir(logsDir(), { recursive: true }).catch(() => {
});
const timestamp = logTimestamp();
const details = error instanceof Error ? `${error.message}
${error.stack}` : String(error);
const block = `${timestamp} - ERROR:
${details}
`;
await fs20.promises.appendFile(errorLogFile, block);
if (DEBUG_MODE) console.error(block);
} catch {
}
}
async function appendErrorRaw(raw, status) {
try {
const errorLogFile = path20.join(logsDir(), "error.log");
await fs20.promises.mkdir(logsDir(), { recursive: true }).catch(() => {
});
const timestamp = logTimestamp();
const header = typeof status === "number" ? `BACKEND RAW (status ${status})` : "BACKEND RAW";
const block = `${timestamp} - ${header}:
${raw}
`;
await fs20.promises.appendFile(errorLogFile, block);
} catch {
}
}
// src/helpers/generationToolCommon.ts
import fs21 from "fs";
import path21 from "path";
import { pathToFileURL } from "url";
var ALLOWED_GEN_INPUT_KEYS = [
"prompt",
"width",
"height",
"imageFormat",
"variants",
"canvas",
"moodboard"
];
function stripInternalToolKeys(obj) {
if (!obj || typeof obj !== "object") return {};
const out = {};
for (const [k, v] of Object.entries(obj)) {
if (k.startsWith("_")) continue;
out[k] = v;
}
return out;
}
function normalizeSourceNotation(s) {
let t = String(s || "").trim().toLowerCase();
if (t === "a") t = "a1";
if (t === "v") t = "v1";
if (t === "p") t = "p1";
if (t === "i") t = "i1";
return t;
}
function parsePrefixedNotation(s) {
const t = normalizeSourceNotation(s);
const m = t.match(/^([avpi])\s*(\d+)$/);
if (!m) return null;
const idx = Math.max(1, parseInt(m[2], 10));
const pool = m[1] === "a" ? "attachment" : m[1] === "v" ? "variant" : m[1] === "i" ? "image" : "picture";
return { pool, index: idx };
}
function parseDigitOnlyNotation(s) {
const t = String(s || "").trim();
const m = t.match(/^(\d+)$/);
if (!m) return null;
return Math.max(1, parseInt(m[1], 10));
}
function encodeFileUrl(abs) {
return pathToFileURL(abs).toString();
}
function isoStamp() {
return (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
}
function getCurrentConnectionSettings() {
return getEngineConnectionDefaults({
host: process.env.DRAW_THINGS_HOST,
httpPort: process.env.DRAW_THINGS_HTTP_PORT ? parseInt(process.env.DRAW_THINGS_HTTP_PORT, 10) : void 0,
grpcPort: process.env.DRAW_THINGS_GRPC_PORT ? parseInt(process.env.DRAW_THINGS_GRPC_PORT, 10) : void 0
});
}
async function getLMConversationFilePath(chatId) {
try {
const home = findLMStudioHome();
const convDir = path21.join(home, "conversations");
if (!fs21.existsSync(convDir)) return null;
if (chatId) {
const p = path21.join(convDir, `${chatId}.conversation.json`);
return await fs21.promises.stat(p).then((s) => s.isFile() ? p : null).catch(() => null);
}
const entries = await fs21.promises.readdir(convDir).catch(() => []);
const convFiles = entries.filter((f) => f.endsWith(".conversation.json")).map((f) => path21.join(convDir, f));
if (convFiles.length === 0) return null;
const withTimes = (await Promise.all(
convFiles.map(async (p) => {
try {
const s = await fs21.promises.stat(p);
return s.isFile() ? { p, t: s.mtimeMs } : null;
} catch {
return null;
}
})
)).filter(Boolean);
if (withTimes.length === 0) return null;
withTimes.sort((a, b) => b.t - a.t);
return withTimes[0].p;
} catch {
return null;
}
}
function isSupportedImageBuffer(buf) {
if (!buf || buf.length < 12) return false;
if (buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71 && buf[4] === 13 && buf[5] === 10 && buf[6] === 26 && buf[7] === 10)
return true;
if (buf[0] === 255 && buf[1] === 216) return true;
if (buf[0] === 82 && buf[1] === 73 && buf[2] === 70 && buf[3] === 70 && buf[8] === 87 && buf[9] === 69 && buf[10] === 66 && buf[11] === 80)
return true;
return false;
}
function createSaveOriginalPng(injectXmpIntoBuffer2) {
return async function saveOriginalPng(sourceBuffer, preferredDir, preferredFileName, xmpParams) {
if (!preferredDir) {
throw new Error(
"No output directory resolved (LM Studio chat working directory missing)."
);
}
const dir = path21.resolve(preferredDir);
await fs21.promises.mkdir(dir, { recursive: true });
const name = preferredFileName && preferredFileName.endsWith(".png") ? preferredFileName : preferredFileName ? `${preferredFileName}.png` : `generated-image-${tsForFilename()}.png`;
const abs = path21.join(dir, name);
const embedMeta = xmpParams != null && /^(1|true|yes)$/i.test(String(process.env.EMBED_PNG_METADATA ?? "true").trim());
try {
if (!isSupportedImageBuffer(sourceBuffer)) {
const binName = name.replace(/\.png$/i, ".bin");
const binAbs = path21.join(dir, binName);
await fs21.promises.writeFile(binAbs, sourceBuffer);
const stat2 = await fs21.promises.stat(binAbs);
return {
savedPath: binAbs,
fileName: binName,
size: stat2.size,
mimeType: "application/octet-stream",
fileUrl: encodeFileUrl(binAbs)
};
}
let pngBuf;
if (isPng(sourceBuffer)) {
pngBuf = sourceBuffer;
} else {
pngBuf = await toPng(sourceBuffer);
}
if (embedMeta) {
pngBuf = injectXmpIntoBuffer2(pngBuf, xmpParams);
}
await fs21.promises.writeFile(abs, pngBuf);
} catch {
await fs21.promises.writeFile(abs, sourceBuffer);
}
const stat = await fs21.promises.stat(abs);
return {
savedPath: abs,
fileName: name,
size: stat.size,
mimeType: "image/png",
fileUrl: encodeFileUrl(abs)
};
};
}
async function normalizeInputBuffer(buf, opts) {
const prefix = opts?.logPrefix || "[normalize]";
const size = await getSize(buf);
let w = size.width || 0;
let h = size.height || 0;
const align = drawthingsLimits.align;
const minDim = drawthingsLimits.minDim;
const targetSum = opts?.targetSumOverride ?? drawthingsLimits.targetSum;
const origW = w;
const origH = h;
const origFmt = isPng(buf) ? "png" : void 0;
const origBytes = buf.byteLength;
let reason = "unchanged";
const hasReqW = typeof opts?.requestedRawW === "number" && Number.isFinite(opts.requestedRawW) && opts.requestedRawW > 0;
const hasReqH = typeof opts?.requestedRawH === "number" && Number.isFinite(opts.requestedRawH) && opts.requestedRawH > 0;
if (hasReqW && hasReqH) {
w = opts.requestedRawW;
h = opts.requestedRawH;
reason = "clamped_to_requested_raw";
log(`${prefix} adopting target dimensions: ${origW}x${origH} \u2192 ${w}x${h}`);
}
const currentSum = w + h;
if (!opts?.skipSumConstraint && currentSum > targetSum) {
const aspect = w / Math.max(1, h);
const rawH = targetSum / (aspect + 1);
const rawW = aspect * rawH;
const wFloor = Math.max(align, Math.floor(rawW / align) * align);
const wRound = Math.max(align, Math.round(rawW / align) * align);
const wCeil = Math.max(align, Math.ceil(rawW / align) * align);
const hFloor = Math.max(align, Math.floor(rawH / align) * align);
const hRound = Math.max(align, Math.round(rawH / align) * align);
const hCeil = Math.max(align, Math.ceil(rawH / align) * align);
const sumCandidates = [];
for (const cw of [wFloor, wRound, wCeil]) {
for (const ch of [hFloor, hRound, hCeil]) {
if (cw + ch <= targetSum) sumCandidates.push({ cw, ch });
}
}
for (const cw of [wFloor, wRound]) {
const ch = Math.max(align, Math.round(cw / aspect / align) * align);
if (cw + ch <= targetSum) sumCandidates.push({ cw, ch });
}
for (const ch of [hFloor, hRound]) {
const cw = Math.max(align, Math.round(ch * aspect / align) * align);
if (cw + ch <= targetSum) sumCandidates.push({ cw, ch });
}
if (sumCandidates.length > 0) {
sumCandidates.sort((a, b) => {
const ae = Math.abs(a.cw / Math.max(1, a.ch) - aspect);
const be = Math.abs(b.cw / Math.max(1, b.ch) - aspect);
if (ae !== be) return ae - be;
return Math.abs(a.cw - rawW) + Math.abs(a.ch - rawH) - (Math.abs(b.cw - rawW) + Math.abs(b.ch - rawH));
});
w = sumCandidates[0].cw;
h = sumCandidates[0].ch;
} else {
let fbW = wFloor;
let fbH = hFloor;
while (fbW + fbH > targetSum && (fbW > align || fbH > align)) {
if (fbW >= fbH) fbW = Math.max(align, fbW - align);
else fbH = Math.max(align, fbH - align);
}
w = fbW;
h = fbH;
}
if (reason === "unchanged") reason = "normalized_to_constraints";
}
if (w % align !== 0 || h % align !== 0) {
const aspect = w / Math.max(1, h);
const wFloor = Math.max(align, Math.floor(w / align) * align);
const wRound = Math.max(align, Math.round(w / align) * align);
const hFloor = Math.max(align, Math.floor(h / align) * align);
const hRound = Math.max(align, Math.round(h / align) * align);
const candidates = [
{ cw: wFloor, ch: hFloor },
{ cw: wFloor, ch: hRound },
{ cw: wRound, ch: hFloor },
{ cw: wRound, ch: hRound }
];
for (const wBase of [wFloor, wRound]) {
const hDerived = Math.max(align, Math.round(wBase / aspect / align) * align);
candidates.push({ cw: wBase, ch: hDerived });
}
for (const hBase of [hFloor, hRound]) {
const wDerived = Math.max(align, Math.round(hBase * aspect / align) * align);
candidates.push({ cw: wDerived, ch: hBase });
}
const valid = candidates.filter(
(c) => c.cw >= align && c.ch >= align && c.cw + c.ch <= targetSum
);
if (valid.length > 0) {
valid.sort((a, b) => {
const ae = Math.abs(a.cw / Math.max(1, a.ch) - aspect);
const be = Math.abs(b.cw / Math.max(1, b.ch) - aspect);
if (ae !== be) return ae - be;
const ad = Math.abs(a.cw - w) + Math.abs(a.ch - h);
const bd = Math.abs(b.cw - w) + Math.abs(b.ch - h);
return ad - bd;
});
w = valid[0].cw;
h = valid[0].ch;
} else {
w = Math.max(align, Math.floor(w / align) * align);
h = Math.max(align, Math.floor(h / align) * align);
}
if (reason === "unchanged") reason = "normalized_to_constraints";
}
if (w < minDim || h < minDim) {
const scale = minDim / Math.min(w, h);
w = Math.round(w * scale);
h = Math.round(h * scale);
w = Math.max(align, Math.floor(w / align) * align);
h = Math.max(align, Math.floor(h / align) * align);
while (w + h > targetSum && (w > minDim || h > minDim)) {
if (w > h) w = Math.max(minDim, w - align);
else h = Math.max(minDim, h - align);
}
if (reason === "unchanged") reason = "normalized_to_constraints";
}
let outBuf;
if (w !== origW || h !== origH) {
outBuf = await resizeCoverToPng(buf, w, h);
if (reason === "unchanged") reason = "normalized_to_constraints";
log(
`${prefix} dimension normalization: ${origW}x${origH} \u2192 ${w}x${h} (sum=${w + h})`
);
} else {
if (isPng(buf)) {
outBuf = buf;
} else {
outBuf = await toPng(buf);
if (reason === "unchanged") reason = "converted_to_png";
}
}
return {
buf: outBuf,
preprocess: {
original: {
width: origW,
height: origH,
format: origFmt,
bytes: origBytes
},
adjusted: {
width: w,
height: h,
format: "png",
bytes: outBuf.byteLength
},
reason
},
normalizedLongSide: w !== origW || h !== origH ? Math.max(w, h) : void 0
};
}
// src/helpers/injectionMarker.ts
var injectedRegistry = /* @__PURE__ */ new Map();
function stripKnownMarkdownInjections(text) {
if (!text) return text;
const lines = text.split(/\r?\n/);
const outLines = [];
const injectedImageLine = /^!\[(Image Variant v\d+|Image i\d+)\]\(\.(?:\/)?(preview-[^)\s]+\.(?:jpg|jpeg|webp|png)|generated-image-[^)\s]+\.(?:png|jpg|jpeg|webp))\)\s*$/i;
for (const line of lines) {
if (injectedImageLine.test(line.trim())) continue;
outLines.push(line);
}
let s = outLines.join("\n");
const kept = [];
const ls = s.split(/\r?\n/);
for (let i = 0; i < ls.length; i++) {
const line = ls[i];
const header = line.trim();
const isOurHeader = header === "| Preview | ID / Title | Source |" || header === "| Preview | ID / Title | Source |" || header === "| Preview | ID / Generation Data |" || header === "| Index Image Results |";
if (!isOurHeader) {
kept.push(line);
continue;
}
const sep = (ls[i + 1] ?? "").trim();
const isSeparator = /^\|[-\s|]+\|$/.test(sep) || sep === "|---|---|---|" || sep === "|---|---|" || sep === "|---|";
if (!isSeparator) {
kept.push(line);
continue;
}
let j = i + 2;
let sawImageCell = false;
for (; j < ls.length; j++) {
const row = ls[j];
const t = row.trim();
if (!t.startsWith("|") || !t.endsWith("|")) break;
if (t.includes(") sawImageCell = true;
}
if (sawImageCell) {
i = j - 1;
continue;
}
kept.push(line);
}
return kept.join("\n");
}
function trackInjection(chatId, markdown, _mediaType) {
if (!chatId || !markdown) return;
let set = injectedRegistry.get(chatId);
if (!set) {
set = /* @__PURE__ */ new Set();
injectedRegistry.set(chatId, set);
}
set.add(markdown);
}
function stripInjections(chatId, text) {
if (!chatId || !text) return text;
const set = injectedRegistry.get(chatId);
if (!set || set.size === 0) return text;
let result = text;
for (const injection of set) {
result = result.split(injection + "\n").join("");
result = result.split(injection).join("");
}
result = stripKnownMarkdownInjections(result);
return result.trim();
}
function hasTrackedInjections(chatId) {
const set = injectedRegistry.get(chatId);
return !!set && set.size > 0;
}
function clearInjections(chatId) {
injectedRegistry.delete(chatId);
}
function getInjectionCount(chatId) {
return injectedRegistry.get(chatId)?.size ?? 0;
}
var INJECTION_START = "";
var INJECTION_END = "";
function wrapInjection(markdown, _mediaType) {
return markdown;
}
function hasInjections(_text) {
return false;
}
// src/helpers/maskColorDrift.ts
var DEFAULTS = {
sigmaSpatial: 30,
sigmaColor: 8,
tau: 14,
margin: 3,
cap: 8,
confidenceWeight: 4,
downscale: 2,
maxSamples: 3e3,
minSamples: 150
};
var MAX_ESTIMATE_CELLS = 12e4;
var SRGB_TO_LINEAR = (() => {
const lut = new Float32Array(256);
for (let i = 0; i < 256; i++) {
const c = i / 255;
lut[i] = c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
}
return lut;
})();
var XN = 0.95047;
var ZN = 1.08883;
var LAB_EPS = 216 / 24389;
var LAB_KAPPA = 24389 / 27;
function labF(t) {
return t > LAB_EPS ? Math.cbrt(t) : (LAB_KAPPA * t + 16) / 116;
}
function labFInv(t) {
const t3 = t * t * t;
return t3 > LAB_EPS ? t3 : (116 * t - 16) / LAB_KAPPA;
}
function rgbToLab(r, g, b, out, o) {
const lr = SRGB_TO_LINEAR[r];
const lg = SRGB_TO_LINEAR[g];
const lb = SRGB_TO_LINEAR[b];
const x = (0.4124564 * lr + 0.3575761 * lg + 0.1804375 * lb) / XN;
const y = 0.2126729 * lr + 0.7151522 * lg + 0.072175 * lb;
const z4 = (0.0193339 * lr + 0.119192 * lg + 0.9503041 * lb) / ZN;
const fx = labF(x);
const fy = labF(y);
const fz = labF(z4);
out[o] = 116 * fy - 16;
out[o + 1] = 500 * (fx - fy);
out[o + 2] = 200 * (fy - fz);
}
function encodeSrgb(linear) {
const c = Math.min(1, Math.max(0, linear));
const v = c <= 31308e-7 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
return Math.round(v * 255);
}
function labToRgb(l, a, b, out, o) {
const fy = (l + 16) / 116;
const fx = fy + a / 500;
const fz = fy - b / 200;
const x = labFInv(fx) * XN;
const y = labFInv(fy);
const z4 = labFInv(fz) * ZN;
out[o] = encodeSrgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z4);
out[o + 1] = encodeSrgb(-0.969266 * x + 1.8760108 * y + 0.041556 * z4);
out[o + 2] = encodeSrgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z4);
}
function erode(binary, w, h, radius) {
if (radius <= 0) return binary;
const tmp = new Uint8Array(w * h);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
let v = 1;
for (let k = -radius; k <= radius && v; k++) {
const xx = x + k;
if (xx < 0 || xx >= w || !binary[y * w + xx]) v = 0;
}
tmp[y * w + x] = v;
}
}
const out = new Uint8Array(w * h);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
let v = 1;
for (let k = -radius; k <= radius && v; k++) {
const yy = y + k;
if (yy < 0 || yy >= h || !tmp[yy * w + x]) v = 0;
}
out[y * w + x] = v;
}
}
return out;
}
function correctMaskColorDrift(original, result, mask, options = {}) {
const opt = { ...DEFAULTS, ...options };
const { width: W, height: H } = result;
if (original.width !== W || original.height !== H) {
throw new Error(`original ${original.width}x${original.height} and result ${W}x${H} differ in size`);
}
if (mask.length < W * H) throw new Error(`mask has ${mask.length} entries, expected ${W * H}`);
const out = new Uint8Array(result.data);
const unchanged = { data: out, applied: false, samples: 0, meanOffsetLab: [0, 0, 0], maxCorrectionDE: 0 };
let x0 = W;
let y0 = H;
let x1 = -1;
let y1 = -1;
for (let y = 0; y < H; y++) {
for (let x = 0; x < W; x++) {
if (mask[y * W + x] > 1e-3) {
if (x < x0) x0 = x;
if (x > x1) x1 = x;
if (y < y0) y0 = y;
if (y > y1) y1 = y;
}
}
}
if (x1 < 0) return unchanged;
x0 = Math.max(0, x0 - 2);
y0 = Math.max(0, y0 - 2);
x1 = Math.min(W - 1, x1 + 2);
y1 = Math.min(H - 1, y1 + 2);
const rw = x1 - x0 + 1;
const rh = y1 - y0 + 1;
const labO = new Float32Array(rw * rh * 3);
const labR = new Float32Array(rw * rh * 3);
const m = new Float32Array(rw * rh);
const full = new Uint8Array(rw * rh);
for (let y = 0; y < rh; y++) {
for (let x = 0; x < rw; x++) {
const i = y * rw + x;
const src = ((y0 + y) * W + (x0 + x)) * result.channels;
const srcO = ((y0 + y) * W + (x0 + x)) * original.channels;
rgbToLab(original.data[srcO], original.data[srcO + 1], original.data[srcO + 2], labO, i * 3);
rgbToLab(result.data[src], result.data[src + 1], result.data[src + 2], labR, i * 3);
const mv = mask[(y0 + y) * W + (x0 + x)];
m[i] = mv;
full[i] = mv >= 0.999 ? 1 : 0;
}
}
const inner = erode(full, rw, rh, opt.margin);
const s = Math.max(1, Math.round(opt.downscale), Math.ceil(Math.sqrt(rw * rh / MAX_ESTIMATE_CELLS)));
const lw = Math.ceil(rw / s);
const lh = Math.ceil(rh / s);
const loR = new Float32Array(lw * lh * 3);
const loO = new Float32Array(lw * lh * 3);
const loM = new Float32Array(lw * lh);
const loInner = new Uint8Array(lw * lh);
for (let ly = 0; ly < lh; ly++) {
for (let lx = 0; lx < lw; lx++) {
let n = 0;
let allInner = 1;
const acc = [0, 0, 0, 0, 0, 0];
let mm = 0;
for (let dy = 0; dy < s; dy++) {
const y = ly * s + dy;
if (y >= rh) break;
for (let dx = 0; dx < s; dx++) {
const x = lx * s + dx;
if (x >= rw) break;
const i = y * rw + x;
n++;
for (let c = 0; c < 3; c++) {
acc[c] += labR[i * 3 + c];
acc[3 + c] += labO[i * 3 + c];
}
mm += m[i];
if (!inner[i]) allInner = 0;
}
}
const j = ly * lw + lx;
for (let c = 0; c < 3; c++) {
loR[j * 3 + c] = acc[c] / n;
loO[j * 3 + c] = acc[3 + c] / n;
}
loM[j] = mm / n;
loInner[j] = allInner;
}
}
const evidence = [];
for (let j = 0; j < lw * lh; j++) {
if (!loInner[j]) continue;
const dl = loR[j * 3] - loO[j * 3];
const da = loR[j * 3 + 1] - loO[j * 3 + 1];
const db = loR[j * 3 + 2] - loO[j * 3 + 2];
if (Math.sqrt(dl * dl + da * da + db * db) < opt.tau) evidence.push(j);
}
const total = evidence.length;
if (total < opt.minSamples) return { ...unchanged, samples: total };
const grid = Math.max(1, Math.ceil(Math.sqrt(total / opt.maxSamples)));
const sampleIdx = [];
for (const j of evidence) {
if (j % lw % grid === 0 && Math.floor(j / lw) % grid === 0) sampleIdx.push(j);
}
const ns = sampleIdx.length;
const sx = new Float32Array(ns);
const sy = new Float32Array(ns);
const sCol = new Float32Array(ns * 3);
const sOff = new Float32Array(ns * 3);
const mean = [0, 0, 0];
for (let k = 0; k < ns; k++) {
const j = sampleIdx[k];
sx[k] = j % lw;
sy[k] = Math.floor(j / lw);
for (let c = 0; c < 3; c++) {
sCol[k * 3 + c] = loR[j * 3 + c];
sOff[k * 3 + c] = loR[j * 3 + c] - loO[j * 3 + c];
mean[c] += sOff[k * 3 + c] / ns;
}
}
const sigS = opt.sigmaSpatial / s;
const invS2 = 1 / (sigS * sigS);
const invC2 = 1 / (opt.sigmaColor * opt.sigmaColor);
const reach2 = 9 * sigS * sigS;
const corr = new Float32Array(lw * lh * 3);
for (let ly = 0; ly < lh; ly++) {
for (let lx = 0; lx < lw; lx++) {
const j = ly * lw + lx;
if (loM[j] <= 0) continue;
const pl = loR[j * 3];
const pa = loR[j * 3 + 1];
const pb = loR[j * 3 + 2];
let den = 0;
let n0 = 0;
let n1 = 0;
let n2 = 0;
for (let k = 0; k < ns; k++) {
const ddx = lx - sx[k];
const ddy = ly - sy[k];
const d2 = ddx * ddx + ddy * ddy;
if (d2 > reach2) continue;
const cl = pl - sCol[k * 3];
const ca = pa - sCol[k * 3 + 1];
const cb = pb - sCol[k * 3 + 2];
const e = d2 * invS2 + (cl * cl + ca * ca + cb * cb) * invC2;
if (e > 16) continue;
const wgt = Math.exp(-e);
den += wgt;
n0 += wgt * sOff[k * 3];
n1 += wgt * sOff[k * 3 + 1];
n2 += wgt * sOff[k * 3 + 2];
}
if (den <= 1e-9) continue;
let f0 = n0 / den;
let f1 = n1 / den;
let f2 = n2 / den;
const mag = Math.sqrt(f0 * f0 + f1 * f1 + f2 * f2);
const scale = Math.min(1, opt.cap / Math.max(mag, 1e-9)) * Math.min(1, den / opt.confidenceWeight);
f0 *= scale;
f1 *= scale;
f2 *= scale;
corr[j * 3] = f0;
corr[j * 3 + 1] = f1;
corr[j * 3 + 2] = f2;
}
}
let maxDE = 0;
let touched = false;
const clampX = (v) => Math.min(lw - 1, Math.max(0, v));
const clampY = (v) => Math.min(lh - 1, Math.max(0, v));
for (let y = 0; y < rh; y++) {
const fy = (y + 0.5) / s - 0.5;
const iy0 = Math.floor(fy);
const wy = fy - iy0;
const ya = clampY(iy0);
const yb = clampY(iy0 + 1);
for (let x = 0; x < rw; x++) {
const i = y * rw + x;
const mv = m[i];
if (mv <= 0) continue;
const fx = (x + 0.5) / s - 0.5;
const ix0 = Math.floor(fx);
const wx = fx - ix0;
const xa = clampX(ix0);
const xb = clampX(ix0 + 1);
let c0 = 0;
let c1 = 0;
let c2 = 0;
for (let c = 0; c < 3; c++) {
const v = corr[(ya * lw + xa) * 3 + c] * (1 - wx) * (1 - wy) + corr[(ya * lw + xb) * 3 + c] * wx * (1 - wy) + corr[(yb * lw + xa) * 3 + c] * (1 - wx) * wy + corr[(yb * lw + xb) * 3 + c] * wx * wy;
if (c === 0) c0 = v * mv;
else if (c === 1) c1 = v * mv;
else c2 = v * mv;
}
const de = Math.sqrt(c0 * c0 + c1 * c1 + c2 * c2);
if (de < 0.01) continue;
if (de > maxDE) maxDE = de;
touched = true;
const o = ((y0 + y) * W + (x0 + x)) * result.channels;
labToRgb(labR[i * 3] - c0, labR[i * 3 + 1] - c1, labR[i * 3 + 2] - c2, out, o);
}
}
return { data: out, applied: touched, samples: total, meanOffsetLab: mean, maxCorrectionDE: maxDE };
}
function bitmapToLab(bitmap) {
const n = bitmap.width * bitmap.height;
const out = new Float32Array(n * 3);
for (let i = 0; i < n; i++) {
const p = i * bitmap.channels;
rgbToLab(bitmap.data[p], bitmap.data[p + 1], bitmap.data[p + 2], out, i * 3);
}
return out;
}
function rectMask(width, height, box, feather = 5) {
const [bx0, by0, bx1, by1] = box;
const out = new Float32Array(width * height);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const d = Math.min(x - bx0, bx1 - 1 - x, y - by0, by1 - 1 - y);
out[y * width + x] = Math.min(1, Math.max(0, (d + 0.5) / feather));
}
}
return out;
}
async function correctMaskColorDriftPng(originalPng, resultPng, maskPng, options = {}) {
const [orig, res, msk] = await Promise.all([decodeToRgba(originalPng), decodeToRgba(resultPng), decodeToRgba(maskPng)]);
if (orig.width !== res.width || orig.height !== res.height || msk.width !== res.width || msk.height !== res.height) {
throw new Error(
`size mismatch: original ${orig.width}x${orig.height}, result ${res.width}x${res.height}, mask ${msk.width}x${msk.height}`
);
}
const coverage = new Float32Array(res.width * res.height);
for (let i = 0; i < coverage.length; i++) coverage[i] = msk.data[i * 4] / 255;
const fixed = correctMaskColorDrift(
{ data: orig.data, width: orig.width, height: orig.height, channels: 4 },
{ data: res.data, width: res.width, height: res.height, channels: 4 },
coverage,
options
);
if (!fixed.applied) {
return { png: resultPng, applied: false, samples: fixed.samples, meanOffsetLab: fixed.meanOffsetLab, maxCorrectionDE: 0 };
}
return {
png: await encodeRgbaToPng(fixed.data, res.width, res.height),
applied: true,
samples: fixed.samples,
meanOffsetLab: fixed.meanOffsetLab,
maxCorrectionDE: fixed.maxCorrectionDE
};
}
// src/helpers/outputDims.ts
function chooseAlignedCanvas(rawW, rawH, opts) {
const { align, targetSum } = opts;
const aspect = rawW / Math.max(1, rawH);
const scale = rawW + rawH > targetSum ? targetSum / (rawW + rawH) : 1;
const wRaw = rawW * scale;
const hRaw = rawH * scale;
const snaps = (v) => [
Math.max(align, Math.floor(v / align) * align),
Math.max(align, Math.round(v / align) * align),
Math.max(align, Math.ceil(v / align) * align)
];
const candidates = [];
for (const w of snaps(wRaw)) {
for (const h of snaps(hRaw)) {
if (w + h <= targetSum) candidates.push({ width: w, height: h, arErr: Math.abs(w / h - aspect) });
}
}
candidates.sort((a, b) => a.arErr - b.arErr || b.width + b.height - (a.width + a.height));
const best = candidates[0];
if (best) return { width: best.width, height: best.height };
return {
width: Math.max(align, Math.floor(wRaw / align) * align),
height: Math.max(align, Math.floor(hRaw / align) * align)
};
}
function resolveRequestedOutputDims(canvas, requested, limits) {
const valid = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
const hasW = valid(requested.width);
const hasH = valid(requested.height);
if (!hasW && !hasH) return { ...canvas };
const aspect = canvas.width / Math.max(1, canvas.height);
let width = hasW ? Math.round(requested.width) : Math.round(requested.height * aspect);
let height = hasH ? Math.round(requested.height) : Math.round(requested.width / aspect);
const s = Math.min(limits.maxWidth / width, limits.maxHeight / height, 1);
if (s < 1) {
width = Math.round(width * s);
height = Math.round(height * s);
}
return { width: Math.max(1, width), height: Math.max(1, height) };
}
async function resizeCanvasAndMask(canvasBuf, maskBuf, from, target2) {
if (from.width === target2.width && from.height === target2.height) return { canvasBuf, maskBuf };
return {
canvasBuf: await resizeCoverToPng(canvasBuf, target2.width, target2.height),
maskBuf: await resizeCoverToPng(maskBuf, target2.width, target2.height)
};
}
// src/helpers/pngMetadata.ts
import os5 from "node:os";
var DEFAULT_GENERATOR = "ceveyne/draw-things-chat-core";
var CRC_TABLE = (() => {
const table = new Int32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) {
c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
}
table[n] = c;
}
return table;
})();
function crc32(data) {
let crc = 4294967295;
for (let i = 0; i < data.length; i++) {
crc = CRC_TABLE[(crc ^ data[i]) & 255] ^ crc >>> 8;
}
return (crc ^ 4294967295) >>> 0;
}
function normPath(absPath) {
const home = os5.homedir();
return absPath.startsWith(home) ? "~" + absPath.slice(home.length) : absPath;
}
function escapeXml(s) {
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
}
function basename2(filePath) {
return filePath.replace(/^.*[\\/]/, "");
}
function buildA1111Description(p) {
const lines = [];
if (p.prompt) lines.push(p.prompt);
if (p.negativePrompt) lines.push(`Negative prompt: ${p.negativePrompt}`);
const info = [];
if (typeof p.steps === "number") info.push(`Steps: ${p.steps}`);
if (p.sampler) info.push(`Sampler: ${p.sampler}`);
if (typeof p.guidanceScale === "number") info.push(`Guidance Scale: ${p.guidanceScale}`);
if (typeof p.seed === "number") info.push(`Seed: ${p.seed}`);
if (typeof p.width === "number" && typeof p.height === "number") {
info.push(`Size: ${p.width}x${p.height}`);
}
if (p.model) info.push(`Model: ${p.model}`);
if (typeof p.strength === "number") info.push(`Strength: ${p.strength}`);
if (p.seedMode) info.push(`Seed Mode: ${p.seedMode}`);
if (typeof p.shift === "number") info.push(`Shift: ${p.shift}`);
if (info.length > 0) lines.push(info.join(", "));
if (p.loras) {
p.loras.forEach((l, i) => {
const idx = i + 1;
const name = basename2(l.file);
let entry = `LoRA ${idx} Model: ${name}`;
if (typeof l.weight === "number") entry += `, LoRA ${idx} Weight: ${l.weight}`;
lines.push(entry);
});
}
if (p.sources && p.sources.length > 0) {
lines.push(`Source: ${p.sources.map(normPath).join(", ")}`);
}
if (p.crop) {
lines.push(`Crop: left=${p.crop.left}%, top=${p.crop.top}%, right=${p.crop.right}%, bottom=${p.crop.bottom}%`);
}
if (p.cropSource) lines.push(`Crop Source: ${p.cropSource}`);
if (p.isVideoFrame) lines.push("Note: Last frame of generated video.");
return lines.join("\n");
}
function buildUserCommentJson(p) {
const obj = {};
if (p.prompt != null) obj["c"] = p.prompt;
if (p.negativePrompt != null) obj["uc"] = p.negativePrompt;
if (p.model) obj["model"] = p.model;
if (p.sampler) obj["sampler"] = p.sampler;
if (typeof p.guidanceScale === "number") obj["scale"] = p.guidanceScale;
if (typeof p.seed === "number") obj["seed"] = p.seed;
if (p.seedMode) obj["seed_mode"] = p.seedMode;
if (typeof p.shift === "number") obj["shift"] = p.shift;
if (typeof p.width === "number" && typeof p.height === "number") {
obj["size"] = `${p.width}x${p.height}`;
}
if (typeof p.steps === "number") obj["steps"] = p.steps;
if (typeof p.strength === "number") obj["strength"] = p.strength;
if (p.loras && p.loras.length > 0) {
obj["lora"] = p.loras.map((l) => {
const entry = { model: basename2(l.file) };
if (typeof l.weight === "number") entry["weight"] = l.weight;
return entry;
});
}
if (p.sources && p.sources.length > 0) {
obj["sources"] = p.sources.map(normPath);
}
if (p.mode) obj["mode"] = p.mode;
if (p.crop) obj["crop"] = p.crop;
if (p.cropSource) obj["crop_source"] = p.cropSource;
if (p.isVideoFrame) obj["is_video_frame"] = true;
if (p.v2) obj["v2"] = p.v2;
obj["generated_by"] = p.generatedBy ?? DEFAULT_GENERATOR;
return JSON.stringify(obj);
}
function buildXmpString(p) {
const desc = escapeXml(buildA1111Description(p));
const uc = buildUserCommentJson(p);
const createdAt = escapeXml(p.createdAt ?? (/* @__PURE__ */ new Date()).toISOString());
return [
`<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="XMP Core 6.0.0">`,
` <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">`,
` <rdf:Description rdf:about=""`,
` xmlns:dc="http://purl.org/dc/elements/1.1/"`,
` xmlns:xmp="http://ns.adobe.com/xap/1.0/"`,
` xmlns:exif="http://ns.adobe.com/exif/1.0/">`,
` <dc:description>`,
` <rdf:Alt>`,
` <rdf:li xml:lang="x-default">${desc}</rdf:li>`,
` </rdf:Alt>`,
` </dc:description>`,
` <xmp:CreatorTool>${escapeXml(p.generatedBy ?? DEFAULT_GENERATOR)}</xmp:CreatorTool>`,
` <xmp:CreateDate>${createdAt}</xmp:CreateDate>`,
` <exif:UserComment>`,
` <rdf:Alt>`,
` <rdf:li xml:lang="x-default">${uc}</rdf:li>`,
` </rdf:Alt>`,
` </exif:UserComment>`,
` </rdf:Description>`,
` </rdf:RDF>`,
`</x:xmpmeta>`
].join("\n");
}
function buildITxtChunk(keyword, text) {
const keyBuf = Buffer.from(keyword, "utf8");
const textBuf = Buffer.from(text, "utf8");
const data = Buffer.concat([
keyBuf,
Buffer.from([0, 0, 0, 0, 0]),
textBuf
]);
const typeAndData = Buffer.concat([Buffer.from("iTXt", "ascii"), data]);
const crc = crc32(typeAndData);
const chunk = Buffer.allocUnsafe(4 + 4 + data.length + 4);
chunk.writeUInt32BE(data.length, 0);
chunk.write("iTXt", 4, "ascii");
data.copy(chunk, 8);
chunk.writeUInt32BE(crc, 8 + data.length);
return chunk;
}
var PNG_SIG = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
var IHDR_BYTES = 25;
function injectXmpIntoBuffer(pngBuf, params) {
if (pngBuf.length < PNG_SIG.length + IHDR_BYTES) return pngBuf;
if (!pngBuf.subarray(0, PNG_SIG.length).equals(PNG_SIG)) return pngBuf;
const xmp = buildXmpString(params);
const chunk = buildITxtChunk("XML:com.adobe.xmp", xmp);
const insertAt = PNG_SIG.length + IHDR_BYTES;
return Buffer.concat([
pngBuf.subarray(0, insertAt),
chunk,
pngBuf.subarray(insertAt)
]);
}
// src/helpers/generationConfigV2.ts
var flatbuffers8 = __toESM(require_flatbuffers(), 1);
// src/interfaces/generation-configuration.ts
var flatbuffers7 = __toESM(require_flatbuffers(), 1);
// src/interfaces/color-calibration.ts
var ColorCalibration = /* @__PURE__ */ ((ColorCalibration2) => {
ColorCalibration2[ColorCalibration2["Disabled"] = 0] = "Disabled";
ColorCalibration2[ColorCalibration2["Lab"] = 1] = "Lab";
return ColorCalibration2;
})(ColorCalibration || {});
// src/interfaces/compression-method.ts
var CompressionMethod = /* @__PURE__ */ ((CompressionMethod2) => {
CompressionMethod2[CompressionMethod2["Disabled"] = 0] = "Disabled";
CompressionMethod2[CompressionMethod2["H264"] = 1] = "H264";
CompressionMethod2[CompressionMethod2["H265"] = 2] = "H265";
CompressionMethod2[CompressionMethod2["Jpeg"] = 3] = "Jpeg";
return CompressionMethod2;
})(CompressionMethod || {});
// src/interfaces/generation-configuration.ts
var GenerationConfiguration = class _GenerationConfiguration {
bb = null;
bb_pos = 0;
__init(i, bb) {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsGenerationConfiguration(bb, obj) {
return (obj || new _GenerationConfiguration()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
static getSizePrefixedRootAsGenerationConfiguration(bb, obj) {
bb.setPosition(bb.position() + flatbuffers7.SIZE_PREFIX_LENGTH);
return (obj || new _GenerationConfiguration()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
id() {
const offset = this.bb.__offset(this.bb_pos, 4);
return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0");
}
startWidth() {
const offset = this.bb.__offset(this.bb_pos, 6);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
}
startHeight() {
const offset = this.bb.__offset(this.bb_pos, 8);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
}
seed() {
const offset = this.bb.__offset(this.bb_pos, 10);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
steps() {
const offset = this.bb.__offset(this.bb_pos, 12);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
guidanceScale() {
const offset = this.bb.__offset(this.bb_pos, 14);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0;
}
strength() {
const offset = this.bb.__offset(this.bb_pos, 16);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0;
}
model(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 18);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
sampler() {
const offset = this.bb.__offset(this.bb_pos, 20);
return offset ? this.bb.readInt8(this.bb_pos + offset) : 0 /* DPMPP2MKarras */;
}
batchCount() {
const offset = this.bb.__offset(this.bb_pos, 22);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 1;
}
batchSize() {
const offset = this.bb.__offset(this.bb_pos, 24);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 1;
}
hiresFix() {
const offset = this.bb.__offset(this.bb_pos, 26);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
hiresFixStartWidth() {
const offset = this.bb.__offset(this.bb_pos, 28);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
}
hiresFixStartHeight() {
const offset = this.bb.__offset(this.bb_pos, 30);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
}
hiresFixStrength() {
const offset = this.bb.__offset(this.bb_pos, 32);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.7;
}
upscaler(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 34);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
imageGuidanceScale() {
const offset = this.bb.__offset(this.bb_pos, 36);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1.5;
}
seedMode() {
const offset = this.bb.__offset(this.bb_pos, 38);
return offset ? this.bb.readInt8(this.bb_pos + offset) : 0 /* Legacy */;
}
clipSkip() {
const offset = this.bb.__offset(this.bb_pos, 40);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 1;
}
controls(index2, obj) {
const offset = this.bb.__offset(this.bb_pos, 42);
return offset ? (obj || new Control()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index2 * 4), this.bb) : null;
}
controlsLength() {
const offset = this.bb.__offset(this.bb_pos, 42);
return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
}
loras(index2, obj) {
const offset = this.bb.__offset(this.bb_pos, 44);
return offset ? (obj || new LoRA()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index2 * 4), this.bb) : null;
}
lorasLength() {
const offset = this.bb.__offset(this.bb_pos, 44);
return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
}
maskBlur() {
const offset = this.bb.__offset(this.bb_pos, 46);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0;
}
faceRestoration(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 48);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
clipWeight() {
const offset = this.bb.__offset(this.bb_pos, 54);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1;
}
negativePromptForImagePrior() {
const offset = this.bb.__offset(this.bb_pos, 56);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true;
}
imagePriorSteps() {
const offset = this.bb.__offset(this.bb_pos, 58);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 5;
}
refinerModel(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 60);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
originalImageHeight() {
const offset = this.bb.__offset(this.bb_pos, 62);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
originalImageWidth() {
const offset = this.bb.__offset(this.bb_pos, 64);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
cropTop() {
const offset = this.bb.__offset(this.bb_pos, 66);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
}
cropLeft() {
const offset = this.bb.__offset(this.bb_pos, 68);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
}
targetImageHeight() {
const offset = this.bb.__offset(this.bb_pos, 70);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
targetImageWidth() {
const offset = this.bb.__offset(this.bb_pos, 72);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
aestheticScore() {
const offset = this.bb.__offset(this.bb_pos, 74);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 6;
}
negativeAestheticScore() {
const offset = this.bb.__offset(this.bb_pos, 76);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 2.5;
}
zeroNegativePrompt() {
const offset = this.bb.__offset(this.bb_pos, 78);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
refinerStart() {
const offset = this.bb.__offset(this.bb_pos, 80);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.7;
}
negativeOriginalImageHeight() {
const offset = this.bb.__offset(this.bb_pos, 82);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
negativeOriginalImageWidth() {
const offset = this.bb.__offset(this.bb_pos, 84);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
}
name(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 86);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
fpsId() {
const offset = this.bb.__offset(this.bb_pos, 88);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 5;
}
motionBucketId() {
const offset = this.bb.__offset(this.bb_pos, 90);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 127;
}
condAug() {
const offset = this.bb.__offset(this.bb_pos, 92);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.02;
}
startFrameCfg() {
const offset = this.bb.__offset(this.bb_pos, 94);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1;
}
numFrames() {
const offset = this.bb.__offset(this.bb_pos, 96);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 14;
}
maskBlurOutset() {
const offset = this.bb.__offset(this.bb_pos, 98);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
}
sharpness() {
const offset = this.bb.__offset(this.bb_pos, 100);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0;
}
shift() {
const offset = this.bb.__offset(this.bb_pos, 102);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1;
}
stage2Steps() {
const offset = this.bb.__offset(this.bb_pos, 104);
return offset ? this.bb.readUint32(this.bb_pos + offset) : 10;
}
stage2Cfg() {
const offset = this.bb.__offset(this.bb_pos, 106);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1;
}
stage2Shift() {
const offset = this.bb.__offset(this.bb_pos, 108);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 1;
}
tiledDecoding() {
const offset = this.bb.__offset(this.bb_pos, 110);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
decodingTileWidth() {
const offset = this.bb.__offset(this.bb_pos, 112);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 10;
}
decodingTileHeight() {
const offset = this.bb.__offset(this.bb_pos, 114);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 10;
}
decodingTileOverlap() {
const offset = this.bb.__offset(this.bb_pos, 116);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 2;
}
stochasticSamplingGamma() {
const offset = this.bb.__offset(this.bb_pos, 118);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.3;
}
preserveOriginalAfterInpaint() {
const offset = this.bb.__offset(this.bb_pos, 120);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true;
}
tiledDiffusion() {
const offset = this.bb.__offset(this.bb_pos, 122);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
diffusionTileWidth() {
const offset = this.bb.__offset(this.bb_pos, 124);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 16;
}
diffusionTileHeight() {
const offset = this.bb.__offset(this.bb_pos, 126);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 16;
}
diffusionTileOverlap() {
const offset = this.bb.__offset(this.bb_pos, 128);
return offset ? this.bb.readUint16(this.bb_pos + offset) : 2;
}
upscalerScaleFactor() {
const offset = this.bb.__offset(this.bb_pos, 130);
return offset ? this.bb.readUint8(this.bb_pos + offset) : 0;
}
t5TextEncoder() {
const offset = this.bb.__offset(this.bb_pos, 132);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true;
}
separateClipL() {
const offset = this.bb.__offset(this.bb_pos, 134);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
clipLText(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 136);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
separateOpenClipG() {
const offset = this.bb.__offset(this.bb_pos, 138);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
openClipGText(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 140);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
speedUpWithGuidanceEmbed() {
const offset = this.bb.__offset(this.bb_pos, 142);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true;
}
guidanceEmbed() {
const offset = this.bb.__offset(this.bb_pos, 144);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 3.5;
}
resolutionDependentShift() {
const offset = this.bb.__offset(this.bb_pos, 146);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true;
}
teaCacheStart() {
const offset = this.bb.__offset(this.bb_pos, 148);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 5;
}
teaCacheEnd() {
const offset = this.bb.__offset(this.bb_pos, 150);
return offset ? this.bb.readInt32(this.bb_pos + offset) : -1;
}
teaCacheThreshold() {
const offset = this.bb.__offset(this.bb_pos, 152);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.06;
}
teaCache() {
const offset = this.bb.__offset(this.bb_pos, 154);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
separateT5() {
const offset = this.bb.__offset(this.bb_pos, 156);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
t5Text(optionalEncoding) {
const offset = this.bb.__offset(this.bb_pos, 158);
return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
}
teaCacheMaxSkipSteps() {
const offset = this.bb.__offset(this.bb_pos, 160);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 3;
}
causalInferenceEnabled() {
const offset = this.bb.__offset(this.bb_pos, 162);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
causalInference() {
const offset = this.bb.__offset(this.bb_pos, 164);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 3;
}
causalInferencePad() {
const offset = this.bb.__offset(this.bb_pos, 166);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
}
cfgZeroStar() {
const offset = this.bb.__offset(this.bb_pos, 168);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
cfgZeroInitSteps() {
const offset = this.bb.__offset(this.bb_pos, 170);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
}
compressionArtifacts() {
const offset = this.bb.__offset(this.bb_pos, 172);
return offset ? this.bb.readInt8(this.bb_pos + offset) : 0 /* Disabled */;
}
compressionArtifactsQuality() {
const offset = this.bb.__offset(this.bb_pos, 174);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 43.1;
}
colorCalibration() {
const offset = this.bb.__offset(this.bb_pos, 176);
return offset ? this.bb.readInt8(this.bb_pos + offset) : 0 /* Disabled */;
}
expandPromptToJson() {
const offset = this.bb.__offset(this.bb_pos, 178);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
shiftForAudio() {
const offset = this.bb.__offset(this.bb_pos, 180);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 3;
}
usesSolAttention() {
const offset = this.bb.__offset(this.bb_pos, 182);
return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
}
solAttentionStart() {
const offset = this.bb.__offset(this.bb_pos, 184);
return offset ? this.bb.readInt32(this.bb_pos + offset) : 2;
}
solAttentionTau() {
const offset = this.bb.__offset(this.bb_pos, 186);
return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.5;
}
static startGenerationConfiguration(builder) {
builder.startObject(92);
}
static addId(builder, id) {
builder.addFieldInt64(0, id, BigInt("0"));
}
static addStartWidth(builder, startWidth) {
builder.addFieldInt16(1, startWidth, 0);
}
static addStartHeight(builder, startHeight) {
builder.addFieldInt16(2, startHeight, 0);
}
static addSeed(builder, seed) {
builder.addFieldInt32(3, seed, 0);
}
static addSteps(builder, steps) {
builder.addFieldInt32(4, steps, 0);
}
static addGuidanceScale(builder, guidanceScale) {
builder.addFieldFloat32(5, guidanceScale, 0);
}
static addStrength(builder, strength) {
builder.addFieldFloat32(6, strength, 0);
}
static addModel(builder, modelOffset) {
builder.addFieldOffset(7, modelOffset, 0);
}
static addSampler(builder, sampler) {
builder.addFieldInt8(8, sampler, 0 /* DPMPP2MKarras */);
}
static addBatchCount(builder, batchCount) {
builder.addFieldInt32(9, batchCount, 1);
}
static addBatchSize(builder, batchSize) {
builder.addFieldInt32(10, batchSize, 1);
}
static addHiresFix(builder, hiresFix) {
builder.addFieldInt8(11, +hiresFix, 0);
}
static addHiresFixStartWidth(builder, hiresFixStartWidth) {
builder.addFieldInt16(12, hiresFixStartWidth, 0);
}
static addHiresFixStartHeight(builder, hiresFixStartHeight) {
builder.addFieldInt16(13, hiresFixStartHeight, 0);
}
static addHiresFixStrength(builder, hiresFixStrength) {
builder.addFieldFloat32(14, hiresFixStrength, 0.7);
}
static addUpscaler(builder, upscalerOffset) {
builder.addFieldOffset(15, upscalerOffset, 0);
}
static addImageGuidanceScale(builder, imageGuidanceScale) {
builder.addFieldFloat32(16, imageGuidanceScale, 1.5);
}
static addSeedMode(builder, seedMode) {
builder.addFieldInt8(17, seedMode, 0 /* Legacy */);
}
static addClipSkip(builder, clipSkip) {
builder.addFieldInt32(18, clipSkip, 1);
}
static addControls(builder, controlsOffset) {
builder.addFieldOffset(19, controlsOffset, 0);
}
static createControlsVector(builder, data) {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
static startControlsVector(builder, numElems) {
builder.startVector(4, numElems, 4);
}
static addLoras(builder, lorasOffset) {
builder.addFieldOffset(20, lorasOffset, 0);
}
static createLorasVector(builder, data) {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
static startLorasVector(builder, numElems) {
builder.startVector(4, numElems, 4);
}
static addMaskBlur(builder, maskBlur) {
builder.addFieldFloat32(21, maskBlur, 0);
}
static addFaceRestoration(builder, faceRestorationOffset) {
builder.addFieldOffset(22, faceRestorationOffset, 0);
}
static addClipWeight(builder, clipWeight) {
builder.addFieldFloat32(25, clipWeight, 1);
}
static addNegativePromptForImagePrior(builder, negativePromptForImagePrior) {
builder.addFieldInt8(26, +negativePromptForImagePrior, 1);
}
static addImagePriorSteps(builder, imagePriorSteps) {
builder.addFieldInt32(27, imagePriorSteps, 5);
}
static addRefinerModel(builder, refinerModelOffset) {
builder.addFieldOffset(28, refinerModelOffset, 0);
}
static addOriginalImageHeight(builder, originalImageHeight) {
builder.addFieldInt32(29, originalImageHeight, 0);
}
static addOriginalImageWidth(builder, originalImageWidth) {
builder.addFieldInt32(30, originalImageWidth, 0);
}
static addCropTop(builder, cropTop) {
builder.addFieldInt32(31, cropTop, 0);
}
static addCropLeft(builder, cropLeft) {
builder.addFieldInt32(32, cropLeft, 0);
}
static addTargetImageHeight(builder, targetImageHeight) {
builder.addFieldInt32(33, targetImageHeight, 0);
}
static addTargetImageWidth(builder, targetImageWidth) {
builder.addFieldInt32(34, targetImageWidth, 0);
}
static addAestheticScore(builder, aestheticScore) {
builder.addFieldFloat32(35, aestheticScore, 6);
}
static addNegativeAestheticScore(builder, negativeAestheticScore) {
builder.addFieldFloat32(36, negativeAestheticScore, 2.5);
}
static addZeroNegativePrompt(builder, zeroNegativePrompt) {
builder.addFieldInt8(37, +zeroNegativePrompt, 0);
}
static addRefinerStart(builder, refinerStart) {
builder.addFieldFloat32(38, refinerStart, 0.7);
}
static addNegativeOriginalImageHeight(builder, negativeOriginalImageHeight) {
builder.addFieldInt32(39, negativeOriginalImageHeight, 0);
}
static addNegativeOriginalImageWidth(builder, negativeOriginalImageWidth) {
builder.addFieldInt32(40, negativeOriginalImageWidth, 0);
}
static addName(builder, nameOffset) {
builder.addFieldOffset(41, nameOffset, 0);
}
static addFpsId(builder, fpsId) {
builder.addFieldInt32(42, fpsId, 5);
}
static addMotionBucketId(builder, motionBucketId) {
builder.addFieldInt32(43, motionBucketId, 127);
}
static addCondAug(builder, condAug) {
builder.addFieldFloat32(44, condAug, 0.02);
}
static addStartFrameCfg(builder, startFrameCfg) {
builder.addFieldFloat32(45, startFrameCfg, 1);
}
static addNumFrames(builder, numFrames) {
builder.addFieldInt32(46, numFrames, 14);
}
static addMaskBlurOutset(builder, maskBlurOutset) {
builder.addFieldInt32(47, maskBlurOutset, 0);
}
static addSharpness(builder, sharpness) {
builder.addFieldFloat32(48, sharpness, 0);
}
static addShift(builder, shift) {
builder.addFieldFloat32(49, shift, 1);
}
static addStage2Steps(builder, stage2Steps) {
builder.addFieldInt32(50, stage2Steps, 10);
}
static addStage2Cfg(builder, stage2Cfg) {
builder.addFieldFloat32(51, stage2Cfg, 1);
}
static addStage2Shift(builder, stage2Shift) {
builder.addFieldFloat32(52, stage2Shift, 1);
}
static addTiledDecoding(builder, tiledDecoding) {
builder.addFieldInt8(53, +tiledDecoding, 0);
}
static addDecodingTileWidth(builder, decodingTileWidth) {
builder.addFieldInt16(54, decodingTileWidth, 10);
}
static addDecodingTileHeight(builder, decodingTileHeight) {
builder.addFieldInt16(55, decodingTileHeight, 10);
}
static addDecodingTileOverlap(builder, decodingTileOverlap) {
builder.addFieldInt16(56, decodingTileOverlap, 2);
}
static addStochasticSamplingGamma(builder, stochasticSamplingGamma) {
builder.addFieldFloat32(57, stochasticSamplingGamma, 0.3);
}
static addPreserveOriginalAfterInpaint(builder, preserveOriginalAfterInpaint) {
builder.addFieldInt8(58, +preserveOriginalAfterInpaint, 1);
}
static addTiledDiffusion(builder, tiledDiffusion) {
builder.addFieldInt8(59, +tiledDiffusion, 0);
}
static addDiffusionTileWidth(builder, diffusionTileWidth) {
builder.addFieldInt16(60, diffusionTileWidth, 16);
}
static addDiffusionTileHeight(builder, diffusionTileHeight) {
builder.addFieldInt16(61, diffusionTileHeight, 16);
}
static addDiffusionTileOverlap(builder, diffusionTileOverlap) {
builder.addFieldInt16(62, diffusionTileOverlap, 2);
}
static addUpscalerScaleFactor(builder, upscalerScaleFactor) {
builder.addFieldInt8(63, upscalerScaleFactor, 0);
}
static addT5TextEncoder(builder, t5TextEncoder) {
builder.addFieldInt8(64, +t5TextEncoder, 1);
}
static addSeparateClipL(builder, separateClipL) {
builder.addFieldInt8(65, +separateClipL, 0);
}
static addClipLText(builder, clipLTextOffset) {
builder.addFieldOffset(66, clipLTextOffset, 0);
}
static addSeparateOpenClipG(builder, separateOpenClipG) {
builder.addFieldInt8(67, +separateOpenClipG, 0);
}
static addOpenClipGText(builder, openClipGTextOffset) {
builder.addFieldOffset(68, openClipGTextOffset, 0);
}
static addSpeedUpWithGuidanceEmbed(builder, speedUpWithGuidanceEmbed) {
builder.addFieldInt8(69, +speedUpWithGuidanceEmbed, 1);
}
static addGuidanceEmbed(builder, guidanceEmbed) {
builder.addFieldFloat32(70, guidanceEmbed, 3.5);
}
static addResolutionDependentShift(builder, resolutionDependentShift) {
builder.addFieldInt8(71, +resolutionDependentShift, 1);
}
static addTeaCacheStart(builder, teaCacheStart) {
builder.addFieldInt32(72, teaCacheStart, 5);
}
static addTeaCacheEnd(builder, teaCacheEnd) {
builder.addFieldInt32(73, teaCacheEnd, -1);
}
static addTeaCacheThreshold(builder, teaCacheThreshold) {
builder.addFieldFloat32(74, teaCacheThreshold, 0.06);
}
static addTeaCache(builder, teaCache) {
builder.addFieldInt8(75, +teaCache, 0);
}
static addSeparateT5(builder, separateT5) {
builder.addFieldInt8(76, +separateT5, 0);
}
static addT5Text(builder, t5TextOffset) {
builder.addFieldOffset(77, t5TextOffset, 0);
}
static addTeaCacheMaxSkipSteps(builder, teaCacheMaxSkipSteps) {
builder.addFieldInt32(78, teaCacheMaxSkipSteps, 3);
}
static addCausalInferenceEnabled(builder, causalInferenceEnabled) {
builder.addFieldInt8(79, +causalInferenceEnabled, 0);
}
static addCausalInference(builder, causalInference) {
builder.addFieldInt32(80, causalInference, 3);
}
static addCausalInferencePad(builder, causalInferencePad) {
builder.addFieldInt32(81, causalInferencePad, 0);
}
static addCfgZeroStar(builder, cfgZeroStar) {
builder.addFieldInt8(82, +cfgZeroStar, 0);
}
static addCfgZeroInitSteps(builder, cfgZeroInitSteps) {
builder.addFieldInt32(83, cfgZeroInitSteps, 0);
}
static addCompressionArtifacts(builder, compressionArtifacts) {
builder.addFieldInt8(84, compressionArtifacts, 0 /* Disabled */);
}
static addCompressionArtifactsQuality(builder, compressionArtifactsQuality) {
builder.addFieldFloat32(85, compressionArtifactsQuality, 43.1);
}
static addColorCalibration(builder, colorCalibration) {
builder.addFieldInt8(86, colorCalibration, 0 /* Disabled */);
}
static addExpandPromptToJson(builder, expandPromptToJson) {
builder.addFieldInt8(87, +expandPromptToJson, 0);
}
static addShiftForAudio(builder, shiftForAudio) {
builder.addFieldFloat32(88, shiftForAudio, 3);
}
static addUsesSolAttention(builder, usesSolAttention) {
builder.addFieldInt8(89, +usesSolAttention, 0);
}
static addSolAttentionStart(builder, solAttentionStart) {
builder.addFieldInt32(90, solAttentionStart, 2);
}
static addSolAttentionTau(builder, solAttentionTau) {
builder.addFieldFloat32(91, solAttentionTau, 0.5);
}
static endGenerationConfiguration(builder) {
const offset = builder.endObject();
return offset;
}
static finishGenerationConfigurationBuffer(builder, offset) {
builder.finish(offset);
}
static finishSizePrefixedGenerationConfigurationBuffer(builder, offset) {
builder.finish(offset, void 0, true);
}
static createGenerationConfiguration(builder, id, startWidth, startHeight, seed, steps, guidanceScale, strength, modelOffset, sampler, batchCount, batchSize, hiresFix, hiresFixStartWidth, hiresFixStartHeight, hiresFixStrength, upscalerOffset, imageGuidanceScale, seedMode, clipSkip, controlsOffset, lorasOffset, maskBlur, faceRestorationOffset, clipWeight, negativePromptForImagePrior, imagePriorSteps, refinerModelOffset, originalImageHeight, originalImageWidth, cropTop, cropLeft, targetImageHeight, targetImageWidth, aestheticScore, negativeAestheticScore, zeroNegativePrompt, refinerStart, negativeOriginalImageHeight, negativeOriginalImageWidth, nameOffset, fpsId, motionBucketId, condAug, startFrameCfg, numFrames, maskBlurOutset, sharpness, shift, stage2Steps, stage2Cfg, stage2Shift, tiledDecoding, decodingTileWidth, decodingTileHeight, decodingTileOverlap, stochasticSamplingGamma, preserveOriginalAfterInpaint, tiledDiffusion, diffusionTileWidth, diffusionTileHeight, diffusionTileOverlap, upscalerScaleFactor, t5TextEncoder, separateClipL, clipLTextOffset, separateOpenClipG, openClipGTextOffset, speedUpWithGuidanceEmbed, guidanceEmbed, resolutionDependentShift, teaCacheStart, teaCacheEnd, teaCacheThreshold, teaCache, separateT5, t5TextOffset, teaCacheMaxSkipSteps, causalInferenceEnabled, causalInference, causalInferencePad, cfgZeroStar, cfgZeroInitSteps, compressionArtifacts, compressionArtifactsQuality, colorCalibration, expandPromptToJson, shiftForAudio, usesSolAttention, solAttentionStart, solAttentionTau) {
_GenerationConfiguration.startGenerationConfiguration(builder);
_GenerationConfiguration.addId(builder, id);
_GenerationConfiguration.addStartWidth(builder, startWidth);
_GenerationConfiguration.addStartHeight(builder, startHeight);
_GenerationConfiguration.addSeed(builder, seed);
_GenerationConfiguration.addSteps(builder, steps);
_GenerationConfiguration.addGuidanceScale(builder, guidanceScale);
_GenerationConfiguration.addStrength(builder, strength);
_GenerationConfiguration.addModel(builder, modelOffset);
_GenerationConfiguration.addSampler(builder, sampler);
_GenerationConfiguration.addBatchCount(builder, batchCount);
_GenerationConfiguration.addBatchSize(builder, batchSize);
_GenerationConfiguration.addHiresFix(builder, hiresFix);
_GenerationConfiguration.addHiresFixStartWidth(builder, hiresFixStartWidth);
_GenerationConfiguration.addHiresFixStartHeight(builder, hiresFixStartHeight);
_GenerationConfiguration.addHiresFixStrength(builder, hiresFixStrength);
_GenerationConfiguration.addUpscaler(builder, upscalerOffset);
_GenerationConfiguration.addImageGuidanceScale(builder, imageGuidanceScale);
_GenerationConfiguration.addSeedMode(builder, seedMode);
_GenerationConfiguration.addClipSkip(builder, clipSkip);
_GenerationConfiguration.addControls(builder, controlsOffset);
_GenerationConfiguration.addLoras(builder, lorasOffset);
_GenerationConfiguration.addMaskBlur(builder, maskBlur);
_GenerationConfiguration.addFaceRestoration(builder, faceRestorationOffset);
_GenerationConfiguration.addClipWeight(builder, clipWeight);
_GenerationConfiguration.addNegativePromptForImagePrior(builder, negativePromptForImagePrior);
_GenerationConfiguration.addImagePriorSteps(builder, imagePriorSteps);
_GenerationConfiguration.addRefinerModel(builder, refinerModelOffset);
_GenerationConfiguration.addOriginalImageHeight(builder, originalImageHeight);
_GenerationConfiguration.addOriginalImageWidth(builder, originalImageWidth);
_GenerationConfiguration.addCropTop(builder, cropTop);
_GenerationConfiguration.addCropLeft(builder, cropLeft);
_GenerationConfiguration.addTargetImageHeight(builder, targetImageHeight);
_GenerationConfiguration.addTargetImageWidth(builder, targetImageWidth);
_GenerationConfiguration.addAestheticScore(builder, aestheticScore);
_GenerationConfiguration.addNegativeAestheticScore(builder, negativeAestheticScore);
_GenerationConfiguration.addZeroNegativePrompt(builder, zeroNegativePrompt);
_GenerationConfiguration.addRefinerStart(builder, refinerStart);
_GenerationConfiguration.addNegativeOriginalImageHeight(builder, negativeOriginalImageHeight);
_GenerationConfiguration.addNegativeOriginalImageWidth(builder, negativeOriginalImageWidth);
_GenerationConfiguration.addName(builder, nameOffset);
_GenerationConfiguration.addFpsId(builder, fpsId);
_GenerationConfiguration.addMotionBucketId(builder, motionBucketId);
_GenerationConfiguration.addCondAug(builder, condAug);
_GenerationConfiguration.addStartFrameCfg(builder, startFrameCfg);
_GenerationConfiguration.addNumFrames(builder, numFrames);
_GenerationConfiguration.addMaskBlurOutset(builder, maskBlurOutset);
_GenerationConfiguration.addSharpness(builder, sharpness);
_GenerationConfiguration.addShift(builder, shift);
_GenerationConfiguration.addStage2Steps(builder, stage2Steps);
_GenerationConfiguration.addStage2Cfg(builder, stage2Cfg);
_GenerationConfiguration.addStage2Shift(builder, stage2Shift);
_GenerationConfiguration.addTiledDecoding(builder, tiledDecoding);
_GenerationConfiguration.addDecodingTileWidth(builder, decodingTileWidth);
_GenerationConfiguration.addDecodingTileHeight(builder, decodingTileHeight);
_GenerationConfiguration.addDecodingTileOverlap(builder, decodingTileOverlap);
_GenerationConfiguration.addStochasticSamplingGamma(builder, stochasticSamplingGamma);
_GenerationConfiguration.addPreserveOriginalAfterInpaint(builder, preserveOriginalAfterInpaint);
_GenerationConfiguration.addTiledDiffusion(builder, tiledDiffusion);
_GenerationConfiguration.addDiffusionTileWidth(builder, diffusionTileWidth);
_GenerationConfiguration.addDiffusionTileHeight(builder, diffusionTileHeight);
_GenerationConfiguration.addDiffusionTileOverlap(builder, diffusionTileOverlap);
_GenerationConfiguration.addUpscalerScaleFactor(builder, upscalerScaleFactor);
_GenerationConfiguration.addT5TextEncoder(builder, t5TextEncoder);
_GenerationConfiguration.addSeparateClipL(builder, separateClipL);
_GenerationConfiguration.addClipLText(builder, clipLTextOffset);
_GenerationConfiguration.addSeparateOpenClipG(builder, separateOpenClipG);
_GenerationConfiguration.addOpenClipGText(builder, openClipGTextOffset);
_GenerationConfiguration.addSpeedUpWithGuidanceEmbed(builder, speedUpWithGuidanceEmbed);
_GenerationConfiguration.addGuidanceEmbed(builder, guidanceEmbed);
_GenerationConfiguration.addResolutionDependentShift(builder, resolutionDependentShift);
_GenerationConfiguration.addTeaCacheStart(builder, teaCacheStart);
_GenerationConfiguration.addTeaCacheEnd(builder, teaCacheEnd);
_GenerationConfiguration.addTeaCacheThreshold(builder, teaCacheThreshold);
_GenerationConfiguration.addTeaCache(builder, teaCache);
_GenerationConfiguration.addSeparateT5(builder, separateT5);
_GenerationConfiguration.addT5Text(builder, t5TextOffset);
_GenerationConfiguration.addTeaCacheMaxSkipSteps(builder, teaCacheMaxSkipSteps);
_GenerationConfiguration.addCausalInferenceEnabled(builder, causalInferenceEnabled);
_GenerationConfiguration.addCausalInference(builder, causalInference);
_GenerationConfiguration.addCausalInferencePad(builder, causalInferencePad);
_GenerationConfiguration.addCfgZeroStar(builder, cfgZeroStar);
_GenerationConfiguration.addCfgZeroInitSteps(builder, cfgZeroInitSteps);
_GenerationConfiguration.addCompressionArtifacts(builder, compressionArtifacts);
_GenerationConfiguration.addCompressionArtifactsQuality(builder, compressionArtifactsQuality);
_GenerationConfiguration.addColorCalibration(builder, colorCalibration);
_GenerationConfiguration.addExpandPromptToJson(builder, expandPromptToJson);
_GenerationConfiguration.addShiftForAudio(builder, shiftForAudio);
_GenerationConfiguration.addUsesSolAttention(builder, usesSolAttention);
_GenerationConfiguration.addSolAttentionStart(builder, solAttentionStart);
_GenerationConfiguration.addSolAttentionTau(builder, solAttentionTau);
return _GenerationConfiguration.endGenerationConfiguration(builder);
}
};
// src/helpers/generationConfigV2.ts
function f32(value) {
return Number.isFinite(value) ? parseFloat(value.toPrecision(7)) : value;
}
function omitNull(obj) {
for (const key of Object.keys(obj)) {
if (obj[key] === null || obj[key] === void 0) delete obj[key];
}
return obj;
}
var LORA_MODE = {
[0 /* All */]: "all",
[1 /* Base */]: "base",
[2 /* Refiner */]: "refiner"
};
var CONTROL_MODE = {
[0 /* Balanced */]: "balanced",
[1 /* Prompt */]: "prompt",
[2 /* Control */]: "control"
};
var COMPRESSION = {
[0 /* Disabled */]: "disabled",
[1 /* H264 */]: "h264",
[2 /* H265 */]: "h265",
[3 /* Jpeg */]: "jpeg"
};
var COLOR_CALIBRATION = {
[0 /* Disabled */]: "none",
[1 /* Lab */]: "lab"
};
function generationConfigBytesToV2(bytes) {
const c = GenerationConfiguration.getRootAsGenerationConfiguration(new flatbuffers8.ByteBuffer(bytes));
const loras = [];
for (let i = 0; i < c.lorasLength(); i++) {
const l = c.loras(i);
if (!l) continue;
loras.push(omitNull({ file: l.file(), mode: LORA_MODE[l.mode()] ?? "all", weight: f32(l.weight()) }));
}
const controls = [];
for (let i = 0; i < c.controlsLength(); i++) {
const ctl = c.controls(i);
if (!ctl) continue;
const targetBlocks = [];
for (let b = 0; b < ctl.targetBlocksLength(); b++) targetBlocks.push(String(ctl.targetBlocks(b)));
controls.push(
omitNull({
file: ctl.file(),
weight: f32(ctl.weight()),
guidanceStart: f32(ctl.guidanceStart()),
guidanceEnd: f32(ctl.guidanceEnd()),
noPrompt: ctl.noPrompt(),
globalAveragePooling: ctl.globalAveragePooling(),
downSamplingRate: f32(ctl.downSamplingRate()),
controlImportance: CONTROL_MODE[ctl.controlMode()] ?? "balanced",
inputOverride: (ControlInputType[ctl.inputOverride()] ?? "Unspecified").toLowerCase(),
targetBlocks
})
);
}
const causalEnabled = c.causalInferenceEnabled();
return omitNull({
id: Number(c.id()),
width: c.startWidth() * 64,
height: c.startHeight() * 64,
seed: c.seed(),
steps: c.steps(),
guidanceScale: f32(c.guidanceScale()),
strength: f32(c.strength()),
model: c.model(),
sampler: c.sampler(),
hiresFix: c.hiresFix(),
hiresFixWidth: c.hiresFixStartWidth() * 64,
hiresFixHeight: c.hiresFixStartHeight() * 64,
hiresFixStrength: f32(c.hiresFixStrength()),
tiledDecoding: c.tiledDecoding(),
decodingTileWidth: c.decodingTileWidth() * 64,
decodingTileHeight: c.decodingTileHeight() * 64,
decodingTileOverlap: c.decodingTileOverlap() * 64,
tiledDiffusion: c.tiledDiffusion(),
diffusionTileWidth: c.diffusionTileWidth() * 64,
diffusionTileHeight: c.diffusionTileHeight() * 64,
diffusionTileOverlap: c.diffusionTileOverlap() * 64,
upscaler: c.upscaler(),
upscalerScaleFactor: c.upscalerScaleFactor(),
imageGuidanceScale: f32(c.imageGuidanceScale()),
seedMode: c.seedMode(),
clipSkip: c.clipSkip(),
controls,
loras,
maskBlur: f32(c.maskBlur()),
maskBlurOutset: c.maskBlurOutset(),
sharpness: f32(c.sharpness()),
faceRestoration: c.faceRestoration(),
clipWeight: f32(c.clipWeight()),
negativePromptForImagePrior: c.negativePromptForImagePrior(),
imagePriorSteps: c.imagePriorSteps(),
refinerModel: c.refinerModel(),
originalImageHeight: c.originalImageHeight(),
originalImageWidth: c.originalImageWidth(),
cropTop: c.cropTop(),
cropLeft: c.cropLeft(),
targetImageHeight: c.targetImageHeight(),
targetImageWidth: c.targetImageWidth(),
aestheticScore: f32(c.aestheticScore()),
negativeAestheticScore: f32(c.negativeAestheticScore()),
zeroNegativePrompt: c.zeroNegativePrompt(),
refinerStart: f32(c.refinerStart()),
negativeOriginalImageHeight: c.negativeOriginalImageHeight(),
negativeOriginalImageWidth: c.negativeOriginalImageWidth(),
batchCount: c.batchCount(),
batchSize: c.batchSize(),
numFrames: c.numFrames(),
fps: c.fpsId(),
motionScale: c.motionBucketId(),
guidingFrameNoise: f32(c.condAug()),
startFrameGuidance: f32(c.startFrameCfg()),
shift: f32(c.shift()),
stage2Steps: c.stage2Steps(),
stage2Guidance: f32(c.stage2Cfg()),
stage2Shift: f32(c.stage2Shift()),
stochasticSamplingGamma: f32(c.stochasticSamplingGamma()),
preserveOriginalAfterInpaint: c.preserveOriginalAfterInpaint(),
t5TextEncoder: c.t5TextEncoder(),
separateClipL: c.separateClipL(),
clipLText: c.clipLText(),
separateOpenClipG: c.separateOpenClipG(),
openClipGText: c.openClipGText(),
speedUpWithGuidanceEmbed: c.speedUpWithGuidanceEmbed(),
guidanceEmbed: f32(c.guidanceEmbed()),
resolutionDependentShift: c.resolutionDependentShift(),
teaCache: c.teaCache(),
teaCacheStart: c.teaCacheStart(),
teaCacheEnd: c.teaCacheEnd(),
teaCacheThreshold: f32(c.teaCacheThreshold()),
teaCacheMaxSkipSteps: c.teaCacheMaxSkipSteps(),
separateT5: c.separateT5(),
t5Text: c.t5Text(),
causalInference: causalEnabled ? c.causalInference() : 0,
causalInferencePad: causalEnabled ? c.causalInferencePad() : 0,
cfgZeroStar: c.cfgZeroStar(),
cfgZeroInitSteps: c.cfgZeroInitSteps(),
compressionArtifacts: COMPRESSION[c.compressionArtifacts()] ?? "disabled",
compressionArtifactsQuality: Math.min(Math.max(f32(c.compressionArtifactsQuality()), 0), 100),
colorCalibration: COLOR_CALIBRATION[c.colorCalibration()] ?? "none",
expandPromptToJson: c.expandPromptToJson(),
shiftForAudio: f32(c.shiftForAudio()),
usesSolAttention: c.usesSolAttention(),
solAttentionStart: c.solAttentionStart(),
solAttentionTau: f32(c.solAttentionTau())
});
}
// src/helpers/sourceFreshness.ts
import { createHash as createHash2 } from "node:crypto";
function stableNumber(value) {
if (!Number.isSafeInteger(value)) throw new Error("Project generation identifiers must be safe integers.");
return String(value);
}
function updateHashPart(hash, value) {
const bytes = typeof value === "string" ? Buffer.from(value, "utf8") : Buffer.from(value);
hash.update(String(bytes.length));
hash.update(":");
hash.update(bytes);
hash.update("\0");
}
function projectGenerationIdentity(input) {
const projectPath = input.projectPath.trim();
if (!projectPath) throw new Error("Project generation identity requires a project path.");
return [
projectPath,
stableNumber(input.canvasIndex),
stableNumber(input.historyVersion),
input.thumbnailId === void 0 ? "" : stableNumber(input.thumbnailId)
].join("\0");
}
function projectGenerationFingerprint(input) {
const hash = createHash2("sha256");
updateHashPart(hash, "draw-things-project-generation-v1");
updateHashPart(hash, projectGenerationIdentity(input));
updateHashPart(hash, input.generationBlob);
updateHashPart(hash, input.prompt ?? "");
updateHashPart(hash, input.negativePrompt ?? "");
return `project-generation:${hash.digest("hex")}`;
}
function diffProjectGenerationSnapshots(previous, current) {
const previousById = new Map(previous.map((snapshot) => [snapshot.id, snapshot]));
const currentIds = new Set(current.map((snapshot) => snapshot.id));
const added = [];
const changed = [];
const unchanged = [];
for (const snapshot of current) {
const prior = previousById.get(snapshot.id);
if (!prior) added.push(snapshot);
else if (prior.fingerprint === snapshot.fingerprint) unchanged.push(snapshot);
else changed.push(snapshot);
}
return {
added,
changed,
unchanged,
removed: previous.filter((snapshot) => !currentIds.has(snapshot.id))
};
}
async function checkFreshness(previous, tier1, tier2) {
const currentTier1 = tier1.compute();
if (previous && tier1.equals(previous.tier1, currentTier1)) {
return { status: "unchanged", tier1: currentTier1 };
}
if (!tier2 || !previous?.tier2) {
return { status: "changed", tier1: currentTier1 };
}
const currentTier2 = await tier2.compute();
if (tier2.equals(previous.tier2, currentTier2)) {
return { status: "unchanged-promote", tier1: currentTier1, tier2: currentTier2 };
}
return { status: "changed", tier1: currentTier1, tier2: currentTier2 };
}
// src/helpers/referenceOrigin.ts
import fs22 from "node:fs";
import path22 from "node:path";
var DERIVATIVE_TOOL_NAMES = /* @__PURE__ */ new Set(["detect_object", "annotate_image", "mask"]);
var POOL_PREFIX = {
attachment: "a",
variant: "v",
picture: "p",
image: "i"
};
function toolName(sourceTool) {
if (typeof sourceTool !== "string") return "";
const parts = sourceTool.split(/[\/,\s]+/).filter(Boolean);
return (parts[parts.length - 1] ?? "").toLowerCase();
}
function isDerivativeToolRecord(record) {
return DERIVATIVE_TOOL_NAMES.has(toolName(record?.sourceTool));
}
function derivativeSourceRef(record) {
const detect = typeof record?.detectSource === "string" ? record.detectSource.trim() : "";
if (detect) return detect;
if (toolName(record?.sourceTool) === "mask") {
const crop = typeof record?.cropSource === "string" ? record.cropSource.trim() : "";
if (crop) return crop;
}
return void 0;
}
function parseNotation(token) {
const m = String(token ?? "").trim().toLowerCase().match(/^([avpi])\s*(\d+)$/);
if (!m) return null;
const pool = m[1] === "a" ? "attachment" : m[1] === "v" ? "variant" : m[1] === "p" ? "picture" : "image";
return { pool, index: Math.max(1, parseInt(m[2], 10)) };
}
function recordIndex(pool, record) {
const raw = pool === "attachment" ? record?.a : pool === "variant" ? record?.v ?? 1 : pool === "picture" ? record?.p : record?.i;
return typeof raw === "number" ? raw : void 0;
}
function poolRecords(state, pool) {
const list = pool === "attachment" ? state.attachments : pool === "variant" ? state.variants : pool === "picture" ? state.pictures : state.images;
return Array.isArray(list) ? list : [];
}
function makeHit(pool, record) {
const index2 = recordIndex(pool, record);
if (index2 === void 0) return null;
return { pool, index: index2, notation: `${POOL_PREFIX[pool]}${index2}`, record };
}
var NAME_FIELDS = ["filename", "originAbs", "preview", "origin", "originalName", "sourceUrl"];
var POOL_ORDER = ["image", "variant", "attachment", "picture"];
function findStateRecord(state, token) {
if (!state) return null;
let raw = String(token ?? "").trim();
if (!raw) return null;
const notation = parseNotation(raw);
if (notation) {
const record = poolRecords(state, notation.pool).find((r) => recordIndex(notation.pool, r) === notation.index);
return record ? makeHit(notation.pool, record) : null;
}
if (/^file:\/\//i.test(raw)) {
try {
raw = decodeURIComponent(new URL(raw).pathname);
} catch {
return null;
}
}
const wantedBase = path22.basename(raw).toLowerCase();
if (!wantedBase) return null;
const wantedAbs = path22.isAbsolute(raw) ? path22.resolve(raw) : void 0;
for (const field of NAME_FIELDS) {
for (const pool of POOL_ORDER) {
const records = [...poolRecords(state, pool)].reverse();
for (const record of records) {
const value = record?.[field];
if (typeof value !== "string" || !value) continue;
const match = path22.basename(value).toLowerCase() === wantedBase || wantedAbs !== void 0 && path22.isAbsolute(value) && path22.resolve(value) === wantedAbs;
if (!match) continue;
const hit = makeHit(pool, record);
if (hit) return hit;
}
}
}
return null;
}
function isFile(p) {
try {
return fs22.statSync(p).isFile();
} catch {
return false;
}
}
function resolveOriginalReference(state, token, maxDepth = 8) {
const first = findStateRecord(state, token);
if (!first) return null;
const chain = [first];
const seen = /* @__PURE__ */ new Set([first.notation]);
let current = first;
for (let depth = 0; depth < maxDepth; depth++) {
const sourceRef = derivativeSourceRef(current.record);
if (!sourceRef) break;
const next = findStateRecord(state, sourceRef);
if (!next) {
const abs = sourceRef.replace(/^file:\/\//i, "");
if (path22.isAbsolute(abs) && isFile(abs)) return { ...current, chain, redirected: chain.length > 1, sourcePath: abs };
break;
}
if (seen.has(next.notation)) break;
seen.add(next.notation);
chain.push(next);
current = next;
}
return { ...current, chain, redirected: chain.length > 1 };
}
function resolveEffectiveSourceToken(state, token) {
const resolved = resolveOriginalReference(state, token);
if (!resolved) return token;
return resolved.sourcePath ?? resolved.notation;
}
// src/helpers/resolveImg2ImgSourceLMStudio.ts
import { promises as fsp4 } from "fs";
import { existsSync as existsSync6, statSync as statSync3 } from "fs";
import { join as join6, basename as basename4, extname as extname2 } from "path";
import os6 from "os";
// src/helpers/resolveLMStudioChatId.ts
import { promises as fsp3 } from "fs";
import { existsSync as existsSync5, statSync as statSync2 } from "fs";
import { join as join5, basename as basename3 } from "path";
function scoreToConfidence(score) {
if (score >= 2) return "high";
if (score === 1) return "medium";
return "low";
}
async function sleep2(ms) {
return new Promise((r) => setTimeout(r, ms));
}
async function resolveActiveLMStudioChatId(opts) {
const retries = typeof opts?.retries === "number" ? opts.retries : 4;
const delayMs = typeof opts?.delayMs === "number" ? opts.delayMs : 200;
const recentSec = typeof opts?.requireRecentMtimeSec === "number" ? opts.requireRecentMtimeSec : 120;
try {
const home = findLMStudioHome();
const convDir = join5(home, "conversations");
if (!existsSync5(convDir)) {
return {
ok: false,
reason: `LM Studio conversations dir not found: ${convDir}`
};
}
let chosenPath = null;
let mtimeMs = 0;
for (let attempt = 0; attempt < Math.max(1, retries); attempt++) {
const convFiles = listConversationFiles(convDir);
if (convFiles.length === 0) {
if (attempt < retries - 1) {
await sleep2(delayMs);
continue;
}
return { ok: false, reason: "No conversation files found" };
}
const withTimes = convFiles.map((p) => {
try {
const s = statSync2(p);
return s.isFile() ? { p, t: s.mtimeMs } : null;
} catch {
return null;
}
}).filter(Boolean);
if (withTimes.length === 0) {
if (attempt < retries - 1) {
await sleep2(delayMs);
continue;
}
return { ok: false, reason: "No readable conversation files" };
}
withTimes.sort((a, b) => b.t - a.t);
chosenPath = withTimes[0].p;
mtimeMs = withTimes[0].t;
try {
const raw = await fsp3.readFile(chosenPath, "utf8");
JSON.parse(raw);
break;
} catch {
if (attempt < retries - 1) {
await sleep2(delayMs);
continue;
}
break;
}
}
if (!chosenPath)
return { ok: false, reason: "Failed to pick conversation" };
const chatId = basename3(chosenPath).replace(/\.conversation\.json$/i, "");
let score = 0;
let reason = [];
if (mtimeMs > 0) {
const ageSec = (Date.now() - mtimeMs) / 1e3;
if (ageSec <= recentSec) {
score += 1;
reason.push(`recent:${Math.round(ageSec)}s`);
} else {
reason.push(`stale:${Math.round(ageSec)}s`);
}
}
try {
const raw = await fsp3.readFile(chosenPath, "utf8");
JSON.parse(raw);
score += 1;
reason.push("parse_ok");
} catch {
reason.push("parse_uncertain");
}
return {
ok: true,
chatId,
filePath: chosenPath,
mtimeMs,
confidence: scoreToConfidence(score),
reason: reason.join(",")
};
} catch (e) {
return { ok: false, reason: e?.message || String(e) };
}
}
// src/helpers/resolveImg2ImgSourceLMStudio.ts
var LM_HOME = join6(os6.homedir(), ".lmstudio");
try {
const h = findLMStudioHome();
if (h && typeof h === "string") LM_HOME = h;
} catch {
}
async function sleep3(ms) {
return new Promise((r) => setTimeout(r, ms));
}
async function waitForStableFile(filePath, {
maxWaitMs = 2400,
pollMs = 120,
stableRounds = 2
} = {}) {
const started = Date.now();
let lastSize = -1;
let sameCount = 0;
while (Date.now() - started <= maxWaitMs) {
try {
const st = statSync3(filePath);
if (!st.isFile()) return { ok: false, reason: "not a file" };
const size = st.size;
if (size > 0 && size === lastSize) {
sameCount++;
if (sameCount >= stableRounds) return { ok: true, size };
} else {
if (lastSize >= 0 && size !== lastSize) {
console.error(
`[LM] waitForStableFile: size changed ${lastSize} -> ${size} for ${filePath}`
);
}
sameCount = 0;
}
lastSize = size;
} catch (e) {
}
await sleep3(pollMs);
}
return { ok: false, reason: "timeout waiting for stable file" };
}
async function ensureFullyDecodable(input) {
try {
const meta = await getSize(input);
const width = typeof meta?.width === "number" ? meta.width : void 0;
const height = typeof meta?.height === "number" ? meta.height : void 0;
return {
ok: true,
buffer: input,
format: meta?.format,
width,
height
};
} catch (e) {
return { ok: false, reason: e?.message || String(e) };
}
}
async function readStableAndDecode(filePath) {
const stable = await waitForStableFile(filePath);
if (!stable.ok) {
console.error(`[LM] readStableAndDecode: ${stable.reason} for ${filePath}`);
}
const maxAttempts = 5;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const buf = await fsp4.readFile(filePath);
const validated = await ensureFullyDecodable(buf);
if (validated.ok) return { ok: true, buffer: buf };
console.error(
`[LM] decode attempt ${attempt} failed for ${filePath}: ${validated.reason}`
);
} catch (e) {
console.error(
`[LM] read attempt ${attempt} failed for ${filePath}: ${e?.message || e}`
);
}
await sleep3(150);
}
return { ok: false, reason: `failed to read/fully-decode: ${filePath}` };
}
function inferMimeFromExt2(name, fallback = "image/png") {
const ext = extname2(name).toLowerCase().replace(/^\./, "");
switch (ext) {
case "jpg":
case "jpeg":
return "image/jpeg";
case "png":
return "image/png";
case "webp":
return "image/webp";
case "gif":
return "image/gif";
case "bmp":
return "image/bmp";
case "tif":
case "tiff":
return "image/tiff";
case "heic":
return "image/heic";
default:
return fallback;
}
}
async function readJSONSafe(p) {
try {
const raw = await fsp4.readFile(p, "utf-8");
return JSON.parse(raw);
} catch {
return null;
}
}
async function resolveImg2ImgSourceLMStudio(opts) {
const options = {
freshOnly: opts?.freshOnly !== void 0 ? opts.freshOnly : false,
freshSeconds: typeof opts?.freshSeconds === "number" ? opts.freshSeconds : 180,
chatId: typeof opts?.chatId === "string" ? opts.chatId : void 0,
explicitAttachmentSource: opts?.explicitAttachmentSource === true,
attachmentIndex: typeof opts?.attachmentIndex === "number" && opts.attachmentIndex >= 1 ? Math.round(opts.attachmentIndex) : void 0
};
try {
const home = findLMStudioHome();
const convDir = join6(home, "conversations");
if (!existsSync6(convDir)) {
console.error(`[LM] Conversations dir not found: ${convDir}`);
return {
ok: false,
client: "lmstudio",
reason: `Conversations dir not found: ${convDir}`
};
}
let chatId = options.chatId || null;
let chosenConv = null;
if (chatId) {
const p = findConversationFileByChatId(chatId, convDir);
if (p) {
chosenConv = p;
} else {
console.error(`[LM] Provided chatId has no conversation file: ${chatId}.conversation.json under ${convDir}`);
}
}
if (!chosenConv) {
const best = await resolveActiveLMStudioChatId().catch(() => null);
if (!best || !best.ok) {
console.error(`[LM] No conversation files found in ${convDir}`);
return {
ok: false,
client: "lmstudio",
reason: "No conversation files found"
};
}
chosenConv = best.filePath;
chatId = best.chatId;
console.error(
`[LM] Heuristic selected conversation: ${chosenConv} (chatId=${chatId})`
);
}
if (!chatId) {
return {
ok: false,
client: "lmstudio",
reason: "Failed to resolve LM Studio chatId"
};
}
const workingDir = join6(home, "working-directories", chatId);
if (options.explicitAttachmentSource) {
const mediaStatePath = join6(workingDir, "chat_media_state.json");
if (existsSync6(mediaStatePath)) {
console.log(`[LM] Checking chat_media_state.json: ${mediaStatePath}`);
const mediaState = await readJSONSafe(mediaStatePath);
if (mediaState && Array.isArray(mediaState.attachments) && mediaState.attachments.length > 0) {
const sortedByA = [...mediaState.attachments].sort(
(a, b) => (b.a ?? 0) - (a.a ?? 0)
);
const highestA = sortedByA[0]?.n ?? mediaState.attachments.length;
const targetA = options.attachmentIndex ?? highestA;
const selectedAtt = mediaState.attachments.find(
(a) => a.a === targetA
);
if (!selectedAtt) {
const availableNs = mediaState.attachments.map((a) => a.a).filter((n) => typeof n === "number").sort((a, b) => a - b);
return {
ok: false,
client: "lmstudio",
reason: `Requested attachment a${targetA} not found. Available: a${availableNs.join(
", a"
)}`
};
}
const lastAtt = selectedAtt;
let imagePath = null;
if (typeof lastAtt.originAbs === "string" && existsSync6(lastAtt.originAbs)) {
imagePath = lastAtt.originAbs;
} else if (typeof lastAtt.filename === "string") {
const copyPath = join6(workingDir, lastAtt.filename);
if (existsSync6(copyPath)) imagePath = copyPath;
}
if (imagePath) {
try {
const read = await readStableAndDecode(imagePath);
if (read.ok) {
const buffer = read.buffer;
const mimeType = inferMimeFromExt2(imagePath, "image/png");
const fileIdentifier = typeof lastAtt.originAbs === "string" && lastAtt.originAbs.trim() ? lastAtt.originAbs : imagePath;
console.log(
`[LM] Resolved attachment from chat_media_state.json: ${fileIdentifier} (path=${imagePath}, a${targetA})`
);
return {
ok: true,
client: "lmstudio",
buffer,
mimeType,
sourceName: basename4(imagePath),
chatId,
fileIdentifier,
originalPath: imagePath,
originalName: typeof lastAtt.originalName === "string" && lastAtt.originalName ? lastAtt.originalName : void 0
};
} else {
console.error(
`[LM] chat_media_state attachment not decodable (${read.reason}), will try conversation.json`
);
}
} catch (e) {
console.error(
`[LM] Failed to read chat_media_state attachment ${imagePath}: ${e.message}`
);
}
} else {
console.error(
`[LM] chat_media_state.json has attachment but file not found: originAbs=${lastAtt.originAbs}, filename=${lastAtt.filename}`
);
}
}
}
}
console.error(
`[LM] No attachment available. Generator must process conversation.json first and write chat_media_state.json.`
);
return {
ok: false,
client: "lmstudio",
reason: "No attachment in chat_media_state.json or pending file. Wait for Generator to process conversation.json."
};
} catch (e) {
return { ok: false, client: "lmstudio", reason: e?.message || String(e) };
}
}
// src/helpers/visionCapabilityPrimer.ts
import { exec } from "child_process";
import { promisify } from "util";
import path23 from "path";
import os7 from "os";
import fs23 from "fs";
async function getAxios2() {
return (await import("axios")).default;
}
var execAsync = promisify(exec);
function appendPluginLog(line) {
try {
ensureLogsDir();
const logFile3 = path23.join(getLogsDir(), getPluginLogFilename());
fs23.appendFileSync(logFile3, `${localTimestamp()} - ${line}
`);
} catch (e) {
console.error(
`[AgentModel] Failed to append to ${getPluginLogFilename()}:`,
e?.message || String(e)
);
}
}
function normalizeLmApiRoot3(baseUrl) {
const u = String(baseUrl || "").trim();
return u.replace(/\/(api\/v1|v1)\/?$/i, "").replace(/\/+$/, "");
}
function buildLmApiAuthHeaders2(apiKey) {
if (typeof apiKey === "string" && apiKey.trim()) {
return { Authorization: `Bearer ${apiKey.trim()}` };
}
return {};
}
function isLocalLmApiBaseUrl(baseUrl) {
const raw = String(baseUrl || "").trim();
if (!raw) return false;
try {
const host = new URL(raw).hostname.toLowerCase();
return host === "localhost" || host === "127.0.0.1" || host === "::1";
} catch {
return false;
}
}
async function findLmsCli() {
const candidates = [
path23.join(os7.homedir(), ".lmstudio", "bin", "lms"),
"/usr/local/bin/lms",
"/opt/homebrew/bin/lms"
];
for (const candidate of candidates) {
try {
await execAsync(`"${candidate}" -h`);
return candidate;
} catch {
}
}
try {
const { stdout } = await execAsync("which lms");
const lmsPath = stdout.trim();
if (lmsPath) {
await execAsync(`"${lmsPath}" -h`);
return lmsPath;
}
} catch {
}
return null;
}
async function isModelInstalled(lmsCli, modelKey, timeoutMs = 5e3) {
const normalizedKey = modelKey.toLowerCase().trim();
try {
const { stdout } = await execAsync(`"${lmsCli}" ls --json`, {
timeout: timeoutMs,
maxBuffer: 10 * 1024 * 1024
});
let models;
try {
models = JSON.parse(stdout);
} catch (parseErr) {
try {
const { stdout: textOut, stderr: textErr } = await execAsync(
`"${lmsCli}" ls`,
{
timeout: Math.max(1e3, timeoutMs),
maxBuffer: 10 * 1024 * 1024
}
);
const haystack = `${textOut}
${textErr}`.toLowerCase();
if (haystack.includes(normalizedKey)) {
return { installed: true, modelInfo: { modelKey } };
}
return {
installed: false,
error: `Failed to parse lms ls --json output (fallback used): ${parseErr?.message || parseErr}`
};
} catch (fallbackErr) {
return {
installed: false,
error: `Failed to parse lms ls --json output and fallback ls failed: ${parseErr?.message || parseErr} / ${fallbackErr?.message || String(fallbackErr)}`
};
}
}
if (!Array.isArray(models)) {
return {
installed: false,
error: "lms ls --json returned non-array"
};
}
const found = models.find((m) => {
const key = String(m?.modelKey || "").toLowerCase().trim();
const path34 = String(m?.path || "").toLowerCase().trim();
const keyBase = key.split("@")[0]?.trim() || key;
return key === normalizedKey || keyBase === normalizedKey || path34 === normalizedKey;
});
if (found) {
return {
installed: true,
modelInfo: {
modelKey: found.path || found.modelKey,
displayName: found.displayName,
sizeBytes: found.sizeBytes,
vision: found.vision === true
}
};
}
return { installed: false };
} catch (e) {
return {
installed: false,
error: e?.message || String(e)
};
}
}
async function isModelLoaded(lmsCli, identifier, timeoutMs = 5e3) {
const normalizedId = identifier.toLowerCase().trim();
try {
const { stdout } = await execAsync(`"${lmsCli}" ps --json`, {
timeout: timeoutMs
});
let instances;
try {
instances = JSON.parse(stdout);
} catch {
return false;
}
if (!Array.isArray(instances)) {
return false;
}
return instances.some((inst) => {
const instId = String(inst?.identifier || "").toLowerCase().trim();
return instId === normalizedId;
});
} catch {
return false;
}
}
async function checkLmsLoadAmbiguity(lmsCli, modelKey, timeoutMs = 5e3) {
const normalizedKey = modelKey.toLowerCase().trim();
try {
const { stdout } = await execAsync(`"${lmsCli}" ls "${modelKey}" --json`, {
timeout: timeoutMs,
maxBuffer: 10 * 1024 * 1024
});
const models = JSON.parse(stdout);
if (!Array.isArray(models)) return { ok: true };
const matches = models.map((model) => {
const path34 = String(model?.path || "").trim();
if (path34) return path34;
const key = String(model?.modelKey || model?.key || "").trim();
return key.split("@")[0]?.trim() || key;
}).filter(Boolean);
const uniqueMatches = Array.from(new Set(matches));
if (uniqueMatches.length <= 1) return { ok: true };
const exactMatches = uniqueMatches.filter(
(key) => key.toLowerCase().trim() === normalizedKey
);
if (exactMatches.length === 1 && uniqueMatches.every((key) => key.toLowerCase().trim() === normalizedKey)) {
return { ok: true };
}
const listed = uniqueMatches.map((key) => `- ${key}`).join("\n");
const error = `lms load would be ambiguous for '${modelKey}'. Matching models:
${listed}`;
return {
ok: false,
error,
userFacingError: `**Vision Attachment Support:**
The configured primer model \`${modelKey}\` is ambiguous for \`lms load\`.
Matching models:
${listed}
Remove or rename the conflicting model, or configure a model key that \`lms load\` resolves without prompting.`
};
} catch (error) {
console.warn(
"[VisionPrimer] Could not preflight lms load ambiguity:",
error?.message || error
);
return { ok: true };
}
}
async function checkVisionPrimerStatus(config) {
const { modelKey, identifier = "vision-capability-priming" } = config;
console.debug("[VisionPrimer] Quick status check...");
const lmsCli = await findLmsCli();
if (!lmsCli) {
console.warn("[VisionPrimer] lms CLI not found (infrastructure error, silent)");
return {
lmsCli: null,
installed: false,
alreadyLoaded: false,
needsLoad: false,
infrastructureError: true,
error: "lms CLI not found. Is LM Studio installed?"
};
}
console.debug("[VisionPrimer] Found lms CLI:", lmsCli);
const installResult = await isModelInstalled(lmsCli, modelKey, 5e3);
if (installResult.error) {
console.warn("[VisionPrimer] Installation check failed:", installResult.error);
return {
lmsCli,
installed: false,
alreadyLoaded: false,
needsLoad: false,
infrastructureError: true,
error: `Installation check failed: ${installResult.error}`
};
}
if (!installResult.installed) {
const userMsg = `**Vision Attachment Support:**
The vision-capability-priming model \`${modelKey}\` is not installed.
This model enables image attachments in the chat UI. To install it:
1. Open LM Studio
2. Search for \`${modelKey}\`
3. Download the model
Without this model, you can still use text prompts for image generation.`;
console.warn(`[VisionPrimer] Model not installed: ${modelKey}`);
return {
lmsCli,
installed: false,
alreadyLoaded: false,
needsLoad: false,
notInstalled: true,
userFacingError: userMsg,
error: `Model '${modelKey}' is not installed locally.`
};
}
console.debug(`[VisionPrimer] Model installed: ${modelKey}`);
const loaded = await isModelLoaded(lmsCli, identifier, 5e3);
if (loaded) {
console.debug(`[VisionPrimer] Model already loaded with identifier: ${identifier}`);
return {
lmsCli,
installed: true,
alreadyLoaded: true,
needsLoad: false
};
}
console.debug(`[VisionPrimer] Model installed but not loaded, needs load`);
return {
lmsCli,
installed: true,
alreadyLoaded: false,
needsLoad: true
};
}
async function loadVisionPrimerModel(lmsCli, config) {
const startTs = Date.now();
const {
modelKey,
contextLength = 512,
gpuMode = "off",
ttlSeconds = 7200,
identifier = "vision-capability-priming"
} = config;
if (!lmsCli) {
const error = "lms CLI not found. The Vision Primer requires lms to load the attachment primer with the configured identifier.";
console.error("[VisionPrimer]", error);
return {
ok: false,
infrastructureError: true,
error
};
}
const gpuArg = gpuMode === "off" ? "--gpu off" : gpuMode === "max" ? "--gpu max" : `--gpu ${gpuMode}`;
const ambiguity = await checkLmsLoadAmbiguity(lmsCli, modelKey, 5e3);
if (!ambiguity.ok) {
console.error("[VisionPrimer]", ambiguity.error);
return {
ok: false,
loadFailed: true,
userFacingError: ambiguity.userFacingError,
error: ambiguity.error
};
}
const cmd = [
`"${lmsCli}"`,
"load",
`"${modelKey}"`,
`--context-length ${contextLength}`,
gpuArg,
`--ttl ${ttlSeconds}`,
`--identifier "${identifier}"`
].join(" ");
console.debug("[VisionPrimer] Running:", cmd);
try {
const { stdout, stderr } = await execAsync(cmd, {
timeout: 12e4
});
const output = stdout + stderr;
const loadTimeSec = Math.round((Date.now() - startTs) / 1e3 * 100) / 100;
let size;
const rawSizeMatch = output.match(/\(([0-9.]+)\s*(GiB|MiB|KiB|GB|MB|KB)?\)/i);
if (rawSizeMatch) {
const numVal = parseFloat(rawSizeMatch[1]);
const unit = (rawSizeMatch[2] || "GiB").toUpperCase();
let bytes;
if (unit.startsWith("KI")) bytes = numVal * 1024;
else if (unit.startsWith("MI")) bytes = numVal * 1024 * 1024;
else if (unit.startsWith("GI")) bytes = numVal * 1024 * 1024 * 1024;
else if (unit === "KB") bytes = numVal * 1e3;
else if (unit === "MB") bytes = numVal * 1e3 * 1e3;
else if (unit === "GB") bytes = numVal * 1e3 * 1e3 * 1e3;
else bytes = numVal * 1024 * 1024 * 1024;
size = (bytes / 1e3 / 1e3 / 1e3).toFixed(2) + " GB";
}
const nowLoaded = await isModelLoaded(lmsCli, identifier, 5e3);
if (!nowLoaded) {
const error = `lms load completed, but '${identifier}' is not present in lms ps --json.`;
console.error("[VisionPrimer]", error);
return {
ok: false,
loadFailed: true,
userFacingError: `**Vision Attachment Support:**
The vision-capability-priming model \`${modelKey}\` load command completed, but readiness verification failed.
Error: ${error}`,
error
};
}
console.debug(`[VisionPrimer] \u2713 Model loaded in ${loadTimeSec}s`);
if (size) console.debug(`[VisionPrimer] Size: ${size}`);
return {
ok: true,
alreadyLoaded: false,
identifier,
size,
loadTimeSec
};
} catch (e) {
const error = e.stderr || e.message || String(e);
console.debug("[VisionPrimer] Load command failed, checking if model is now loaded anyway...");
const nowLoaded = await isModelLoaded(lmsCli, identifier, 5e3);
if (nowLoaded) {
console.debug("[VisionPrimer] Model is now loaded (concurrent load succeeded), treating as success");
return {
ok: true,
alreadyLoaded: true,
identifier
};
}
const userMsg = `**Vision Attachment Support:**
The vision-capability-priming model \`${modelKey}\` could not be loaded.
Error: ${error}
Please check LM Studio logs for details. Without this model, you can still use text prompts for image generation.`;
console.error("[VisionPrimer] Failed to load model:", error);
return {
ok: false,
loadFailed: true,
userFacingError: userMsg,
error: `Failed to load model: ${error}`
};
}
}
async function primeVisionCapability(config) {
const TOTAL_TIMEOUT_MS = 15e3;
const startTs = Date.now();
const remainingMs = () => Math.max(0, TOTAL_TIMEOUT_MS - (Date.now() - startTs));
const {
modelKey,
contextLength = 512,
gpuMode = "off",
ttlSeconds = 7200,
identifier = "vision-capability-priming"
} = config;
console.debug("[VisionPrimer] Starting vision capability priming...");
console.debug("[VisionPrimer] Config:", {
modelKey,
contextLength,
gpuMode,
ttlSeconds,
identifier
});
const lmsCli = await findLmsCli();
if (!lmsCli) {
console.warn("[VisionPrimer] lms CLI not found (infrastructure error, silent)");
return {
ok: false,
infrastructureError: true,
error: "lms CLI not found. Is LM Studio installed?"
};
}
console.debug("[VisionPrimer] Found lms CLI:", lmsCli);
if (remainingMs() < 1e3) {
console.warn("[VisionPrimer] Timeout before installation check");
return {
ok: false,
infrastructureError: true,
error: "Timeout before installation check"
};
}
const installResult = await isModelInstalled(lmsCli, modelKey, Math.min(5e3, remainingMs()));
if (installResult.error) {
console.warn("[VisionPrimer] Installation check failed:", installResult.error);
return {
ok: false,
infrastructureError: true,
error: `Installation check failed: ${installResult.error}`
};
}
if (!installResult.installed) {
const userMsg = `**Vision Attachment Support:**
The vision-capability-priming model \`${modelKey}\` is not installed.
This model enables image attachments in the chat UI. To install it:
1. Open LM Studio
2. Search for \`${modelKey}\`
3. Download the model
Without this model, you can still use text prompts for image generation.`;
console.warn(`[VisionPrimer] Model not installed: ${modelKey}`);
return {
ok: false,
notInstalled: true,
userFacingError: userMsg,
error: `Model '${modelKey}' is not installed locally.`
};
}
console.debug(`[VisionPrimer] Model installed: ${modelKey}`);
if (remainingMs() < 1e3) {
console.warn("[VisionPrimer] Timeout before loaded check");
return {
ok: false,
infrastructureError: true,
error: "Timeout before loaded check"
};
}
const loaded = await isModelLoaded(lmsCli, identifier, Math.min(5e3, remainingMs()));
if (loaded) {
console.debug(
`[VisionPrimer] Model already loaded with identifier: ${identifier}`
);
return {
ok: true,
alreadyLoaded: true,
identifier
};
}
if (remainingMs() < 2e3) {
console.warn("[VisionPrimer] Insufficient time remaining to load model");
return {
ok: false,
infrastructureError: true,
error: "Insufficient time remaining to load model"
};
}
const gpuArg = gpuMode === "off" ? "--gpu off" : gpuMode === "max" ? "--gpu max" : `--gpu ${gpuMode}`;
const ambiguity = await checkLmsLoadAmbiguity(lmsCli, modelKey, Math.min(5e3, remainingMs()));
if (!ambiguity.ok) {
console.error("[VisionPrimer]", ambiguity.error);
return {
ok: false,
loadFailed: true,
userFacingError: ambiguity.userFacingError,
error: ambiguity.error
};
}
const cmd = [
`"${lmsCli}"`,
"load",
`"${modelKey}"`,
`--context-length ${contextLength}`,
gpuArg,
`--ttl ${ttlSeconds}`,
`--identifier "${identifier}"`
].join(" ");
console.debug("[VisionPrimer] Running:", cmd);
try {
const { stdout, stderr } = await execAsync(cmd, {
timeout: remainingMs()
});
const output = stdout + stderr;
const loadTimeSec = Math.round((Date.now() - startTs) / 1e3 * 100) / 100;
let size;
const rawSizeMatch = output.match(/\(([0-9.]+)\s*(GiB|MiB|KiB|GB|MB|KB)?\)/i);
if (rawSizeMatch) {
const numVal = parseFloat(rawSizeMatch[1]);
const unit = (rawSizeMatch[2] || "GiB").toUpperCase();
let bytes;
if (unit.startsWith("KI")) bytes = numVal * 1024;
else if (unit.startsWith("MI")) bytes = numVal * 1024 * 1024;
else if (unit.startsWith("GI")) bytes = numVal * 1024 * 1024 * 1024;
else if (unit === "KB") bytes = numVal * 1e3;
else if (unit === "MB") bytes = numVal * 1e3 * 1e3;
else if (unit === "GB") bytes = numVal * 1e3 * 1e3 * 1e3;
else bytes = numVal * 1024 * 1024 * 1024;
size = (bytes / 1e3 / 1e3 / 1e3).toFixed(2) + " GB";
}
const nowLoaded = await isModelLoaded(lmsCli, identifier, Math.min(5e3, remainingMs()));
if (!nowLoaded) {
const error = `lms load completed, but '${identifier}' is not present in lms ps --json.`;
console.error("[VisionPrimer]", error);
return {
ok: false,
loadFailed: true,
userFacingError: `**Vision Attachment Support:**
The vision-capability-priming model \`${modelKey}\` load command completed, but readiness verification failed.
Error: ${error}`,
error
};
}
console.debug(`[VisionPrimer] \u2713 Model loaded in ${loadTimeSec}s`);
if (size) console.debug(`[VisionPrimer] Size: ${size}`);
return {
ok: true,
alreadyLoaded: false,
identifier,
size,
loadTimeSec
};
} catch (e) {
const error = e.stderr || e.message || String(e);
const userMsg = `**Vision Attachment Support:**
The vision-capability-priming model \`${modelKey}\` could not be loaded.
Error: ${error}
Please check LM Studio logs for details. Without this model, you can still use text prompts for image generation.`;
console.error("[VisionPrimer] Failed to load model:", error);
return {
ok: false,
loadFailed: true,
userFacingError: userMsg,
error: `Failed to load model: ${error}`
};
}
}
async function injectLastUsedModelIntoNewestChat(config) {
const startTs = Date.now();
try {
const resolved = await resolveActiveLMStudioChatId();
if (!resolved.ok) {
console.debug("[VisionPrimer] Could not resolve active chat:", resolved.reason);
return;
}
const newestFile = path23.basename(resolved.filePath);
const filePath = resolved.filePath;
const raw = await fs23.promises.readFile(filePath, "utf8");
const conversation = JSON.parse(raw);
const isActive = Array.isArray(conversation.plugins) && conversation.plugins.includes(config.pluginId);
if (!isActive) {
console.debug(`[VisionPrimer] Not active in ${newestFile}, skipping`);
return;
}
if (conversation.lastUsedModel) {
console.debug(
`[VisionPrimer] lastUsedModel already exists in ${newestFile}:`,
conversation.lastUsedModel.identifier || conversation.lastUsedModel
);
return;
}
const runtimeIdentifier = config.identifier ?? config.modelKey;
const fields = [];
if (typeof config.contextLength === "number" && config.contextLength > 0) {
fields.push({ key: "llm.load.contextLength", value: config.contextLength });
}
if (typeof config.gpuOffloadRatio === "number") {
fields.push({
key: "llm.load.llama.acceleration.offloadRatio",
value: config.gpuOffloadRatio
});
}
conversation.lastUsedModel = {
indexedModelIdentifier: config.modelKey,
identifier: runtimeIdentifier,
instanceLoadTimeConfig: { fields },
instanceOperationTimeConfig: { fields: [] }
};
await fs23.promises.writeFile(filePath, JSON.stringify(conversation, null, 2), "utf8");
const now = /* @__PURE__ */ new Date();
await fs23.promises.utimes(filePath, now, now);
console.debug(
`[VisionPrimer] \u2713 Injected lastUsedModel (model=${config.modelKey}, id=${runtimeIdentifier}) into ${newestFile} (${Date.now() - startTs}ms)`
);
setTimeout(async () => {
try {
const now2 = /* @__PURE__ */ new Date();
await fs23.promises.utimes(filePath, now2, now2);
} catch {
}
}, 2e3);
} catch (e) {
console.warn("[VisionPrimer] Failed to process newest chat:", e.message || e);
}
}
var _lastWrittenModel = null;
async function updateLastUsedModelForAgentModel(config) {
const { modelKey, instanceId, contextLength, gpuOffloadRatio, pluginId, baseUrl, chatId } = config;
const effectiveInstanceId = instanceId ?? modelKey;
if (typeof baseUrl === "string" && baseUrl.trim()) {
try {
const host = new URL(baseUrl).hostname.toLowerCase();
const isLocal = host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
if (!isLocal) {
console.debug(
`[VisionPrimer] Non-local baseUrl (${host}) \u2014 skipping lastUsedModel update`
);
return { ok: true, alreadyCorrect: true };
}
} catch {
}
}
if (_lastWrittenModel !== null && _lastWrittenModel.modelKey === modelKey && _lastWrittenModel.instanceId === effectiveInstanceId && _lastWrittenModel.contextLength === contextLength) {
console.debug(
`[VisionPrimer] lastUsedModel cache hit \u2014 skipping SSOT write (${modelKey})`
);
return { ok: true, alreadyCorrect: true };
}
const conversationsDir = path23.join(findLMStudioHome(), "conversations");
let targetFile = null;
let filePath;
let resolvedChatId = void 0;
if (chatId) {
const found = findConversationFileByChatId(chatId, conversationsDir);
if (!found) {
return { ok: false, error: `Conversation file for chatId ${chatId} not found` };
}
filePath = found;
targetFile = path23.basename(found);
resolvedChatId = chatId;
console.debug("[VisionPrimer] Using SDK chatId:", chatId);
} else {
const resolved = await resolveActiveLMStudioChatId();
if (!resolved.ok) {
return { ok: false, error: `Could not resolve active chat: ${resolved.reason}` };
}
filePath = resolved.filePath;
targetFile = path23.basename(resolved.filePath);
resolvedChatId = resolved.chatId;
}
console.debug("[VisionPrimer] Updating lastUsedModel to agent model:", {
modelKey,
instanceId: effectiveInstanceId,
contextLength,
targetFile,
chatSource: chatId ? "sdk" : "resolveActiveLMStudioChatId"
});
async function verifyWrittenValues(fp) {
try {
const raw = await fs23.promises.readFile(fp, "utf8");
const data = JSON.parse(raw);
if (data.lastUsedModel?.indexedModelIdentifier !== modelKey) {
console.debug(
`[VisionPrimer] Verify FAILED: indexedModelIdentifier is ${JSON.stringify(data.lastUsedModel?.indexedModelIdentifier)}, expected ${modelKey}`
);
return false;
}
if (data.lastUsedModel?.identifier !== effectiveInstanceId) {
console.debug(
`[VisionPrimer] Verify FAILED: identifier is ${JSON.stringify(data.lastUsedModel?.identifier)}, expected ${effectiveInstanceId}`
);
return false;
}
if (contextLength !== void 0) {
const actualCtx = data.lastUsedModel?.instanceLoadTimeConfig?.fields?.find(
(f) => f.key === "llm.load.contextLength"
)?.value;
if (actualCtx !== contextLength) {
console.debug(
`[VisionPrimer] Verify FAILED: contextLength is ${JSON.stringify(actualCtx)}, expected ${contextLength}`
);
return false;
}
}
return true;
} catch (e) {
console.debug(`[VisionPrimer] Verify read failed:`, e.message || e);
return false;
}
}
async function writeOnce() {
const raw = await fs23.promises.readFile(filePath, "utf8");
const conversation = JSON.parse(raw);
if (pluginId) {
const isActive = Array.isArray(conversation.plugins) && conversation.plugins.includes(pluginId);
if (!isActive) {
console.debug(
`[VisionPrimer] We're not active in chat (${targetFile}), skipping update`
);
throw new Error("Plugin not active in this chat");
}
}
const existingModel = conversation.lastUsedModel;
if (existingModel?.indexedModelIdentifier === modelKey && existingModel?.identifier === effectiveInstanceId) {
const existingCtx = existingModel?.instanceLoadTimeConfig?.fields?.find(
(f) => f.key === "llm.load.contextLength"
)?.value;
if (contextLength === void 0 || existingCtx === contextLength) {
_lastWrittenModel = { modelKey, instanceId: effectiveInstanceId, contextLength };
console.debug(
`[VisionPrimer] lastUsedModel already correct for ${modelKey}, skipping (cache populated)`
);
return true;
}
}
const fields = [];
if (typeof contextLength === "number" && contextLength > 0) {
fields.push({ key: "llm.load.contextLength", value: contextLength });
}
if (typeof gpuOffloadRatio !== void 0 && typeof gpuOffloadRatio === "number") {
fields.push({
key: "llm.load.llama.acceleration.offloadRatio",
value: gpuOffloadRatio
});
}
conversation.lastUsedModel = {
indexedModelIdentifier: modelKey,
identifier: effectiveInstanceId,
instanceLoadTimeConfig: { fields },
instanceOperationTimeConfig: { fields: [] }
};
await fs23.promises.writeFile(
filePath,
JSON.stringify(conversation, null, 2),
"utf8"
);
const now = /* @__PURE__ */ new Date();
await fs23.promises.utimes(filePath, now, now);
return true;
}
try {
await new Promise((resolve) => setTimeout(resolve, 400));
const maxAttempts = 3;
let verified = false;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
await writeOnce();
await new Promise((resolve) => setTimeout(resolve, 100));
const ok = await verifyWrittenValues(filePath);
if (ok) {
verified = true;
break;
}
if (attempt < maxAttempts) {
const backoffMs = 300 * attempt;
console.debug(
`[VisionPrimer] Write not persisted yet (attempt ${attempt}/${maxAttempts}), retrying in ${backoffMs}ms`
);
await new Promise((resolve) => setTimeout(resolve, backoffMs));
}
}
if (!verified) {
try {
const finalRaw = await fs23.promises.readFile(filePath, "utf8");
const finalData = JSON.parse(finalRaw);
console.warn(
`[VisionPrimer] \u2717 Could not verify write after ${maxAttempts} attempts. File has indexedModelIdentifier=${JSON.stringify(finalData.lastUsedModel?.indexedModelIdentifier)}, contextLength=${JSON.stringify(finalData.lastUsedModel?.instanceLoadTimeConfig?.fields?.find((f) => f.key === "llm.load.contextLength")?.value)}. Expected ${modelKey} / ctx=${contextLength}`
);
} catch {
console.warn(
`[VisionPrimer] \u2717 Could not verify write after ${maxAttempts} attempts and cannot read final state`
);
}
return { ok: false, error: `Write verification failed after ${maxAttempts} attempts`, chatId: resolvedChatId };
}
_lastWrittenModel = { modelKey, instanceId: effectiveInstanceId, contextLength };
console.debug(
`[VisionPrimer] \u2713 Verified lastUsedModel update to agent model: ${modelKey} (ctx=${contextLength ?? "default"}) in ${targetFile}`
);
setTimeout(async () => {
try {
const now2 = /* @__PURE__ */ new Date();
await fs23.promises.utimes(filePath, now2, now2);
console.debug(`[VisionPrimer] \u2713 Second touch for agent model update`);
} catch {
}
}, 1500);
return { ok: true, chatId: resolvedChatId };
} catch (e) {
if (e.message === "Plugin not active in this chat") {
return { ok: false, error: e.message, chatId: resolvedChatId };
}
console.warn(
"[VisionPrimer] Failed to update lastUsedModel:",
e.message || e
);
return { ok: false, error: e.message || String(e), chatId: resolvedChatId };
}
}
async function unloadVisionPrimer(identifier = "vision-capability-priming", opts) {
if (opts?.baseUrl) {
const apiRoot = normalizeLmApiRoot3(opts.baseUrl);
const unloadUrl = `${apiRoot}/api/v1/models/unload`;
try {
const axios2 = await getAxios2();
await axios2.post(
unloadUrl,
{ instance_id: identifier },
{
timeout: 3e4,
headers: {
"Content-Type": "application/json",
...buildLmApiAuthHeaders2(opts.apiKey)
}
}
);
console.debug(`[VisionPrimer] \u2713 Unloaded model via API: ${identifier}`);
return true;
} catch (e) {
const resp = e?.response;
const respText = resp?.data ? typeof resp.data === "string" ? resp.data : JSON.stringify(resp.data) : void 0;
console.warn(
"[VisionPrimer] Failed to unload via API:",
respText || e?.message || e
);
return false;
}
}
const lmsCli = await findLmsCli();
if (!lmsCli) return false;
try {
await execAsync(`"${lmsCli}" unload "${identifier}"`);
console.debug(`[VisionPrimer] \u2713 Unloaded model: ${identifier}`);
return true;
} catch (e) {
console.warn("[VisionPrimer] Failed to unload:", e.message || e);
return false;
}
}
async function ensureAgentModelLoaded(config) {
const startTs = Date.now();
const { modelKey } = config;
appendPluginLog(
`[AgentModel] ensureAgentModelLoaded start modelKey=${String(
modelKey
)} baseUrl=${String(config.baseUrl || "").trim() || "(missing)"}`
);
console.log("[AgentModel] Ensuring agent model is loaded...");
console.log("[AgentModel] Model:", modelKey);
const formatVisionModelsTable = (models) => {
const rows = models.map((m) => {
const id = String(m?.key || m?.id || "?");
const name = String(m?.display_name || id);
const params = String(m?.params_string || "?");
const size = m?.size_bytes ? (Number(m.size_bytes) / 1e3 / 1e3 / 1e3).toFixed(2) + " GB" : "?";
const caps2 = m?.capabilities;
const hasVision = caps2?.vision === true;
const hasToolUse = caps2?.trained_for_tool_use === true;
const visionMark = hasVision ? "\u2713" : "";
const toolsMark = hasToolUse ? "\u2713" : "";
const PRIMER_INSTANCE_ID = "vision-capability-priming";
const loadedAsId = Array.isArray(m?.loaded_instances) ? m.loaded_instances.some((inst) => {
const instId = typeof inst === "string" ? inst : typeof inst?.id === "string" ? inst.id : void 0;
return typeof instId === "string" && instId === id;
}) : false;
const loadedAsPrimer = Array.isArray(m?.loaded_instances) ? m.loaded_instances.some((inst) => {
const instId = typeof inst === "string" ? inst : typeof inst?.id === "string" ? inst.id : void 0;
return typeof instId === "string" && instId === PRIMER_INSTANCE_ID;
}) : false;
const status = loadedAsId ? "\u2713" : loadedAsPrimer ? "primer" : "";
return `| ${id} | ${name} | ${params} | ${size} | ${visionMark} | ${toolsMark} | ${status} |`;
});
return `
**Vision Models:**
| ID | Name | Params | Size | Vision | Tools | Loaded |
|---|---|---|---|---|---|---|
${rows.join(
"\n"
)}
`;
};
if (!config.baseUrl) {
return {
ok: false,
error: "Configuration error: Missing baseUrl for Model API check."
};
}
const requestedKeyRaw = String(modelKey || "").trim();
const requestedKey = requestedKeyRaw.toLowerCase();
if (!requestedKeyRaw) {
return { ok: false, error: "Configuration error: Empty model key." };
}
if (requestedKey === "vision-capability-priming") {
return {
ok: false,
error: "Invalid agent model: 'vision-capability-priming' is an infrastructure primer model and must not be used for chat orchestration."
};
}
const apiRoot = normalizeLmApiRoot3(config.baseUrl);
const modelsUrl = `${apiRoot}/api/v1/models`;
const loadUrl = `${apiRoot}/api/v1/models/load`;
const headers = {};
if (typeof config.apiKey === "string" && config.apiKey.trim()) {
headers.Authorization = `Bearer ${config.apiKey.trim()}`;
}
let foundModel;
let visionModels = [];
try {
console.debug(`[AgentModel] Checking status via ${modelsUrl}`);
const response = await (await getAxios2()).get(modelsUrl, {
timeout: 5e3,
headers
});
const data = response.data;
const models = Array.isArray(data) ? data : Array.isArray(data?.models) ? data.models : Array.isArray(data?.data) ? data.data : [];
if (data?.error && models.length === 0) {
throw new Error(String(data.error));
}
visionModels = models.filter((m) => m?.capabilities?.vision === true);
foundModel = models.find((m) => {
const key = String(m?.key || "").trim();
return key && key.toLowerCase() === requestedKey;
});
if (foundModel) {
const li = Array.isArray(foundModel?.loaded_instances) ? foundModel.loaded_instances : [];
const ids = li.map((inst) => {
if (typeof inst === "string") return inst;
if (inst && typeof inst.id === "string") return inst.id;
return void 0;
}).filter((v) => typeof v === "string").slice(0, 5).join(", ");
appendPluginLog(
`[AgentModel] status key=${requestedKeyRaw} found=true loaded_instances=${li.length}${ids ? ` ids=[${ids}]` : ""}`
);
} else {
appendPluginLog(`[AgentModel] status key=${requestedKeyRaw} found=false`);
}
} catch (e) {
const resp = e?.response;
const respText = resp?.data ? typeof resp.data === "string" ? resp.data : JSON.stringify(resp.data) : void 0;
const msg = respText || e?.message || String(e);
appendPluginLog(
`[AgentModel] status query failed url=${modelsUrl} error=${msg}`
);
const standardModelsUrl = `${apiRoot}/v1/models`;
appendPluginLog(
`[AgentModel] falling back to standard models endpoint: ${standardModelsUrl}`
);
try {
const fallbackResp = await (await getAxios2()).get(standardModelsUrl, {
timeout: 5e3,
headers
});
const fallbackData = fallbackResp.data;
const fallbackModels = Array.isArray(fallbackData) ? fallbackData : Array.isArray(fallbackData?.models) ? fallbackData.models : Array.isArray(fallbackData?.data) ? fallbackData.data : [];
const foundInFallback = fallbackModels.find((m) => {
const id = String(m?.id || m?.key || "").trim().toLowerCase();
if (!id) return false;
return id === requestedKey || id.endsWith("/" + requestedKey);
});
if (!foundInFallback) {
appendPluginLog(
`[AgentModel] model not found in standard endpoint: ${requestedKeyRaw}`
);
return {
ok: false,
error: `Model '${requestedKeyRaw}' not found on server (tried ${modelsUrl} and ${standardModelsUrl}).`
};
}
if (!isKnownModel(requestedKeyRaw)) {
appendPluginLog(
`[AgentModel] model not in capabilities.ts, cannot verify vision support: ${requestedKeyRaw}`
);
return {
ok: false,
error: `Model '${requestedKeyRaw}' is not listed in the plugin's capabilities registry. Add it to capabilities.ts to enable non-LM-Studio server support.`
};
}
const fallbackCaps = detectCapabilities(requestedKeyRaw);
if (!fallbackCaps.supportsVision) {
appendPluginLog(
`[AgentModel] model not vision-capable per capabilities.ts: ${requestedKeyRaw}`
);
return {
ok: false,
error: `Model '${requestedKeyRaw}' is not vision-capable (per capabilities.ts).`
};
}
appendPluginLog(
`[AgentModel] fallback ok (capabilities.ts vision=true): ${requestedKeyRaw}`
);
return {
ok: true,
alreadyLoaded: true,
identifier: requestedKeyRaw,
loadedInstanceId: requestedKeyRaw
};
} catch (fallbackErr) {
const fallbackMsg = fallbackErr?.message || String(fallbackErr);
appendPluginLog(
`[AgentModel] standard fallback also failed: ${fallbackMsg}`
);
return {
ok: false,
error: `Could not query model list via API (${modelsUrl}): ${msg}`
};
}
}
const modelTable = visionModels.length > 0 ? formatVisionModelsTable(visionModels) : "\n\n(No vision-capable models found with capabilities { vision: true }.)";
if (!foundModel) {
appendPluginLog(`[AgentModel] model not found: ${requestedKeyRaw}`);
return {
ok: false,
error: `Model '${requestedKeyRaw}' not found on server.${modelTable}`
};
}
const caps = foundModel?.capabilities;
const isSuitable = caps?.vision === true;
if (!isSuitable) {
appendPluginLog(
`[AgentModel] model not suitable (no vision): ${requestedKeyRaw}`
);
return {
ok: false,
error: `Model '${requestedKeyRaw}' is not suitable (requires vision).${modelTable}`
};
}
const loadedInstances = Array.isArray(foundModel?.loaded_instances) ? foundModel.loaded_instances : [];
const getInstanceId = (inst) => {
if (typeof inst === "string") return inst;
if (inst && typeof inst.id === "string") return inst.id;
return void 0;
};
const getInstanceContextLength = (inst) => {
if (!inst || typeof inst === "string") return void 0;
const cfg = inst?.config;
const cfgLen = typeof cfg?.context_length === "number" ? cfg.context_length : typeof cfg?.contextLength === "number" ? cfg.contextLength : void 0;
if (typeof cfgLen === "number" && Number.isFinite(cfgLen)) return cfgLen;
const v = typeof inst.context_length === "number" ? inst.context_length : typeof inst.contextLength === "number" ? inst.contextLength : void 0;
return typeof v === "number" && Number.isFinite(v) ? v : void 0;
};
const loadedInstance = loadedInstances.find((inst) => {
const instId = getInstanceId(inst);
return typeof instId === "string" && instId.toLowerCase() === requestedKey;
});
const fallbackLoadedInstance = loadedInstance ?? (loadedInstances.length > 0 ? loadedInstances[0] : void 0);
const alreadyLoaded = loadedInstances.length > 0;
if (alreadyLoaded) {
if (!loadedInstance && loadedInstances.length > 0) {
const ids = loadedInstances.map((inst) => getInstanceId(inst)).filter((v) => typeof v === "string").slice(0, 5).join(", ");
appendPluginLog(
`[AgentModel] alreadyLoaded=true via loaded_instances.length (${loadedInstances.length}) but no exact id match. requestedKey=${requestedKeyRaw} ids=[${ids}]`
);
}
console.log(
`[AgentModel] Model already loaded (via API): ${requestedKeyRaw}`
);
appendPluginLog(`[AgentModel] already loaded: ${requestedKeyRaw}`);
return {
ok: true,
alreadyLoaded: true,
identifier: requestedKeyRaw,
loadedInstanceId: getInstanceId(fallbackLoadedInstance) ?? requestedKeyRaw,
loadedInstanceContextLength: getInstanceContextLength(
fallbackLoadedInstance
),
maxContextLength: typeof foundModel?.max_context_length === "number" ? foundModel.max_context_length : typeof foundModel?.maxContextLength === "number" ? foundModel.maxContextLength : void 0,
size: foundModel?.size_bytes ? (Number(foundModel.size_bytes) / 1e3 / 1e3 / 1e3).toFixed(2) + " GB" : void 0
};
}
console.log("[AgentModel] Loading model via API:", requestedKeyRaw);
appendPluginLog(`[AgentModel] loading via API: ${requestedKeyRaw}`);
try {
const loadResp = await (await getAxios2()).post(
loadUrl,
{
model: requestedKeyRaw,
echo_load_config: true
},
{
timeout: 3e5,
headers: {
"Content-Type": "application/json",
...headers
}
}
);
const loadData = loadResp.data;
const loadTimeSecApi = typeof loadData?.load_time_seconds === "number" ? loadData.load_time_seconds : void 0;
const loadTimeSecLocal = Math.round((Date.now() - startTs) / 1e3 * 100) / 100;
const loadTimeSec = loadTimeSecApi ?? loadTimeSecLocal;
let loadedInstanceId;
let loadedInstanceContextLength;
let maxContextLength;
try {
const response2 = await (await getAxios2()).get(modelsUrl, {
timeout: 5e3,
headers
});
const data2 = response2.data;
const models2 = Array.isArray(data2) ? data2 : Array.isArray(data2?.models) ? data2.models : Array.isArray(data2?.data) ? data2.data : [];
const foundModel2 = models2.find((m) => {
const key = String(m?.key || "").trim();
return key && key.toLowerCase() === requestedKey;
});
const loadedInstances2 = Array.isArray(foundModel2?.loaded_instances) ? foundModel2.loaded_instances : [];
const loadedInstance2 = loadedInstances2.find((inst) => {
const instId = getInstanceId(inst);
return typeof instId === "string" && instId.toLowerCase() === requestedKey;
});
loadedInstanceId = getInstanceId(loadedInstance2);
loadedInstanceContextLength = getInstanceContextLength(loadedInstance2);
maxContextLength = typeof foundModel2?.max_context_length === "number" ? foundModel2.max_context_length : typeof foundModel2?.maxContextLength === "number" ? foundModel2.maxContextLength : void 0;
} catch (e) {
console.debug(
"[AgentModel] Post-load model status re-check failed (skipping context warning)."
);
}
return {
ok: true,
alreadyLoaded: false,
identifier: requestedKeyRaw,
loadedInstanceId: loadedInstanceId ?? requestedKeyRaw,
loadedInstanceContextLength,
maxContextLength,
size: foundModel?.size_bytes ? (Number(foundModel.size_bytes) / 1e3 / 1e3 / 1e3).toFixed(2) + " GB" : void 0,
loadTimeSec
};
} catch (e) {
const resp = e?.response;
const respText = resp?.data ? typeof resp.data === "string" ? resp.data : JSON.stringify(resp.data) : void 0;
const msg = respText || e?.message || String(e);
const UNSPECIFIC = "Error: Error loading model.";
const FRIENDLY = "Model load failed. Please open LM Studio Debug logs; the model configuration (e.g. context length / GPU offload) may not match your Model Loading Guardrails settings.";
const safeMsg = typeof msg === "string" && msg.includes(UNSPECIFIC) ? msg.split(UNSPECIFIC).join(FRIENDLY) : msg;
appendPluginLog(
`[AgentModel] load failed: ${requestedKeyRaw} error=${safeMsg}`
);
return {
ok: false,
error: `Failed to load model via API: ${safeMsg}`
};
}
}
// src/media-promotion-core/promotion.ts
import fs24 from "fs";
import path24 from "path";
async function pathExists3(p) {
try {
await fs24.promises.access(p, fs24.constants.F_OK);
return true;
} catch {
return false;
}
}
async function recordGeneratedVariants(chatWd, state, discoveredOriginals, previewOpts, turnIdByOriginAbs, debug = false) {
if (!discoveredOriginals.length) return { changed: false };
const prepared = [];
for (const src of discoveredOriginals) {
const abs = src.startsWith("file://") ? fileUriToPath(src) : path24.isAbsolute(src) ? src : path24.join(chatWd, src);
if (debug)
console.info(
`[recordGeneratedVariants] Processing src: ${src} \u2192 abs: ${abs}`
);
if (!await pathExists3(abs)) {
if (debug)
console.warn(
`[recordGeneratedVariants] Original not found, skipping: ${abs}`
);
continue;
}
if (!isAllowedOriginalExt(abs)) {
if (debug)
console.warn(
`[recordGeneratedVariants] Extension not allowed, skipping: ${abs}`
);
continue;
}
const base = path24.basename(abs);
if (debug) console.info(`[recordGeneratedVariants] basename: ${base}`);
const vName = base;
const vAbs = path24.join(chatWd, vName);
if (!await pathExists3(vAbs)) {
if (debug)
console.warn(
`[recordGeneratedVariants] Original missing in chatWd, skipping: ${vAbs}`
);
continue;
}
const m = /^generated-image-(.+)-v(\d+)\.\w+$/i.exec(base);
const ts = m ? m[1] : "unknown";
const vNum = parseInt(m ? m[2] : "1", 10) || 1;
if (debug)
console.info(`[recordGeneratedVariants] Parsed: ts=${ts}, vNum=${vNum}`);
const previewCandidates = [`preview-generated-image-${ts}-v${vNum}.jpg`];
let foundPreview = null;
for (const cand of previewCandidates) {
const pAbs = path24.join(chatWd, cand);
if (debug)
console.info(
`[recordGeneratedVariants] Looking for preview in chatWd: ${pAbs}`
);
if (await pathExists3(pAbs)) {
foundPreview = cand;
break;
}
}
if (foundPreview) {
const maybeTurnId = (() => {
try {
const key = path24.resolve(abs);
const tid = turnIdByOriginAbs ? turnIdByOriginAbs[key] : void 0;
return typeof tid === "number" && Number.isFinite(tid) ? tid : void 0;
} catch {
return void 0;
}
})();
prepared.push({
filename: vName,
preview: foundPreview,
v: vNum,
ts,
turnId: maybeTurnId
});
} else if (debug) {
console.warn(
`[recordGeneratedVariants] Preview not found in chatWd, skipping variant v${vNum}`
);
}
}
if (!prepared.length) return { changed: false };
const toAppend = prepared.map((r) => ({
filename: r.filename,
preview: r.preview,
turnId: r.turnId,
v: r.v
// Use the v-number parsed from filename for stable identity
}));
const result = appendVariants(state, toAppend);
if (result.changed) {
state.lastEvent = { type: "variants", at: localTimestamp() };
if (debug)
console.info(
"Recorded variants (imported from SSOT):",
result.records.map((x) => `v${x.v}: ${x.filename}`).join(", ")
);
await writeStateAtomic(chatWd, state);
}
return { changed: result.changed };
}
function buildPromotionItems(chatWd, state, {
labels = true,
onlyAttachmentNs,
onlyVariantVs,
onlyImageIs
} = {}) {
const items = [];
const maxAttachments = getAttachmentWindowSize();
const attachments = Array.isArray(state.attachments) ? state.attachments : [];
const sortedAttachments = [...attachments].sort(
(a, b) => (a.a ?? 0) - (b.a ?? 0)
);
const attachmentCap = Math.max(0, Math.floor(maxAttachments));
let cappedAttachments = attachmentCap > 0 ? sortedAttachments.slice(-attachmentCap) : [];
if (onlyAttachmentNs !== void 0) {
const allowedNs = new Set(onlyAttachmentNs);
cappedAttachments = cappedAttachments.filter((a) => allowedNs.has(a.a ?? 0));
}
for (const a of cappedAttachments) {
if (!a) continue;
const stableA = typeof a.a === "number" ? a.a : 0;
const abs = typeof a.originAbs === "string" && String(a.originAbs) ? String(a.originAbs) : "";
const pRel = typeof a.preview === "string" && String(a.preview) ? String(a.preview) : "";
const pAbs = pRel ? path24.join(chatWd, pRel) : "";
if (!abs) {
throw new Error(
`Attachment a${stableA} is missing originAbs (origin=${String(
a.origin
)})`
);
}
if (!pAbs) {
throw new Error(
`Attachment a${stableA} is missing preview (origin=${String(
a.origin
)}, originAbs=${String(a.originAbs)})`
);
}
if (labels && (!(a.originalName && typeof a.originalName === "string") || !String(a.originalName).trim())) {
throw new Error(
`Attachment a${stableA} is missing originalName (filename=${String(
a.filename
)}, origin=${String(a.origin)}, originAbs=${String(
a.originAbs
)})`
);
}
const label = labels ? `Attachment [a${stableA}] ${String(a.originalName)}` : void 0;
items.push({
abs,
previewAbs: pAbs,
label
});
}
const maxEverythingElse = getEverythingElseWindowSize();
const pool = [];
const variants = Array.isArray(state.variants) ? state.variants : [];
for (const v of variants) {
if (v.kind === "tool_result") continue;
if (!v.preview) continue;
pool.push({
kind: "variant",
key: `v${v.v}`,
index: v.v,
createdAt: v.createdAt ?? "",
filename: v.filename,
preview: v.preview
});
}
const images = Array.isArray(state.images) ? state.images : [];
for (const img of images) {
if (!img.preview) continue;
pool.push({
kind: "image",
key: `i${img.i}`,
index: img.i,
createdAt: img.createdAt ?? "",
filename: img.filename,
preview: img.preview
});
}
pool.sort((a, b) => {
const cmp = a.createdAt.localeCompare(b.createdAt);
if (cmp !== 0) return cmp;
if (a.kind !== b.kind) return a.kind === "variant" ? -1 : 1;
return a.index - b.index;
});
const everythingElseCap = Math.max(0, Math.floor(maxEverythingElse));
let windowItems = everythingElseCap > 0 ? pool.slice(-everythingElseCap) : [];
if (onlyVariantVs !== void 0 || onlyImageIs !== void 0) {
const allowedVs = new Set(onlyVariantVs ?? []);
const allowedIs = new Set(onlyImageIs ?? []);
windowItems = windowItems.filter((item) => {
if (item.kind === "variant") {
return onlyVariantVs === void 0 ? true : allowedVs.has(item.index);
}
return onlyImageIs === void 0 ? true : allowedIs.has(item.index);
});
}
for (const item of windowItems) {
const abs = path24.join(chatWd, item.filename);
const pAbs = path24.join(chatWd, item.preview);
const label = labels ? item.kind === "variant" ? `Variant [v${item.index}]` : `Image [i${item.index}]` : void 0;
items.push({
abs,
previewAbs: pAbs,
label
});
}
return items;
}
function getPromotableAttachmentNs(state) {
const maxAttachments = getAttachmentWindowSize();
const attachments = Array.isArray(state.attachments) ? state.attachments : [];
const sortedAttachments = [...attachments].sort(
(a, b) => (a.a ?? 0) - (b.a ?? 0)
);
const cap = Math.max(0, Math.floor(maxAttachments));
const cappedAttachments = cap > 0 ? sortedAttachments.slice(-cap) : [];
const ns = cappedAttachments.map((a) => typeof a.a === "number" ? a.a : 0).filter((n) => n > 0);
ns.sort((a, b) => a - b);
return ns;
}
function shouldPromoteAttachments(state) {
const currentNs = getPromotableAttachmentNs(state);
const lastNs = Array.isArray(state.lastPromotedAttachmentAs) ? [...state.lastPromotedAttachmentAs].sort((a, b) => a - b) : [];
if (currentNs.length !== lastNs.length) return true;
for (let i = 0; i < currentNs.length; i++) {
if (currentNs[i] !== lastNs[i]) return true;
}
return false;
}
function getPromotableEverythingElse(state) {
const maxEverythingElse = getEverythingElseWindowSize();
const pool = [];
const variants = Array.isArray(state.variants) ? state.variants : [];
for (const v of variants) {
if (v.kind === "tool_result") continue;
if (!v.preview) continue;
pool.push({
kind: "variant",
index: v.v,
createdAt: v.createdAt ?? ""
});
}
const images = Array.isArray(state.images) ? state.images : [];
for (const img of images) {
if (!img.preview) continue;
pool.push({
kind: "image",
index: img.i,
createdAt: img.createdAt ?? ""
});
}
pool.sort((a, b) => {
const cmp = a.createdAt.localeCompare(b.createdAt);
if (cmp !== 0) return cmp;
if (a.kind !== b.kind) return a.kind === "variant" ? -1 : 1;
return a.index - b.index;
});
const cap = Math.max(0, Math.floor(maxEverythingElse));
const windowItems = cap > 0 ? pool.slice(-cap) : [];
const variantVs = windowItems.filter((x) => x.kind === "variant").map((x) => x.index).sort((a, b) => a - b);
const imageIs = windowItems.filter((x) => x.kind === "image").map((x) => x.index).sort((a, b) => a - b);
return { variantVs, imageIs };
}
function getPromotableVariantVs(state) {
return getPromotableEverythingElse(state).variantVs;
}
function getPromotableImageIs(state) {
return getPromotableEverythingElse(state).imageIs;
}
function shouldPromoteEverythingElseIdempotent(state) {
const { variantVs, imageIs } = getPromotableEverythingElse(state);
const lastVs = Array.isArray(state.lastPromotedVariantVs) ? [...state.lastPromotedVariantVs].sort((a, b) => a - b) : [];
const lastIs = Array.isArray(state.lastPromotedImageIs) ? [...state.lastPromotedImageIs].sort((a, b) => a - b) : [];
if (variantVs.length !== lastVs.length) return true;
for (let i = 0; i < variantVs.length; i++) {
if (variantVs[i] !== lastVs[i]) return true;
}
if (imageIs.length !== lastIs.length) return true;
for (let i = 0; i < imageIs.length; i++) {
if (imageIs[i] !== lastIs[i]) return true;
}
return false;
}
function shouldPromoteVariantsIdempotent(state) {
return shouldPromoteEverythingElseIdempotent(state);
}
function fileUriToPath(uri) {
const p = decodeURIComponent(uri.replace(/^file:\/\//i, ""));
return p.startsWith("/") ? p : "/" + p;
}
// src/services/schemas.ts
import path25 from "node:path";
import { z } from "zod";
var TOOL_MIN_RENDER_DIM = drawthingsLimits.min;
var TOOL_MAX_WIDTH = drawthingsLimits.maxWidth;
var TOOL_MAX_HEIGHT = drawthingsLimits.maxHeight;
var TOOL_MAX_PREVIEW_W = drawthingsLimits.maxWidth;
var ZOOM_TOOL_MAX_DIM = 2048;
function validateImageGenerationParams(params) {
const errors = [];
if (params.prompt !== void 0 && typeof params.prompt !== "string") {
errors.push("prompt must be a string");
}
if (params.negative_prompt !== void 0 && typeof params.negative_prompt !== "string") {
errors.push("negative_prompt must be a string");
}
if (params.width !== void 0 && (!Number.isInteger(params.width) || params.width <= 0)) {
errors.push("width must be a positive integer");
}
if (params.height !== void 0 && (!Number.isInteger(params.height) || params.height <= 0)) {
errors.push("height must be a positive integer");
}
if (params.steps !== void 0 && (!Number.isInteger(params.steps) || params.steps <= 0)) {
errors.push("steps must be a positive integer");
}
if (params.seed !== void 0 && !Number.isInteger(params.seed)) {
errors.push("seed must be an integer");
}
if (params.guidance_scale !== void 0 && (typeof params.guidance_scale !== "number" || params.guidance_scale < 0)) {
errors.push("guidance_scale must be a number >= 0");
}
if (params.model !== void 0 && typeof params.model !== "string") {
errors.push("model must be a string");
}
if (params.sampler !== void 0 && typeof params.sampler !== "string" && typeof params.sampler !== "number") {
errors.push("sampler must be a string or number");
}
if (params.random_string !== void 0 && typeof params.random_string !== "string") {
errors.push("random_string must be a string");
}
return { valid: errors.length === 0, errors };
}
function normalizeQualityToInt(q, def) {
let n = typeof q === "string" ? parseFloat(q) : typeof q === "number" ? q : def;
if (!Number.isFinite(n)) n = def;
if (n > 0 && n <= 1) n = n * 100;
n = Math.round(n);
if (n < 1) n = 1;
if (n > 100) n = 100;
return n;
}
function clampNumber(n, min, max) {
return Math.min(max, Math.max(min, n));
}
function formatZodError(err) {
return err.issues.map((i) => {
const path34 = i.path && i.path.length ? i.path.join(".") : "(root)";
return `${path34}: ${i.message}`;
}).join("; ");
}
var GenerateToolParamsSchemaBase = z.object({
prompt: z.string().optional(),
negative_prompt: z.string().optional(),
width: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM, `width must be >= ${TOOL_MIN_RENDER_DIM}`).max(TOOL_MAX_WIDTH, `width must be <= ${TOOL_MAX_WIDTH}`).optional(),
height: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM, `height must be >= ${TOOL_MIN_RENDER_DIM}`).max(TOOL_MAX_HEIGHT, `height must be <= ${TOOL_MAX_HEIGHT}`).optional(),
steps: z.coerce.number().int().min(1, "steps must be >= 1").max(50, "steps must be <= 50").optional(),
seed: z.coerce.number().int().optional(),
guidance_scale: z.coerce.number().min(0, "guidance_scale must be >= 0").max(50, "guidance_scale must be <= 50").optional(),
model: z.string().optional(),
sampler: z.union([z.string(), z.number()]).optional(),
numFrames: z.coerce.number().int().min(1, "numFrames must be >= 1").max(641, "numFrames must be <= 641").optional(),
random_string: z.string().optional(),
// preview controls (validation only; defaults applied by caller)
previewFormat: z.enum(["jpeg", "webp"], {
errorMap: () => ({ message: "previewFormat must be 'jpeg' or 'webp'" })
}).optional(),
previewMaxWidth: z.coerce.number().int().min(128).max(TOOL_MAX_PREVIEW_W).optional(),
previewMinWidth: z.coerce.number().int().min(128).max(TOOL_MAX_PREVIEW_W).optional(),
previewMaxBytes: z.coerce.number().int().min(2e3).max(2e5).optional(),
previewQuality: z.union([z.coerce.number(), z.string()]).transform((v) => normalizeQualityToInt(v, NaN)).optional(),
previewMinQuality: z.union([z.coerce.number(), z.string()]).transform((v) => normalizeQualityToInt(v, NaN)).optional(),
previewQualityStep: z.coerce.number().int().min(1).max(20).optional(),
previewScaleStep: z.coerce.number().min(0.5).max(0.98).optional(),
previewInChat: z.coerce.boolean().optional(),
alt: z.string().max(120).optional(),
// saving
saveOriginal: z.coerce.boolean().optional(),
saveDir: z.string().optional()
}).passthrough();
var GenerateToolParamsSchema = GenerateToolParamsSchemaBase.superRefine((d, ctx) => {
if (d.previewMinWidth !== void 0 && d.previewMaxWidth !== void 0 && d.previewMinWidth > d.previewMaxWidth) {
ctx.addIssue({
code: "custom",
path: ["previewMinWidth"],
message: "previewMinWidth must be <= previewMaxWidth"
});
}
if (d.previewMinQuality !== void 0 && d.previewQuality !== void 0 && d.previewMinQuality > d.previewQuality) {
ctx.addIssue({
code: "custom",
path: ["previewMinQuality"],
message: "previewMinQuality must be <= previewQuality"
});
}
});
var multiIndexSchema = z.union([
z.string().transform(
(s) => s.split(/[\s,]+/).map((x) => parseInt(x.trim(), 10)).filter((n) => Number.isInteger(n) && n >= 1)
),
z.coerce.number().int().min(1).transform((n) => [n]),
z.array(z.coerce.number().int().min(1))
]).optional();
function normalizeSourceToken(raw) {
let s = String(raw ?? "").trim();
if (!s) return "";
s = s.replace(/^[\[{(]+/, "").replace(/[\]})]+$/, "");
s = s.replace(/^['"`]+|['"`]+$/g, "");
s = s.replace(/[;:.!?]+$/, "");
s = s.trim();
if (/^a$/i.test(s)) return "a1";
if (/^v$/i.test(s)) return "v1";
if (/^p$/i.test(s)) return "p1";
if (/^i$/i.test(s)) return "i1";
return s;
}
var SourceNotation = z.preprocess(
(v) => typeof v === "string" ? normalizeSourceToken(v) : v,
z.string().trim().regex(
/^([avpi]|[avpi]?[1-9]\d*)$/i,
"Source notation: 'a1', 'v2', 'p1', 'i3', or digit when unambiguous"
)
);
function isSourcePathToken(s) {
return s.length > 0 && (path25.isAbsolute(s) || s === path25.basename(s));
}
var SourcePathReference = z.string().trim().refine(isSourcePathToken, "Source path must be an absolute path or a filename without directory separators");
var SourceNotationOrPath = z.union([SourceNotation, SourcePathReference]);
var SourceNotationList = z.union([
// String form: split by comma/space and validate each part
z.string().transform(
(s) => s.split(/[\s,]+/).map((x) => normalizeSourceToken(x)).filter((x) => x.length > 0)
),
// Array form: validate each element
z.array(SourceNotationOrPath)
]).refine(
(arr) => arr.every((x) => /^([avpi]|[avpi]?[1-9]\d*)$/i.test(String(x)) || isSourcePathToken(String(x))),
"moodboard contains invalid source notation(s)"
);
var GenerateToolParamsShapeMinimal = {
prompt: z.string().optional().describe(
"Image description (mode: 'text2image') OR description of desired changes (mode: 'image2image')."
),
width: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(TOOL_MAX_WIDTH).optional().describe(`Width in pixels (max ${TOOL_MAX_WIDTH}). Has sensible default.`),
height: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(TOOL_MAX_HEIGHT).optional().describe(`Height in pixels (max ${TOOL_MAX_HEIGHT}). Has sensible default.`),
imageFormat: z.enum(["square", "landscape", "portrait", "16:9"]).optional().describe("Aspect ratio shorthand. Override if context suggests. '16:9' yields 1024\xD7576 (video-optimized)."),
// model preset selection — default 'auto' uses built-in settings
model: z.string().optional().describe("Model: 'auto' (default) picks the best model for the mode; otherwise a name from the list of installed models, a model name or a file name."),
// number of images to generate in one call
variants: z.coerce.number().int().min(1).max(4).optional().describe("Number of images (1-4). Default is 1."),
// number of video frames
numFrames: z.coerce.number().int().min(1, "numFrames must be >= 1").max(641, "numFrames must be <= 641").optional().describe("Number of video frames. Must be a multiple of 32 (or multiple of 32 + 1). Default: 1 (image). Silently ignored for non-video modes."),
// image2image controls (only allow selecting a prior variant)
mode: z.enum(["text2image", "image2image", "edit", "text2video", "image2video"]).optional().describe("Generation mode. 'text2video'/'image2video' require a video model (e.g. 'ltx2.3'). Required when sources exist."),
// Primary source for image2image/edit
canvas: z.union([
SourceNotationOrPath,
z.array(SourceNotationOrPath).min(1).max(1).transform((arr) => arr[0])
]).optional().describe(
"Primary source image. Notation: 'a1', 'v2', 'p1', 'i3'. Digit-only allowed only when unambiguous. Also accepts a filename in the scratchpad folder or an absolute path. Tolerates single-item array input."
),
// Additional style references for image2image/edit modes (gRPC only for image2image)
moodboard: SourceNotationList.optional().describe(
"Additional style references for image2image/edit modes. Array of source notations (same format as canvas)."
),
// Opt-in background execution: returns immediately with a requestId instead of waiting for rendering to finish.
runInBackground: z.boolean().optional().describe(
"If true, returns immediately with a requestId instead of waiting for the render to finish. Poll status/result with request_progress(requestId). Default false (synchronous)."
)
};
var GenerateToolParamsSchemaMinimalStrict = z.object(GenerateToolParamsShapeMinimal).strict();
var cropSideField = z.union([z.number(), z.string()]).optional();
var cropSideOrNullField = z.union([z.number(), z.string()]).nullable();
var cropSideOverrideArray = z.array(cropSideOrNullField).optional();
var cropSideOrArrayBase = z.preprocess(
(val) => {
if (typeof val === "string") {
const t = val.trim();
if (t.startsWith("[")) {
try {
const parsed = JSON.parse(t);
if (Array.isArray(parsed)) {
return parsed.map((el) => {
if (typeof el === "string") {
if (el.trim().toLowerCase() === "null") return null;
const n = Number(el.trim());
if (!isNaN(n)) return n;
}
return el;
});
}
} catch {
}
}
}
return val;
},
z.union([z.number(), z.string(), cropSideOverrideArray.unwrap()])
);
var cropSideOrArrayField = cropSideOrArrayBase.optional();
var detectLabelBase = z.preprocess(
(val) => {
if (typeof val === "string") {
const t = val.trim();
if (t.startsWith("[")) {
try {
const parsed = JSON.parse(t);
if (Array.isArray(parsed)) {
return parsed.map((el) => String(el).trim()).filter((s) => s.length > 0);
}
} catch {
}
}
}
return val;
},
z.union([
z.string().transform(
(s) => s.split(/\s*,\s*/).map((x) => x.trim()).filter((x) => x.length > 0)
),
z.array(z.string().min(1))
])
);
var RunInBackgroundField = z.boolean().optional().describe(
"If true, returns immediately with a requestId instead of waiting for the render to finish. Poll status/result with request_progress(requestId). Default false (synchronous)."
);
var ColorCalibrationField = z.boolean().optional().describe(
"Corrects a colour drift inside the mask area. Default false. Only helpful when the result shows a visible colour deviation in the masked area."
);
var CropToolParamsShape = {
canvas: z.union([
SourceNotationOrPath,
z.array(SourceNotationOrPath).min(1).max(1).transform((arr) => arr[0])
]).optional().describe(
"Source image. Notation: 'a1', 'v2', 'p1', 'i3'. Also accepts a filename in the scratchpad folder or an absolute path. Tolerates single-item array input."
),
cropLeft: z.union([z.number(), z.string(), z.array(z.union([z.number(), z.string()]).nullable())]).optional().describe(
"Amount to remove from the left side. Scalar (single-region): number or px-string, e.g. '120px'. Array (multi-region, parallel to detectLabel): one entry per label; null = keep detection value. Default unit: % (0\u201399)."
),
cropRight: z.union([z.number(), z.string(), z.array(z.union([z.number(), z.string()]).nullable())]).optional().describe(
"Amount to remove from the right side. Scalar or per-box array (null = keep detection value). Default unit: % (0\u201399)."
),
cropTop: z.union([z.number(), z.string(), z.array(z.union([z.number(), z.string()]).nullable())]).optional().describe(
"Amount to remove from the top. Scalar or per-box array (null = keep detection value). Default unit: % (0\u201399)."
),
cropBottom: z.union([z.number(), z.string(), z.array(z.union([z.number(), z.string()]).nullable())]).optional().describe(
"Amount to remove from the bottom. Scalar or per-box array (null = keep detection value). Default unit: % (0\u201399)."
),
imageFormat: z.enum(["square", "landscape", "portrait", "16:9"]).optional().describe(
"Target aspect ratio. Only active when explicitly set; omitting it crops with the given sides only (no AR enforcement). Ignored when all 4 crop sides are explicitly given. Unspecified axes are centred; single-side anchors are honoured. 'square'=1:1, 'landscape'=4:3, 'portrait'=3:4, '16:9'=16:9."
),
detectLabel: detectLabelBase.optional().describe(
`Label (or array of labels) of detected objects to mask/crop (requires a prior detect_object run). Array form enables multi-region: one bbox per entry, parallel to detectIndex and per-box crop overrides. String form: comma-separated labels, e.g. "cat, dog". Multi-word labels are supported. canvas: pass the most recent image, typically the detect_object result (e.g. 'i3'); it is traced back to its source automatically.`
),
detectIndex: z.union([
z.string().transform((s) => (s.match(/\d+/g) ?? []).map(Number)),
z.coerce.number().int().min(0).transform((n) => [n]),
z.array(z.coerce.number().int().min(0))
]).optional().describe(
"Zero-based index (or array of indices, parallel to detectLabel) to select among multiple detections with the same label. Default 0 for each entry."
),
frameAdjust: z.union([z.number(), z.string()]).optional().describe(
"Expand (positive) or shrink (negative) each detection bounding box. Applied as the final step after all overrides. Number: percent of bbox diagonal. String: value + optional 'px' suffix, e.g. '20px' or '-10%'. Applies to all regions uniformly."
)
};
var CropToolSchemaStrict = z.object(CropToolParamsShape).strict();
var ZoomInToolParamsShape = {
prompt: z.string().optional().describe("Description of desired changes to apply during re-rendering. Default: empty (preserve content)."),
width: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(ZOOM_TOOL_MAX_DIM).optional().describe(`Output width in pixels (max ${ZOOM_TOOL_MAX_DIM}). Has sensible default.`),
height: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(ZOOM_TOOL_MAX_DIM).optional().describe(`Output height in pixels (max ${ZOOM_TOOL_MAX_DIM}). Has sensible default.`),
model: z.string().optional().describe("Model: 'auto' (default), or a name from the list of installed models, a model name or a file name."),
canvas: z.union([
SourceNotationOrPath,
z.array(SourceNotationOrPath).min(1).max(1).transform((arr) => arr[0])
]).optional().describe(
"Source image. Notation: 'a1', 'v2', 'p1', 'i3'. Also accepts a filename in the scratchpad folder or an absolute path. Tolerates single-item array input."
),
detectLabel: z.string().optional().describe(
"Crop to the bounding box of a detected object by label (requires a prior detect_object run). canvas: pass the most recent image, typically the detect_object result (e.g. 'i3'); it is traced back to its source automatically."
),
detectIndex: z.coerce.number().int().min(0).optional().describe("Zero-based index to select among multiple detections with the same label. Default 0."),
frameAdjust: z.union([z.number(), z.string()]).optional().describe(
"Expand (positive) or shrink (negative) the detection bounding box before cropping. Number: percent of min(W,H). String: value + optional 'px' suffix, e.g. '20px' or '-10%'."
),
imageFormat: z.enum(["square", "landscape", "portrait", "16:9"]).optional().describe(
"Target aspect ratio for the render output. Only active when explicitly set. 'square'=1:1, 'landscape'=4:3, 'portrait'=3:4, '16:9'=16:9."
),
runInBackground: RunInBackgroundField
};
var ZoomInToolSchemaStrict = z.object(ZoomInToolParamsShape).strict();
var InpaintToolParamsShape = {
prompt: z.string().trim().min(1, "prompt is required: describe what should appear in the repainted region.").describe(`Required. What should appear in the repainted region (e.g. 'Replace the digit "2" with a "3"').`),
width: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(ZOOM_TOOL_MAX_DIM).optional().describe(`Output width in pixels (max ${ZOOM_TOOL_MAX_DIM}). Has sensible default.`),
height: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(ZOOM_TOOL_MAX_DIM).optional().describe(`Output height in pixels (max ${ZOOM_TOOL_MAX_DIM}). Has sensible default.`),
model: z.string().optional().describe("Model: 'auto' (default), or a name from the list of installed models, a model name or a file name."),
canvas: z.union([
SourceNotationOrPath,
z.array(SourceNotationOrPath).min(1).max(1).transform((arr) => arr[0])
]).optional().describe(
"Source image. Notation: 'a1', 'v2', 'p1', 'i3'. Also accepts a filename in the scratchpad folder or an absolute path. Tolerates single-item array input."
),
moodboard: SourceNotationList.optional().describe(
"Reference image(s) to guide the repainted region (e.g. a logo or object to insert). Array of source notations (same format as canvas). Passed to the model as a style/content reference only \u2014 not pixel-composited into the mask; its native aspect ratio is preserved."
),
detectLabel: detectLabelBase.optional().describe(
`Label (or array of labels) of detected objects to inpaint. Preferred: array, e.g. ["left eye", "right eye"]. Also accepts comma-separated string, e.g. "left eye, right eye". Multi-word labels are supported. Each entry selects one detection bounding box. Requires a prior detect_object run. canvas may be the source (e.g. 'a1') or the detect_object result (e.g. 'i3').`
),
detectIndex: z.union([
z.string().transform((s) => (s.match(/\d+/g) ?? []).map(Number)),
z.coerce.number().int().min(0).transform((n) => [n]),
z.array(z.coerce.number().int().min(0))
]).optional().describe(
"Zero-based index (or array of indices, parallel to detectLabel) to select among multiple detections with the same label. Default 0 for each entry."
),
frameAdjust: z.union([z.number(), z.string()]).optional().describe(
"Expand (positive) or shrink (negative) each detection bounding box. Applied as the final step after all per-box overrides. Applies uniformly to all regions. Number: percent of bbox diagonal. String: value + optional 'px' suffix, e.g. '20px' or '-10%'."
),
cropLeft: cropSideOrArrayBase.optional().describe(
"Override the left crop side for the detected region(s). Scalar = same for all; array (parallel to detectLabel, null = keep detection value) for per-box control. Default unit: % (0\u201399) or append 'px'."
),
cropRight: cropSideOrArrayBase.optional().describe(
"Override the right crop side. Scalar or per-box array (null = keep detection value). Default unit: %."
),
cropTop: cropSideOrArrayBase.optional().describe(
"Override the top crop side. Scalar or per-box array (null = keep detection value). Default unit: %."
),
cropBottom: cropSideOrArrayBase.optional().describe(
"Override the bottom crop side. Scalar or per-box array (null = keep detection value). Default unit: %."
),
colorCalibration: ColorCalibrationField,
runInBackground: RunInBackgroundField
};
var InpaintToolSchemaStrict = z.object(InpaintToolParamsShape).strict();
var OutpaintToolParamsShape = {
prompt: z.string().trim().min(1, "prompt is required: describe what should appear in the extended area.").describe("Required. What should appear in the extended area (e.g. 'Everything that is not the person becomes a green meadow')."),
width: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(ZOOM_TOOL_MAX_DIM).optional().describe(`Output width in pixels (max ${ZOOM_TOOL_MAX_DIM}). Has sensible default.`),
height: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(ZOOM_TOOL_MAX_DIM).optional().describe(`Output height in pixels (max ${ZOOM_TOOL_MAX_DIM}). Has sensible default.`),
model: z.string().optional().describe("Model: 'auto' (default), or a name from the list of installed models, a model name or a file name."),
canvas: z.union([
SourceNotationOrPath,
z.array(SourceNotationOrPath).min(1).max(1).transform((arr) => arr[0])
]).optional().describe(
"Source image. Notation: 'a1', 'v2', 'p1', 'i3'. Also accepts a filename in the scratchpad folder or an absolute path. Tolerates single-item array input."
),
moodboard: SourceNotationList.optional().describe(
"Reference image(s) to guide the extended region (e.g. a logo or object to insert). Array of source notations (same format as canvas). Passed to the model as a style/content reference only \u2014 not pixel-composited into the mask; its native aspect ratio is preserved."
),
detectLabel: detectLabelBase.optional().describe(
`Label (or array of labels) of detected objects to outpaint. Preferred: array, e.g. ["left eye", "right eye"]. Also accepts comma-separated string, e.g. "left eye, right eye". Multi-word labels are supported. Each entry selects one detection bounding box. Requires a prior detect_object run. canvas may be the source (e.g. 'a1') or the detect_object result (e.g. 'i3').`
),
detectIndex: z.union([
z.string().transform((s) => (s.match(/\d+/g) ?? []).map(Number)),
z.coerce.number().int().min(0).transform((n) => [n]),
z.array(z.coerce.number().int().min(0))
]).optional().describe(
"Zero-based index (or array of indices, parallel to detectLabel) to select among multiple detections with the same label. Default 0 for each entry."
),
frameAdjust: z.union([z.number(), z.string()]).optional().describe(
"Expand (positive) or shrink (negative) each detection bounding box. Applied as the final step after all per-box overrides. Applies uniformly to all regions. Number: percent of bbox diagonal. String: value + optional 'px' suffix, e.g. '20px' or '-10%'."
),
cropLeft: cropSideOrArrayBase.optional().describe(
"Override the left crop side for the detected region(s). Scalar = same for all; array (parallel to detectLabel, null = keep detection value) for per-box control. Default unit: % (0\u201399) or append 'px'."
),
cropRight: cropSideOrArrayBase.optional().describe(
"Override the right crop side. Scalar or per-box array (null = keep detection value). Default unit: %."
),
cropTop: cropSideOrArrayBase.optional().describe(
"Override the top crop side. Scalar or per-box array (null = keep detection value). Default unit: %."
),
cropBottom: cropSideOrArrayBase.optional().describe(
"Override the bottom crop side. Scalar or per-box array (null = keep detection value). Default unit: %."
),
colorCalibration: ColorCalibrationField,
runInBackground: RunInBackgroundField
};
var OutpaintToolSchemaStrict = z.object(OutpaintToolParamsShape).strict();
var UpscaleToolParamsShape = {
prompt: z.string().optional().describe("Description of desired changes to apply during re-rendering. Default: empty (preserve content)."),
width: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(ZOOM_TOOL_MAX_DIM).optional().describe(`Output width in pixels (max ${ZOOM_TOOL_MAX_DIM}). Has sensible default.`),
height: z.coerce.number().int().min(TOOL_MIN_RENDER_DIM).max(ZOOM_TOOL_MAX_DIM).optional().describe(`Output height in pixels (max ${ZOOM_TOOL_MAX_DIM}). Has sensible default.`),
scaleFactor: z.number().positive().optional().describe("Scale factor applied to the canvas dimensions. E.g. 2 doubles the resolution. Mutually exclusive with width/height."),
model: z.string().optional().describe("Model: 'auto' (default), or a name from the list of installed models, a model name or a file name."),
canvas: z.union([
SourceNotationOrPath,
z.array(SourceNotationOrPath).min(1).max(1).transform((arr) => arr[0])
]).optional().describe(
"Source image. Notation: 'a1', 'v2', 'p1', 'i3'. Also accepts a filename in the scratchpad folder or an absolute path. Tolerates single-item array input."
),
imageFormat: z.string().optional().describe("Target image format / aspect ratio preset (e.g. '16:9', 'portrait'). Resolved to concrete pixel dimensions.")
};
var UpscaleToolSchemaStrict = z.object(UpscaleToolParamsShape).strict();
// src/services/modelMappingSnapshot.ts
import path26 from "node:path";
function toUserMode(mode) {
switch (mode) {
case "txt2img":
return "text2image";
case "img2img":
return "image2image";
case "edit":
return "edit";
case "txt2vid":
return "text2video";
case "img2vid":
return "image2video";
}
}
function basenameNormalized(value) {
return path26.basename(value).trim().toLowerCase();
}
function getDefaultModelForMode(mode) {
const raw = mode === "txt2img" ? defaultParams?.model : mode === "img2img" ? defaultParamsImg2Img?.model : mode === "edit" ? defaultParamsImg2Img2?.model : mode === "txt2vid" ? defaultParamsText2Video?.model : defaultParamsImage2Video?.model;
return typeof raw === "string" ? raw : "";
}
function uniqueStrings(values) {
return [...new Set(values.filter(Boolean))];
}
function preferAutoFirst(values) {
const deduped = uniqueStrings(values);
const rest = deduped.filter((v) => v !== "auto");
return deduped.includes("auto") ? ["auto", ...rest] : rest;
}
function computeFamilyIndex(effectiveByPreset, customPresets) {
const familyByModelBasename = /* @__PURE__ */ new Map();
for (const family2 of ["z-image", "qwen-image", "flux", "ltx"]) {
for (const mode of ["txt2img", "img2img", "edit", "txt2vid", "img2vid"]) {
const file = getModelFilename(family2, mode);
if (typeof file !== "string") continue;
const base = basenameNormalized(file);
if (!base) continue;
familyByModelBasename.set(base, family2);
}
}
for (const family2 of ["z-image", "qwen-image", "flux", "ltx"]) {
const capKey = MODEL_PRESET_TO_CAPABILITY_KEY?.[family2];
if (typeof capKey !== "string") continue;
const cap = IMAGE_MODEL_CAPABILITY_MAP?.[capKey];
const filenames = cap?.modelFilenames;
if (!Array.isArray(filenames)) continue;
for (const f of filenames) {
if (typeof f !== "string") continue;
const base = basenameNormalized(f);
if (!base) continue;
if (!familyByModelBasename.has(base)) familyByModelBasename.set(base, family2);
}
}
for (const preset of customPresets.values()) {
const model = preset?.params?.model;
if (typeof model !== "string") continue;
const base = basenameNormalized(model);
if (!base) continue;
if (!familyByModelBasename.has(base)) familyByModelBasename.set(base, "custom");
}
const out = /* @__PURE__ */ new Map();
for (const info of effectiveByPreset.values()) {
out.set(info.model_filename, familyByModelBasename.get(info.model_filename) ?? "unknown");
}
return out;
}
function computeEffectiveModelForPreset(modelId, modeInternal) {
const baseModel = getDefaultModelForMode(modeInternal);
const baseBase = basenameNormalized(baseModel);
const notation = `${toUserMode(modeInternal)}.${modelId}`;
const customPreset = getCustomPreset(notation);
const hasCustomPreset = !!customPreset;
const customModelRaw = customPreset?.params?.model;
const customBase = typeof customModelRaw === "string" && customModelRaw.trim() ? basenameNormalized(customModelRaw) : void 0;
if (!hasCustomPreset && modelId !== "auto" && modelId !== "custom") {
const support = checkModeSupport(modelId, toUserMode(modeInternal));
if (!support.supported) return "";
}
if (modelId === "custom" && !customPreset) return "";
const overlay = getEffectiveOverlay(modelId, modeInternal);
const overlayModel = overlay.params?.model;
const overlayBase = typeof overlayModel === "string" && overlayModel.trim() ? basenameNormalized(overlayModel) : void 0;
return customBase ?? overlayBase ?? baseBase;
}
async function buildDtcModelMappingSnapshot() {
const customPresets = await loadCustomConfigs();
const modes = ["txt2img", "img2img", "edit", "txt2vid", "img2vid"];
const effectiveByPreset = /* @__PURE__ */ new Map();
for (const modeInternal of modes) {
const mode = toUserMode(modeInternal);
for (const modelId of MODEL_FAMILIES) {
const preset = `${mode}.${modelId}`;
effectiveByPreset.set(preset, {
mode,
model_id: modelId,
preset,
model_filename: computeEffectiveModelForPreset(modelId, modeInternal),
model_family: "unknown"
});
}
}
const familyIndex = computeFamilyIndex(effectiveByPreset, customPresets);
for (const info of effectiveByPreset.values()) {
info.model_family = familyIndex.get(info.model_filename) ?? "unknown";
}
const presetsByModel = /* @__PURE__ */ new Map();
for (const info of effectiveByPreset.values()) {
if (!info.model_filename) continue;
const set = presetsByModel.get(info.model_filename) ?? /* @__PURE__ */ new Set();
set.add(info.preset);
presetsByModel.set(info.model_filename, set);
}
const models = {};
for (const [modelFilename, presetSet] of presetsByModel.entries()) {
const model_family = familyIndex.get(modelFilename) ?? "unknown";
const model_use_by_mode = {};
for (const p of Array.from(presetSet).sort()) {
const [mode, modelId] = p.split(".");
if (!mode || !modelId) continue;
if (mode !== "text2image" && mode !== "image2image" && mode !== "edit" && mode !== "text2video" && mode !== "image2video") continue;
const existing = model_use_by_mode[mode] ?? [];
model_use_by_mode[mode] = preferAutoFirst([...existing, modelId]);
}
models[modelFilename] = {
model_family,
model_use_by_mode
};
}
return {
schema: "dtc.model-mapping-snapshot.v1",
models
};
}
// src/services/defaultParamsDrawThingsRestore.ts
var defaultParamsImg2Img3 = {
aesthetic_score: 6.5,
batch_count: 1,
batch_size: 1,
causal_inference: 0,
causal_inference_pad: 0,
cfg_zero_init_steps: 0,
cfg_zero_star: false,
clip_l_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
clip_skip: 1,
clip_weight: 1,
controls: [],
crop_left: 0,
crop_top: 0,
fps: 25,
guidance_embed: 1,
guidance_scale: 1,
guiding_frame_noise: 0.019999999552965164,
// Ensure size keys exist for filtering; service overwrites with actual PNG size
width: 576,
height: 768,
hires_fix: false,
hires_fix_height: 512,
hires_fix_strength: 0.4000000059604645,
// hires_fix_width: 384,
image_guidance: 1.5,
image_prior_steps: 5,
loras: [],
mask_blur: 2.5,
mask_blur_outset: 0,
model: "flux_2_klein_9b_kv_q6p.ckpt",
motion_scale: 127,
negative_aesthetic_score: 0,
// negative_original_height: 512, negative_original_width: 512,
negative_prompt: "",
negative_prompt_for_image_prior: true,
num_frames: 1,
open_clip_g_text: "Could this be it, or not, I am not sure really.",
// original_height: 512, original_width: 512,
preserve_original_after_inpaint: true,
prompt: "Restore the image. Maintain the identity of the subjects, objects, backgrounds, and scenes exactly as in the original image.",
refiner_model: null,
refiner_start: 0.4000000059604645,
resolution_dependent_shift: false,
sampler: "DDIM Trailing",
seed: 175308301,
seed_mode: "Scale Alike",
separate_clip_l: false,
separate_open_clip_g: false,
separate_t5: false,
sharpness: 0,
shift: 3,
speed_up_with_guidance_embed: true,
stage_2_guidance: 1,
stage_2_shift: 1,
start_frame_guidance: 1.2000000476837158,
steps: 4,
stochastic_sampling_gamma: 0.3,
strength: 1,
t5_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
t5_text_encoder_decoding: true,
// target_height: 512, target_width: 512,
tea_cache: false,
tea_cache_end: 100,
tea_cache_max_skip_steps: 3,
tea_cache_start: 5,
tea_cache_threshold: 0.20000000298023224,
tiled_decoding: false,
tiled_diffusion: false,
upscaler: null,
upscaler_scale: 0,
zero_negative_prompt: false
};
// src/services/defaultParamsZoom.ts
var defaultParamsZoom = {
aesthetic_score: 6.5,
batch_count: 1,
batch_size: 1,
causal_inference: 0,
causal_inference_pad: 0,
cfg_zero_init_steps: 0,
cfg_zero_star: false,
clip_l_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
clip_skip: 1,
clip_weight: 1,
controls: [],
crop_left: 0,
crop_top: 0,
decoding_tile_height: 1024,
decoding_tile_overlap: 128,
decoding_tile_width: 1024,
diffusion_tile_height: 1024,
diffusion_tile_overlap: 128,
diffusion_tile_width: 1024,
fps: 25,
guidance_embed: 1,
guidance_scale: 1,
guiding_frame_noise: 0.019999999552965164,
// Ensure size keys exist for filtering; service overwrites with actual PNG size
width: 768,
height: 1024,
hires_fix: false,
hires_fix_height: 512,
hires_fix_strength: 0.4000000059604645,
// hires_fix_width: 384,
image_guidance: 1.5,
image_prior_steps: 5,
loras: [],
mask_blur: 1.5,
mask_blur_outset: 0,
model: "seedvr2_7b_q6p.ckpt",
motion_scale: 127,
negative_aesthetic_score: 0,
// negative_original_height: 512, negative_original_width: 512,
negative_prompt: "",
negative_prompt_for_image_prior: true,
num_frames: 1,
open_clip_g_text: "Could this be it, or not, I am not sure really.",
// original_height: 512, original_width: 512,
preserve_original_after_inpaint: true,
prompt: "",
refiner_model: null,
refiner_start: 0.4000000059604645,
resolution_dependent_shift: false,
sampler: "DDIM Trailing",
seed: 175308301,
seed_mode: "Scale Alike",
separate_clip_l: false,
separate_open_clip_g: false,
separate_t5: false,
sharpness: 0,
shift: 3,
speed_up_with_guidance_embed: true,
stage_2_guidance: 1,
stage_2_shift: 1,
start_frame_guidance: 1.2000000476837158,
steps: 1,
stochastic_sampling_gamma: 0.3,
strength: 1,
t5_text: "80s poster, high quality, best quality, detailed, professional photograph, award-winning, trending on artstation",
t5_text_encoder_decoding: true,
// target_height: 512, target_width: 512,
tea_cache: false,
tea_cache_end: 100,
tea_cache_max_skip_steps: 3,
tea_cache_start: 5,
tea_cache_threshold: 0.20000000298023224,
tiled_decoding: true,
tiled_diffusion: true,
upscaler: null,
upscaler_scale: 0,
zero_negative_prompt: false
};
// src/services/modelInventoryShadow.ts
var OVERLAY_MODES2 = ["txt2img", "img2img", "edit", "txt2vid", "img2vid"];
var CAPABILITY_MODES = ["text2image", "edit", "text2video", "image2video"];
function compareInventoryWithRegistry(inv) {
const findings = [];
let checked = 0, ok = 0, absent = 0;
const check = (subject, mode, main, required, fixed2) => {
checked++;
if (!required.every((f) => inv.files.has(f))) {
absent++;
if (fixed2) findings.push({ level: "warn", kind: "fixed-profile-missing", subject, file: main, detail: `${main} (or a required LoRA) is not installed` });
return;
}
const s = stateOfFile(inv, main);
if (s.state === "requires-missing") findings.push({ level: "warn", kind: "requires-missing", subject, file: main, detail: `required files missing: ${s.missing.join(", ")}` });
else if (s.state === "custom") findings.push({ level: "info", kind: "custom-model", subject, file: main, detail: `not in the catalog (spec family ${s.model.family})` });
else if (s.state === "not-installed") findings.push({ level: "info", kind: "unknown-file", subject, file: main, detail: "file present, but neither catalog nor server spec knows it" });
else if (mode && !supportsMode(s.model.modes, mode)) {
findings.push({ level: s.model.modesUncertain ? "info" : "warn", kind: "mode-unsupported", subject, file: main, detail: `catalog modes of ${s.model.id}: ${s.model.modes.join(", ")}${s.model.modesUncertain ? " (uncertain)" : ""}` });
} else ok++;
};
for (const id of MODEL_IDS) {
if (id === "auto" || id === "custom") continue;
for (const mode of OVERLAY_MODES2) {
const main = getModelFilename(id, mode);
if (!main) continue;
const required = getModelRequiredFiles(id, mode);
const loras = required.filter((f) => f !== main);
const missing = loras.filter((f) => !inv.files.has(f));
if (missing.length && inv.files.has(main)) {
checked++;
findings.push({ level: "warn", kind: "lora-missing", subject: `overlay ${id}/${mode}`, file: main, detail: `overlay settings assume LoRA ${missing.join(", ")}` });
continue;
}
check(`overlay ${id}/${mode}`, mode, main, required, false);
}
}
const fixed = [
["auto/text2image", defaultParams.model, "txt2img"],
["auto/image2image", defaultParamsImg2Img.model, "img2img"],
["auto/edit", defaultParamsImg2Img2.model, "edit"],
["auto/text2video", defaultParamsText2Video.model, "txt2vid"],
["auto/image2video", defaultParamsImage2Video.model, "img2vid"],
["profile restore", defaultParamsImg2Img3.model, null],
["profile zoom", defaultParamsZoom.model, null]
];
for (const [subject, file, mode] of fixed) if (file) check(subject, mode, file, [file], subject.startsWith("profile"));
for (const [key, cap] of Object.entries(IMAGE_MODEL_CAPABILITY_MAP)) {
const present = (cap.modelFilenames ?? []).filter((f) => inv.byFile.has(f));
if (!present.length) continue;
checked++;
const derived = new Set(present.flatMap((f) => inv.byFile.get(f).modes));
const uncertain = present.every((f) => inv.byFile.get(f).modesUncertain);
const hand = CAPABILITY_MODES.filter((m) => cap.modes[m]);
const diff = [...hand.filter((m) => !derived.has(m)).map((m) => `-${m}`), ...CAPABILITY_MODES.filter((m) => derived.has(m) && !hand.includes(m)).map((m) => `+${m}`)];
if (diff.length) findings.push({ level: uncertain ? "info" : "warn", kind: "capability-mode", subject: `capability ${key}`, file: present[0], detail: `registry vs catalog: ${diff.join(" ")}` });
else ok++;
}
return { checked, ok, absent, findings, hash: inv.hash };
}
var lastLoggedHash = null;
function logShadowReport(report, log2 = console) {
if (report.hash === lastLoggedHash) return;
lastLoggedHash = report.hash;
log2.info(`[inventory-shadow] checked=${report.checked} ok=${report.ok} absent=${report.absent} findings=${report.findings.length}${report.echoMs === void 0 ? "" : ` echo=${report.echoMs}ms`}`);
for (const f of report.findings) (f.level === "warn" ? log2.warn : log2.info)(`[inventory-shadow] ${f.level} ${f.kind}: ${f.subject} (${f.file}) ${f.detail}`);
}
function runInventoryShadow(echoResponse, echoMs) {
try {
logShadowReport({ ...compareInventoryWithRegistry(buildInventory(parseEchoResponse(echoResponse))), echoMs });
} catch {
}
}
// src/services/profileModels.ts
import path27 from "node:path";
var DEFAULT_MODEL = {
zoom: () => defaultParamsZoom.model,
restore: () => defaultParamsImg2Img3.model
};
var LABEL = { zoom: "the zoom pass", restore: "the restore pass" };
function substituteInstalledPrecision(file, inv) {
return installedFileOf(file, inv);
}
function substitutionNote(from, to) {
return `'${from}' is not installed; using '${to}' (another precision of the same model).`;
}
function requiredFileForProfile(profile) {
const overlay = getEffectiveOverlay(void 0, profile);
const custom = overlay.source === "custom" ? overlay.params?.model : void 0;
if (typeof custom === "string" && custom.trim()) return { file: path27.basename(custom.trim()), fromCustomConfig: true };
return { file: DEFAULT_MODEL[profile]() ?? "", fromCustomConfig: false };
}
function describeMissingProfileModel(profile, inv) {
const { file, fromCustomConfig } = requiredFileForProfile(profile);
if (!file) return null;
const effective = fromCustomConfig ? { file, substituted: false } : substituteInstalledPrecision(file, inv);
if (inv.files.has(effective.file)) {
const known = inv.byFile.get(effective.file);
return known && !known.ready ? `${LABEL[profile]} needs '${known.name}', but it is incomplete. ${explainFile(inv, effective.file)}` : null;
}
const name = catalogModelOfFile(file)?.name;
const label = name ? `${name} (${file})` : `'${file}'`;
return fromCustomConfig ? `${LABEL[profile]} needs ${label}, set in your '${profile}.auto' preset, but it is not installed. Install it in Draw Things or fix the preset.` : `${LABEL[profile]} needs ${label}, but no precision of it is installed. Install it in Draw Things (any precision works), or save a '${profile}.auto' preset with a model you have.`;
}
async function checkProfileModels(profiles) {
try {
const inv = await currentInventory();
if (!inv) return null;
const problems = profiles.map((p) => describeMissingProfileModel(p, inv)).filter((m) => !!m);
if (!problems.length) return null;
return `Cannot run: ${problems.join(" ")}`.replace(/\s+/g, " ");
} catch {
return null;
}
}
// src/services/autoFallback.ts
var MODES2 = {
text2image: { internal: "txt2img", defaultModel: () => defaultParams.model },
image2image: { internal: "img2img", defaultModel: () => defaultParamsImg2Img.model },
edit: { internal: "edit", defaultModel: () => defaultParamsImg2Img2.model },
text2video: { internal: "txt2vid", defaultModel: () => defaultParamsText2Video.model },
image2video: { internal: "img2vid", defaultModel: () => defaultParamsImage2Video.model }
};
function autoFallbackFor(mode, inv) {
const cfg = MODES2[mode];
const file = cfg?.defaultModel();
if (!cfg || !file || !inv) return null;
if (getEffectiveOverlay("auto", cfg.internal).source === "custom") return null;
const state = stateOfFile(inv, substituteInstalledPrecision(file, inv).file);
if (state.state === "ready" || state.state === "custom" && state.model.ready) return null;
const pick = pickFallbackModel(inv, mode, { accept: isImage2ImageMode(mode) ? (m) => !!image2imagePresetOf(m, inv) : void 0 });
if (!pick) return null;
const why = state.state === "requires-missing" ? `is incomplete (missing: ${state.missing.join(", ")})` : "is not installed";
const i2i = isImage2ImageMode(mode) ? image2imagePresetOf(pick.model, inv) : null;
const preset = i2i ? i2i.kind === "user" ? i2i.preset.modelId : i2i.preset : tunedPresetFor(pick.model.id, mode, inv);
return {
modelId: preset ?? pick.model.file,
note: `Default model '${file}' ${why}; using '${pick.model.name}' (${preset ? `preset ${preset}` : pick.model.file}) instead.${pick.notes.length ? ` ${pick.notes.join(" ")}` : ""}`
};
}
async function resolveAutoFallback(mode) {
try {
return autoFallbackFor(mode, await currentInventory());
} catch {
return null;
}
}
// src/services/modelListText.ts
var PRESET_MODE_ORDER = AGENT_MODE_ORDER;
var DEFAULT_MAX_CHARS = 1800;
var RECOMMENDED_EDIT = [
{ tag: "flux2_9b", hint: "our default" },
{ tag: "flux3_5b" },
{ tag: "qwen_image_2.1", hint: "Turbo" }
];
var INTRO = "auto (default) picks the best installed model for the mode. Otherwise name one of these (the best installed variant is used), or a user-defined entry from custom_configs.json.";
function tunedNames() {
const names = /* @__PURE__ */ new Set();
for (const id of MODEL_IDS) {
if (id === "auto" || id === "custom") continue;
for (const mode of ["txt2img", "edit", "txt2vid", "img2vid"]) {
const file = getModelFilename(id, mode);
const model = file ? catalogModelOfFile(file) : void 0;
const name = model && agentNameOfModel(model);
if (name) names.add(name);
}
}
return [...names].sort();
}
function userPresetLine() {
const byName = /* @__PURE__ */ new Map();
try {
for (const [mode, name] of getAvailableCustomCombinations()) {
if (name === "auto" || isPresetName(name) || runtimeCatalog.families[name]) continue;
byName.set(name, (byName.get(name) ?? /* @__PURE__ */ new Set()).add(mode));
}
} catch {
return null;
}
if (!byName.size) return null;
const names = [...byName].sort(([a], [b]) => a.localeCompare(b)).map(([name, modes]) => `${name} (${PRESET_MODE_ORDER.filter((m) => modes.has(m)).join(", ")})`);
return `- your presets (custom_configs.json): ${names.slice(0, 8).join(", ")}${names.length > 8 ? `, +${names.length - 8} more` : ""}`;
}
function buildModelListText(inv, opts = {}) {
if (opts.recommendedEdit) {
const installedFamilies = inv && new Set(inv.installed.filter((m) => m.ready).map((m) => m.family));
const shown = RECOMMENDED_EDIT.filter((r) => !installedFamilies || installedFamilies.has(r.tag));
const list = (shown.length ? shown : RECOMMENDED_EDIT).map((r) => r.hint ? `${agentNameOfFamily(r.tag)} (${r.hint})` : agentNameOfFamily(r.tag)).join(", ");
return `Default: auto, the recommended model. Omit unless the user asks. Alternatives: ${list}.`;
}
const presetLine = userPresetLine();
if (!inv) return `${INTRO} Names we tune: ${tunedNames().join(", ")} (installed models could not be checked).${presetLine ? `
${presetLine}` : ""}`;
const names = installedAgentNames(inv);
const lines = names.map((e) => `- ${e.name} (${e.modes.join(", ")})`);
const custom = inv.custom.filter((c) => c.ready).map((c) => `${c.name} [${c.family}]`).sort();
if (custom.length) lines.push(`- custom models: ${custom.slice(0, 5).join(", ")}${custom.length > 5 ? `, +${custom.length - 5} more` : ""}`);
if (presetLine) lines.push(presetLine);
if (!lines.length) return `${INTRO} No curated model is installed on this machine.`;
const full = `${INTRO} Installed on this machine:
${lines.join("\n")}`;
if (full.length <= (opts.maxChars ?? DEFAULT_MAX_CHARS)) return full;
return `${INTRO} Installed: ${names.map((e) => e.name).join(", ")}. An unknown name returns the full list.`;
}
async function getModelListText(req = {}) {
let timer;
try {
const inv = await Promise.race([
(async () => {
await req.prepare?.();
return currentInventory();
})(),
new Promise((resolve) => {
timer = setTimeout(() => resolve(null), req.timeoutMs ?? 3e3);
})
]);
return buildModelListText(inv, req);
} catch {
return buildModelListText(null, req);
} finally {
if (timer) clearTimeout(timer);
}
}
function prepareInventoryFetcher(ServiceCtor) {
if (hasInventoryFetcher()) return;
const conn = getEngineConnectionDefaults({
host: process.env.DRAW_THINGS_HOST,
httpPort: process.env.DRAW_THINGS_HTTP_PORT ? parseInt(process.env.DRAW_THINGS_HTTP_PORT, 10) : void 0,
grpcPort: process.env.DRAW_THINGS_GRPC_PORT ? parseInt(process.env.DRAW_THINGS_GRPC_PORT, 10) : void 0
});
new ServiceCtor((conn.grpc?.target || "127.0.0.1:7859").replace(/^grpc:\/\//i, ""));
}
// src/services/drawThingsConfigMapper.ts
var flatbuffers9 = __toESM(require_flatbuffers(), 1);
function buildDtGenerationConfiguration(p) {
const w = typeof p.width === "number" ? p.width : 576;
const h = typeof p.height === "number" ? p.height : 768;
const start_width = Math.max(1, Math.round(w / 64));
const start_height = Math.max(1, Math.round(h / 64));
let samplerEnum = 17 /* UniPCTrailing */;
let samplerName = "UniPCTrailing";
if (typeof p.sampler === "number") {
samplerEnum = p.sampler;
samplerName = Object.keys(SamplerType).find(
(k) => SamplerType[k] === p.sampler
) || "Unknown";
} else if (typeof p.sampler === "string") {
samplerName = p.sampler.replace(/\s+/g, "");
samplerEnum = SamplerType[samplerName] ?? 17 /* UniPCTrailing */;
}
const seedModeEnum = SeedMode[String(p.seed_mode || "Scale Alike").replace(/\s+/g, "")] ?? 2 /* ScaleAlike */;
const view = {
id: 1,
start_width,
start_height,
seed: typeof p.seed === "number" ? p.seed : void 0,
steps: typeof p.steps === "number" ? p.steps : void 0,
sampler: samplerName,
batch_count: typeof p.batch_count === "number" ? p.batch_count : void 0,
batch_size: typeof p.batch_size === "number" ? Math.max(1, Math.min(4, Math.round(p.batch_size))) : 1,
model: p.model || void 0,
seed_mode: String(p.seed_mode || "Scale Alike").replace(/\s+/g, ""),
t5_text: p.t5_text || void 0,
clip_l_text: p.clip_l_text || void 0,
image_guidance_scale: typeof p.image_guidance === "number" ? p.image_guidance : void 0,
tiled_decoding: !!p.tiled_decoding,
decoding_tile_width: typeof p.decoding_tile_width === "number" ? Math.max(1, Math.round(p.decoding_tile_width / 64)) : void 0,
decoding_tile_height: typeof p.decoding_tile_height === "number" ? Math.max(1, Math.round(p.decoding_tile_height / 64)) : void 0,
decoding_tile_overlap: typeof p.decoding_tile_overlap === "number" ? Math.max(0, Math.round(p.decoding_tile_overlap / 64)) : void 0,
compressionArtifacts: p.compressionArtifacts ?? p.compression_artifacts ?? void 0,
compressionArtifactsQuality: typeof p.compressionArtifactsQuality === "number" ? p.compressionArtifactsQuality : typeof p.compression_artifacts_quality === "number" ? p.compression_artifacts_quality : void 0,
num_frames: typeof p.num_frames === "number" ? p.num_frames : void 0
};
const builder = new flatbuffers9.Builder(2048);
const modelOffset = p.model ? builder.createString(p.model) : 0;
const upscalerOffset = typeof p.upscaler === "string" && p.upscaler ? builder.createString(p.upscaler) : 0;
const clipLTextOffset = p.clip_l_text ? builder.createString(p.clip_l_text) : 0;
const t5TextOffset = p.t5_text ? builder.createString(p.t5_text) : 0;
const openClipGTextOffset = p.open_clip_g_text ? builder.createString(p.open_clip_g_text) : 0;
let lorasVector = 0;
if (Array.isArray(p.loras) && p.loras.length) {
const loff = [];
for (const l of p.loras) {
const f = l.file ? builder.createString(l.file) : 0;
const wt = typeof l.weight === "number" ? l.weight : 1;
loff.push(LoRA.createLoRA(builder, f, wt, 0 /* All */));
}
lorasVector = GenerationConfiguration.createLorasVector(builder, loff);
}
GenerationConfiguration.startGenerationConfiguration(builder);
GenerationConfiguration.addId(builder, BigInt(1));
GenerationConfiguration.addStartWidth(builder, start_width);
GenerationConfiguration.addStartHeight(builder, start_height);
if (typeof p.seed === "number")
GenerationConfiguration.addSeed(builder, p.seed);
if (typeof p.steps === "number")
GenerationConfiguration.addSteps(builder, p.steps);
if (typeof p.guidance_scale === "number")
GenerationConfiguration.addGuidanceScale(builder, p.guidance_scale);
if (typeof p.strength === "number")
GenerationConfiguration.addStrength(builder, p.strength);
if (modelOffset) GenerationConfiguration.addModel(builder, modelOffset);
GenerationConfiguration.addSampler(builder, samplerEnum);
if (typeof p.batch_count === "number") {
GenerationConfiguration.addBatchCount(
builder,
p.batch_count
);
}
const batchSize = typeof p.batch_size === "number" ? Math.max(1, Math.min(4, Math.round(p.batch_size))) : 1;
GenerationConfiguration.addBatchSize(builder, batchSize);
if (typeof p.image_guidance === "number")
GenerationConfiguration.addImageGuidanceScale(builder, p.image_guidance);
GenerationConfiguration.addSeedMode(builder, seedModeEnum);
if (typeof p.clip_skip === "number")
GenerationConfiguration.addClipSkip(builder, p.clip_skip);
if (lorasVector) GenerationConfiguration.addLoras(builder, lorasVector);
if (typeof p.mask_blur === "number")
GenerationConfiguration.addMaskBlur(builder, p.mask_blur);
if (typeof p.mask_blur_outset === "number")
GenerationConfiguration.addMaskBlurOutset(builder, p.mask_blur_outset);
if (typeof p.preserve_original_after_inpaint === "boolean")
GenerationConfiguration.addPreserveOriginalAfterInpaint(builder, p.preserve_original_after_inpaint);
if (typeof p.clip_weight === "number")
GenerationConfiguration.addClipWeight(builder, p.clip_weight);
if (typeof p.image_prior_steps === "number")
GenerationConfiguration.addImagePriorSteps(builder, p.image_prior_steps);
if (typeof p.negative_original_height === "number")
GenerationConfiguration.addNegativeOriginalImageHeight(
builder,
p.negative_original_height
);
if (typeof p.negative_original_width === "number")
GenerationConfiguration.addNegativeOriginalImageWidth(
builder,
p.negative_original_width
);
if (typeof p.fps === "number")
GenerationConfiguration.addFpsId(builder, p.fps);
if (typeof p.motion_scale === "number")
GenerationConfiguration.addMotionBucketId(builder, p.motion_scale);
if (typeof p.start_frame_guidance === "number")
GenerationConfiguration.addStartFrameCfg(builder, p.start_frame_guidance);
if (typeof p.num_frames === "number")
GenerationConfiguration.addNumFrames(builder, p.num_frames);
if (typeof p.sharpness === "number")
GenerationConfiguration.addSharpness(builder, p.sharpness);
if (typeof p.shift === "number")
GenerationConfiguration.addShift(builder, p.shift);
if (typeof p.tiled_decoding === "boolean")
GenerationConfiguration.addTiledDecoding(builder, !!p.tiled_decoding);
if (typeof p.decoding_tile_width === "number")
GenerationConfiguration.addDecodingTileWidth(
builder,
Math.max(1, Math.round(p.decoding_tile_width / 64))
);
if (typeof p.decoding_tile_height === "number")
GenerationConfiguration.addDecodingTileHeight(
builder,
Math.max(1, Math.round(p.decoding_tile_height / 64))
);
if (typeof p.decoding_tile_overlap === "number")
GenerationConfiguration.addDecodingTileOverlap(
builder,
Math.max(0, Math.round(p.decoding_tile_overlap / 64))
);
if (typeof p.stochastic_sampling_gamma === "number")
GenerationConfiguration.addStochasticSamplingGamma(
builder,
p.stochastic_sampling_gamma
);
if (typeof p.tiled_diffusion === "boolean")
GenerationConfiguration.addTiledDiffusion(builder, !!p.tiled_diffusion);
if (clipLTextOffset)
GenerationConfiguration.addClipLText(builder, clipLTextOffset);
if (openClipGTextOffset)
GenerationConfiguration.addOpenClipGText(builder, openClipGTextOffset);
if (typeof p.speed_up_with_guidance_embed === "boolean")
GenerationConfiguration.addSpeedUpWithGuidanceEmbed(
builder,
!!p.speed_up_with_guidance_embed
);
if (typeof p.guidance_embed === "number")
GenerationConfiguration.addGuidanceEmbed(builder, p.guidance_embed);
if (typeof p.resolution_dependent_shift === "boolean")
GenerationConfiguration.addResolutionDependentShift(
builder,
!!p.resolution_dependent_shift
);
if (typeof p.tea_cache_start === "number")
GenerationConfiguration.addTeaCacheStart(builder, p.tea_cache_start);
if (typeof p.tea_cache_end === "number")
GenerationConfiguration.addTeaCacheEnd(builder, p.tea_cache_end);
if (typeof p.tea_cache_threshold === "number")
GenerationConfiguration.addTeaCacheThreshold(
builder,
p.tea_cache_threshold
);
if (typeof p.tea_cache === "boolean")
GenerationConfiguration.addTeaCache(builder, !!p.tea_cache);
if (typeof p.separate_t5 === "boolean")
GenerationConfiguration.addSeparateT5(builder, !!p.separate_t5);
if (t5TextOffset) GenerationConfiguration.addT5Text(builder, t5TextOffset);
if (typeof p.tea_cache_max_skip_steps === "number")
GenerationConfiguration.addTeaCacheMaxSkipSteps(
builder,
p.tea_cache_max_skip_steps
);
if (typeof p.causal_inference === "number")
GenerationConfiguration.addCausalInference(builder, p.causal_inference);
if (typeof p.causal_inference_pad === "number")
GenerationConfiguration.addCausalInferencePad(
builder,
p.causal_inference_pad
);
if (typeof p.cfg_zero_star === "boolean")
GenerationConfiguration.addCfgZeroStar(builder, !!p.cfg_zero_star);
if (typeof p.cfg_zero_init_steps === "number")
GenerationConfiguration.addCfgZeroInitSteps(builder, p.cfg_zero_init_steps);
const caValue = p.compressionArtifacts ?? p.compression_artifacts;
if (typeof caValue === "string") {
const ca = caValue;
const caEnum = ca === "h264" ? 1 /* H264 */ : ca === "h265" ? 2 /* H265 */ : ca === "jpeg" ? 3 /* Jpeg */ : 0 /* Disabled */;
GenerationConfiguration.addCompressionArtifacts(builder, caEnum);
}
const caQualityValue = p.compressionArtifactsQuality ?? p.compression_artifacts_quality;
if (typeof caQualityValue === "number")
GenerationConfiguration.addCompressionArtifactsQuality(builder, caQualityValue);
if (upscalerOffset) GenerationConfiguration.addUpscaler(builder, upscalerOffset);
const upscalerScale = p.upscaler_scale;
if (typeof upscalerScale === "number" && upscalerScale > 0)
GenerationConfiguration.addUpscalerScaleFactor(builder, upscalerScale);
const root = GenerationConfiguration.endGenerationConfiguration(builder);
GenerationConfiguration.finishGenerationConfigurationBuffer(builder, root);
const bytes = Buffer.from(builder.asUint8Array());
return { view, bytes };
}
// src/services/drawThingsService.ts
import axios from "axios";
import fs25 from "fs";
import path28 from "path";
var HTTP_SEED_MODE_FROM_CODE = {
0: "Legacy",
1: "Torch CPU Compatible",
2: "Scale Alike",
3: "NVIDIA GPU Compatible"
};
var HTTP_SEED_MODE_FROM_KEY = {
Legacy: "Legacy",
TorchCpuCompatible: "Torch CPU Compatible",
TorchCPUCompatible: "Torch CPU Compatible",
ScaleAlike: "Scale Alike",
NvidiaGpuCompatible: "NVIDIA GPU Compatible",
NvidiaGPUCompatible: "NVIDIA GPU Compatible"
};
var HTTP_SAMPLER_FROM_CODE = {
0: "DPM++ 2M Karras",
1: "Euler a",
2: "DDIM",
3: "PLMS",
4: "DPM++ SDE Karras",
5: "UniPC",
6: "LCM",
7: "Euler A Substep",
8: "DPM++ SDE Substep",
9: "TCD",
10: "Euler A Trailing",
11: "DPM++ SDE Trailing",
12: "DPM++ 2M AYS",
13: "Euler A AYS",
14: "DPM++ SDE AYS",
15: "DPM++ 2M Trailing",
16: "DDIM Trailing",
17: "UniPC Trailing",
18: "UniPC AYS",
19: "TCD Trailing"
};
var HTTP_SAMPLER_FROM_KEY = {
DPMPP2MKarras: "DPM++ 2M Karras",
EulerA: "Euler a",
DDIM: "DDIM",
PLMS: "PLMS",
DPMPPSDEKarras: "DPM++ SDE Karras",
UniPC: "UniPC",
LCM: "LCM",
EulerASubstep: "Euler A Substep",
DPMPPSDESubstep: "DPM++ SDE Substep",
TCD: "TCD",
EulerATrailing: "Euler A Trailing",
DPMPPSDETrailing: "DPM++ SDE Trailing",
DPMPP2MAYS: "DPM++ 2M AYS",
EulerAAYS: "Euler A AYS",
DPMPPSDEAYS: "DPM++ SDE AYS",
DPMPP2MTrailing: "DPM++ 2M Trailing",
DDIMTrailing: "DDIM Trailing",
UniPCTrailing: "UniPC Trailing",
UniPCAYS: "UniPC AYS",
TCDTrailing: "TCD Trailing"
};
function normalizeHttpSeedMode(value) {
if (typeof value === "number" && Number.isFinite(value)) {
return HTTP_SEED_MODE_FROM_CODE[value] ?? String(value);
}
if (typeof value === "string" && value.trim()) {
const raw = value.trim();
if (raw.includes(" ")) return raw;
const key = raw.replace(/\s+/g, "");
return HTTP_SEED_MODE_FROM_KEY[key] ?? raw;
}
return value;
}
function normalizeHttpSampler(value) {
if (typeof value === "number" && Number.isFinite(value)) {
return HTTP_SAMPLER_FROM_CODE[value] ?? String(value);
}
if (typeof value === "string" && value.trim()) {
const raw = value.trim();
if (raw.includes(" ") || raw.includes("+")) return raw;
const key = raw.replace(/\s+/g, "");
return HTTP_SAMPLER_FROM_KEY[key] ?? raw;
}
return value;
}
function applyHttpCustomOverlayFixups(overlay) {
const out = { ...overlay };
const rename = (from, to) => {
if (!Object.prototype.hasOwnProperty.call(out, from)) return;
if (!Object.prototype.hasOwnProperty.call(out, to)) out[to] = out[from];
delete out[from];
};
rename("stage2_guidance", "stage_2_guidance");
rename("stage2_shift", "stage_2_shift");
delete out.stage2_steps;
rename("stage2Guidance", "stage_2_guidance");
rename("stage2Shift", "stage_2_shift");
delete out.stage2Steps;
rename("t5_text_encoder", "t5_text_encoder_decoding");
rename("t5TextEncoder", "t5_text_encoder_decoding");
rename("image_guidance_scale", "image_guidance");
rename("imageGuidanceScale", "image_guidance");
delete out.target_image_height;
delete out.target_image_width;
delete out.targetImageHeight;
delete out.targetImageWidth;
delete out.original_image_height;
delete out.original_image_width;
delete out.originalImageHeight;
delete out.originalImageWidth;
delete out.negative_original_image_height;
delete out.negative_original_image_width;
delete out.negativeOriginalImageHeight;
delete out.negativeOriginalImageWidth;
delete out.face_restoration;
delete out.faceRestoration;
delete out.width;
delete out.height;
delete out.target_width;
delete out.target_height;
delete out.batch_count;
delete out.batch_size;
delete out.batchCount;
delete out.batchSize;
delete out.upscaler;
delete out.upscaler_scale;
delete out.upscalerScale;
const teaCache = typeof out.tea_cache === "boolean" ? out.tea_cache : typeof out.teaCache === "boolean" ? out.teaCache : void 0;
if (teaCache === false) {
delete out.tea_cache_start;
delete out.tea_cache_end;
delete out.teaCacheStart;
delete out.teaCacheEnd;
}
if (Object.prototype.hasOwnProperty.call(out, "upscaler_scale_factor")) {
if (!Object.prototype.hasOwnProperty.call(out, "upscaler_scale")) {
out.upscaler_scale = out.upscaler_scale_factor;
}
delete out.upscaler_scale_factor;
}
if (Object.prototype.hasOwnProperty.call(out, "upscalerScaleFactor")) {
if (!Object.prototype.hasOwnProperty.call(out, "upscaler_scale")) {
out.upscaler_scale = out.upscalerScaleFactor;
}
delete out.upscalerScaleFactor;
}
if (Object.prototype.hasOwnProperty.call(out, "upscalerScale")) {
delete out.upscalerScale;
}
if (Object.prototype.hasOwnProperty.call(out, "seed_mode")) {
out.seed_mode = normalizeHttpSeedMode(out.seed_mode);
}
if (Object.prototype.hasOwnProperty.call(out, "seedMode")) {
out.seedMode = normalizeHttpSeedMode(out.seedMode);
}
if (Object.prototype.hasOwnProperty.call(out, "sampler")) {
out.sampler = normalizeHttpSampler(out.sampler);
}
return out;
}
function buildAuditLogger2({
backend,
mode
}) {
const requestId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const entry = {
timestamp: logTimestamp(),
backend,
mode,
requestId
};
function setRequested(obj) {
entry.requested = obj;
}
function setUserInput(obj) {
entry.user_input = obj;
}
function setPrompt(p) {
if (typeof p === "string" && p.trim().length > 0) entry.prompt = p;
}
function setBackendReturned(obj) {
entry.backendReturned = obj;
}
function setPostProcessed(obj) {
entry.postProcessed = obj;
}
function setExtras(obj) {
entry.extras = { ...entry.extras || {}, ...obj };
}
function setInferenceTime(ms) {
entry.inference_time_ms = ms;
}
function setError(err) {
let message = "unknown error";
let status = void 0;
if (typeof err === "string") message = err;
else if (err && typeof err === "object") {
const anyErr = err;
message = anyErr.message || JSON.stringify(anyErr);
if (typeof anyErr.status === "number") status = anyErr.status;
}
entry.error = status ? { message, status } : { message };
}
async function write() {
try {
const logsDir2 = getLogsDir();
const filePath = path28.resolve(
logsDir2,
getPluginLogFilename().replace(/\.log$/, ".audit.jsonl")
);
await fs25.promises.mkdir(logsDir2, { recursive: true });
const block = JSON.stringify(entry, null, 2) + "\n\n";
await fs25.promises.appendFile(filePath, block, { encoding: "utf8" });
} catch (e) {
console.error(
"auditLog write failed:",
e instanceof Error ? e.message : String(e)
);
}
}
return {
requestId,
setPrompt,
setUserInput,
setRequested,
setBackendReturned,
setPostProcessed,
setExtras,
setInferenceTime,
setError,
write
};
}
var DrawThingsService = class {
name = "drawthings";
// make baseUrl public for compatibility with index.ts
baseUrl;
// change to public axios for compatibility
axios;
constructor(apiUrl = "http://127.0.0.1:7860", sharedSecretParam) {
this.baseUrl = apiUrl;
const sharedSecret = (sharedSecretParam ?? process.env.DRAWTHINGS_SHARED_SECRET) || void 0;
this.axios = axios.create({
baseURL: this.baseUrl,
timeout: 3e5,
// 5 minutes timeout (image generation may take time)
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Accept-Encoding": "gzip, deflate, br",
...sharedSecret ? { Authorization: `Bearer ${sharedSecret}` } : {}
}
});
console.info(
`DrawThingsService initialized, API location: ${this.baseUrl}`
);
}
/** Set new base URL and update axios instance */
setBaseUrl(url) {
this.baseUrl = url;
this.axios.defaults.baseURL = url;
console.info(`Updated API base URL to: ${url}`);
}
/** check API connection simplified version that just checks if API is available */
async checkApiConnection() {
try {
console.debug(`Checking API connection to: ${this.baseUrl}`);
const response = await this.axios.get("/sdapi/v1/options", {
timeout: 5e3,
validateStatus: (status) => status >= 200
});
const isConnected = response.status >= 200;
console.info(
`API connection check: ${isConnected ? "Success" : "Failed"}`
);
return isConnected;
} catch (error) {
console.error(`API connection check failed: ${error.message}`);
return false;
}
}
/** get default params */
getDefaultParams() {
return defaultParams;
}
/** generate image (text-to-image) */
async generateImage(inputParams = {}, _onProgress) {
const audit = buildAuditLogger2({ backend: this.name, mode: "txt2img" });
let overlaySource = "default";
let overlayPreset;
let overlayNote;
let effectiveModel;
let effectiveLoras;
try {
let startTime = 0;
let endTime = 0;
let params = {};
try {
const validationResult = validateImageGenerationParams(inputParams);
if (validationResult.valid) {
params = inputParams;
} else {
console.warn("parameter validation failed, use default params");
}
} catch (error) {
console.warn("parameter validation error:", error);
}
if (params.random_string && (!params.prompt || Object.keys(params).length === 1)) {
params.prompt = params.random_string;
delete params.random_string;
}
if (!params.prompt) {
params.prompt = inputParams.prompt || defaultParams.prompt;
}
let usedImageFormat = void 0;
try {
const fmt = inputParams.imageFormat;
if (params.width == null && params.height == null) {
if (fmt === "square") {
params.width = 1024;
params.height = 1024;
usedImageFormat = "square";
} else if (fmt === "landscape") {
params.width = 1024;
params.height = 768;
usedImageFormat = "landscape";
} else if (fmt === "portrait") {
params.width = 768;
params.height = 1024;
usedImageFormat = "portrait";
} else if (fmt === "16:9") {
params.width = 1024;
params.height = 576;
usedImageFormat = "16:9";
}
}
const variants = inputParams.variants;
if (typeof variants === "number") {
const v = Math.max(1, Math.min(4, Math.round(variants)));
params.batch_size = v;
params.batch_count = 1;
}
} catch {
}
const allowedKeys = new Set(Object.keys(defaultParams));
const filteredParams = {};
for (const [k, v] of Object.entries(params)) {
if (allowedKeys.has(k)) {
filteredParams[k] = v;
}
}
const modelId = inputParams.model;
const {
source,
presetName,
note,
params: overlayParams
} = getEffectiveOverlay(modelId, "txt2img");
const overlayParamsHttp = source === "custom" && overlayParams ? applyHttpCustomOverlayFixups(overlayParams) : overlayParams;
overlaySource = source;
overlayPreset = presetName;
overlayNote = note;
if (!modelId || !modelId.trim() || modelId === "auto") {
delete filteredParams.model;
}
if (overlayParamsHttp) {
console.info(
`Applying ${source} overlay for '${modelId ?? "auto"}' (txt2img)${presetName ? ` preset=${presetName}` : ""}`
);
delete filteredParams.model;
}
audit.setExtras({
overlay_source: source,
...presetName && { overlay_preset: presetName }
});
const effectiveSeed = source === "custom" && typeof overlayParamsHttp?.seed === "number" && Number.isFinite(overlayParamsHttp?.seed) ? overlayParamsHttp.seed : defaultParams.seed;
const effectiveSeedMode = source === "custom" && typeof overlayParamsHttp?.seed_mode === "string" && String(overlayParamsHttp.seed_mode).trim() ? String(overlayParamsHttp.seed_mode) : defaultParams.seed_mode;
const requestParams = {
...defaultParams,
...overlayParamsHttp || {},
...filteredParams,
seed: effectiveSeed,
seed_mode: effectiveSeedMode
};
effectiveModel = String(requestParams.model || "");
try {
const userSpecifiedLoras = Object.prototype.hasOwnProperty.call(
filteredParams,
"loras"
);
const overlaySelected = !!overlayParamsHttp;
if (userSpecifiedLoras) {
const ls = Array.isArray(filteredParams.loras) ? filteredParams.loras : [];
effectiveLoras = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else if (overlaySelected) {
const ls = Array.isArray(overlayParamsHttp?.loras) ? overlayParamsHttp.loras : [];
effectiveLoras = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else {
const ls = Array.isArray(requestParams?.loras) ? requestParams.loras : [];
effectiveLoras = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
}
} catch {
}
console.debug(`use prompt: "${requestParams.prompt}"`);
console.info("send request to Draw Things API...");
startTime = Date.now();
const response = await this.axios.post(
"/sdapi/v1/txt2img",
requestParams
);
endTime = Date.now();
if (!response.data || !response.data.images || response.data.images.length === 0) {
throw new Error("API did not return image data");
}
const imagesArr = response.data.images;
console.info(
`DrawThings: received ${imagesArr.length} image(s) from API`
);
const first = imagesArr[0];
const formattedFirst = first.startsWith("data:image/") ? first : `data:image/png;base64,${first}`;
const cleanBase64 = formattedFirst.includes(",") ? formattedFirst.split(",")[1] : formattedFirst.replace(/^data:image\/\w+;base64,/, "");
const imageBuffer = Buffer.from(cleanBase64, "base64");
console.info("image generation success");
try {
audit.setUserInput({
width: inputParams?.width,
height: inputParams?.height,
imageFormat: inputParams?.imageFormat
});
} catch {
}
try {
audit.setPrompt(String(requestParams.prompt || ""));
audit.setRequested({
source: "http.body",
model: String(requestParams.model || ""),
width: Number(requestParams.width),
height: Number(requestParams.height),
steps: Number(requestParams.steps)
});
} catch {
}
let backendW;
let backendH;
try {
const meta = await getSize(imageBuffer);
backendW = meta.width;
backendH = meta.height;
} catch {
}
audit.setBackendReturned({ width: backendW, height: backendH });
audit.setPostProcessed({ width: backendW, height: backendH });
audit.setInferenceTime(endTime - startTime);
const result = {
isError: false,
imageData: formattedFirst,
imageBuffer,
images: imagesArr.map(
(img) => img.startsWith("data:image/") ? img : `data:image/png;base64,${img}`
),
metadata: {
alt: `Image generated from prompt: ${requestParams.prompt}`,
inference_time_ms: endTime - startTime,
model: effectiveModel,
width: Number(requestParams.width),
height: Number(requestParams.height),
requested_dimensions: {
width: Number(requestParams.width),
height: Number(requestParams.height)
},
image_format: usedImageFormat,
steps: Number(requestParams.steps),
seed: typeof requestParams.seed === "number" && Number.isFinite(requestParams.seed) ? requestParams.seed : void 0,
seed_mode: (() => {
const sm = requestParams.seed_mode ?? requestParams.seedMode;
return typeof sm === "string" && sm.trim() ? sm : void 0;
})(),
seed_source: source === "custom" && typeof overlayParamsHttp?.seed === "number" && Number.isFinite(overlayParamsHttp?.seed) ? "custom" : "default",
seed_mode_source: source === "custom" && typeof overlayParamsHttp?.seed_mode === "string" && String(overlayParamsHttp.seed_mode).trim() ? "custom" : "default",
prompt_used: String(requestParams.prompt || ""),
prompt_origin: typeof inputParams.prompt === "string" && inputParams.prompt.trim() ? "user" : "default:drawthings:txt2img",
transport: "http",
drawthings_params: requestParams,
variantsReturned: imagesArr.length,
// Overlay source tracking for audit
overlay_source: overlaySource,
...overlayPreset && { overlay_preset: overlayPreset },
...overlayNote && { overlay_note: overlayNote },
defaults_used: "defaultParamsDrawThingsTxt2Img",
overlay_lookup_mode: "txt2img",
strength_used: typeof requestParams.strength === "number" && Number.isFinite(requestParams.strength) ? Number(requestParams.strength) : void 0,
steps_used: typeof requestParams.steps === "number" && Number.isFinite(requestParams.steps) ? Number(requestParams.steps) : void 0,
sampler_used: typeof requestParams.sampler === "string" && String(requestParams.sampler).trim() ? String(requestParams.sampler) : void 0,
guidance_scale_used: typeof requestParams.guidance_scale === "number" && Number.isFinite(requestParams.guidance_scale) ? Number(requestParams.guidance_scale) : void 0,
...effectiveLoras && effectiveLoras.length > 0 && { loras_used: effectiveLoras }
}
};
return result;
} catch (error) {
const errMsg = error instanceof Error ? error.message : String(error);
console.error(`image generation error: ${errMsg}`);
const axiosError = error;
let status = void 0;
let rawBody = void 0;
if (axiosError && axiosError.response) {
status = axiosError.response.status;
const data = axiosError.response.data;
if (typeof data === "string") rawBody = data;
else if (data !== void 0) {
try {
rawBody = JSON.stringify(data);
} catch {
rawBody = String(data);
}
}
}
if (!rawBody) {
if (typeof axiosError?.message === "string")
rawBody = axiosError.message;
else if (error instanceof Error && typeof error.message === "string")
rawBody = error.message;
else rawBody = "unknown error";
}
return {
isError: true,
status,
errorMessage: rawBody
};
}
}
/** generate image (image-to-image) */
async generateImageImg2Img(inputParams = {}, sourceBuffer, _onProgress, _maskBuffer) {
const audit = buildAuditLogger2({ backend: this.name, mode: "img2img" });
let overlaySource = "default";
let overlayPreset;
let overlayNote;
let effectiveModel;
let effectiveLoras;
try {
const i2iProfile = inputParams?._dt_i2i_profile;
const baseDefaults = i2iProfile === "zoom" ? defaultParamsZoom : i2iProfile === "restore" ? defaultParamsImg2Img3 : i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint" ? defaultParamsImg2Img2 : defaultParamsImg2Img;
const baseLimits = i2iProfile === "restore" || i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint" ? drawthingsLimits : drawthingsLimits;
let startTime = 0;
let endTime = 0;
let params = {};
try {
const validationResult = validateImageGenerationParams(inputParams);
if (validationResult.valid) {
params = inputParams;
}
} catch {
}
if (params.random_string && (!params.prompt || Object.keys(params).length === 1)) {
params.prompt = params.random_string;
delete params.random_string;
}
if (!params.prompt) {
params.prompt = inputParams.prompt || baseDefaults.prompt;
}
let usedImageFormat = void 0;
try {
const fmt = inputParams.imageFormat;
if (params.width == null && params.height == null) {
if (fmt === "square") {
params.width = 1024;
params.height = 1024;
usedImageFormat = "square";
} else if (fmt === "landscape") {
params.width = 1024;
params.height = 768;
usedImageFormat = "landscape";
} else if (fmt === "portrait") {
params.width = 768;
params.height = 1024;
usedImageFormat = "portrait";
} else if (fmt === "16:9") {
params.width = 1024;
params.height = 576;
usedImageFormat = "16:9";
}
}
const variants = inputParams.variants;
if (typeof variants === "number") {
const v = Math.max(1, Math.min(4, Math.round(variants)));
params.batch_size = v;
params.batch_count = 1;
}
} catch {
}
const allowedKeys = new Set(Object.keys(baseDefaults));
const filteredParams = {};
for (const [k, v] of Object.entries(params)) {
if (allowedKeys.has(k)) filteredParams[k] = v;
}
const modelId = i2iProfile === "zoom" ? void 0 : inputParams.model;
const overlayMode = i2iProfile === "zoom" ? "zoom" : i2iProfile === "restore" || i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint" ? i2iProfile : "img2img";
const {
source,
presetName,
note,
params: overlayParams
} = getEffectiveOverlay(modelId, overlayMode === "inpaint" || overlayMode === "outpaint" ? "edit" : overlayMode);
const overlayParamsHttp = source === "custom" && overlayParams ? applyHttpCustomOverlayFixups(overlayParams) : overlayParams;
overlaySource = source;
overlayPreset = presetName;
overlayNote = note;
if (!modelId || !modelId.trim() || modelId === "auto") {
delete filteredParams.model;
}
if (overlayParamsHttp) {
console.info(
`Applying ${source} overlay for '${modelId ?? "auto"}' (img2img)${presetName ? ` preset=${presetName}` : ""}`
);
delete filteredParams.model;
}
audit.setExtras({
overlay_source: source,
...presetName && { overlay_preset: presetName }
});
let initPng = sourceBuffer;
let srcW;
let srcH;
try {
initPng = await toPng(sourceBuffer);
const meta = await getSize(initPng);
srcW = meta.width;
srcH = meta.height;
} catch {
}
const initB64 = initPng.toString("base64");
const requestParams = {
...baseDefaults,
...overlayParamsHttp || {},
...filteredParams,
// Seed policy: allow Custom Configs to override (incl. -1); otherwise keep defaults.
seed: source === "custom" && typeof overlayParamsHttp?.seed === "number" && Number.isFinite(overlayParamsHttp?.seed) ? overlayParamsHttp.seed : baseDefaults.seed,
// Seed mode policy mirrors seed: allow Custom Configs to override; otherwise keep defaults.
seed_mode: source === "custom" && typeof overlayParamsHttp?.seed_mode === "string" && String(overlayParamsHttp.seed_mode).trim() ? String(overlayParamsHttp.seed_mode) : baseDefaults.seed_mode,
init_images: [initB64]
};
const defaultsUsed = i2iProfile === "restore" ? "defaultParamsDrawThingsRestore" : i2iProfile === "edit" ? "defaultParamsDrawThingsEdit" : "defaultParamsDrawThingsImg2Img";
const overlayLookupMode = overlayMode;
effectiveModel = String(requestParams.model || "");
try {
const userSpecifiedLoras = Object.prototype.hasOwnProperty.call(
filteredParams,
"loras"
);
const overlaySelected = !!overlayParamsHttp;
if (userSpecifiedLoras) {
const ls = Array.isArray(filteredParams.loras) ? filteredParams.loras : [];
effectiveLoras = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else if (overlaySelected) {
const ls = Array.isArray(overlayParamsHttp?.loras) ? overlayParamsHttp.loras : [];
effectiveLoras = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else {
const ls = Array.isArray(requestParams?.loras) ? requestParams.loras : [];
effectiveLoras = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
}
} catch {
}
const userReqW = (() => {
const v = filteredParams?.width ?? params?.width;
return typeof v === "number" && Number.isFinite(v) ? Math.round(v) : void 0;
})();
const userReqH = (() => {
const v = filteredParams?.height ?? params?.height;
return typeof v === "number" && Number.isFinite(v) ? Math.round(v) : void 0;
})();
if (srcW && srcH) {
requestParams.original_width = srcW;
requestParams.original_height = srcH;
}
{
const hasW = typeof requestParams.width === "number" && Number.isFinite(requestParams.width);
const hasH = typeof requestParams.height === "number" && Number.isFinite(requestParams.height);
if (!hasW)
requestParams.width = userReqW ?? srcW;
if (!hasH)
requestParams.height = userReqH ?? srcH;
const hasTW = typeof requestParams.target_width === "number" && Number.isFinite(requestParams.target_width);
const hasTH = typeof requestParams.target_height === "number" && Number.isFinite(requestParams.target_height);
if (!hasTW)
requestParams.target_width = requestParams.width;
if (!hasTH)
requestParams.target_height = requestParams.height;
}
{
const needs = inputParams?._dt_needs_upscaler;
if (typeof needs !== "boolean") {
throw new Error(
"Invariant failed: _dt_needs_upscaler must be provided by core for img2img"
);
}
if (needs && i2iProfile !== "zoom" && baseLimits.upscaleMethod !== "zoom-pass") {
requestParams.upscaler = baseLimits.upscaler;
requestParams.upscaler_scale = baseLimits.upscalerScaleFactor;
console.info(`DT img2img upscaler enabled (core)`);
} else {
requestParams.upscaler = null;
requestParams.upscaler_scale = 0;
console.info(`DT img2img upscaler disabled (core)`);
}
}
console.info(
`DT img2img size set: width=${requestParams.width}, height=${requestParams.height}, original_width=${requestParams.original_width}, original_height=${requestParams.original_height}, target_width=${requestParams.target_width}, target_height=${requestParams.target_height}, upscaler=${requestParams.upscaler ?? "-"}, upscaler_scale=${requestParams.upscaler_scale ?? "-"}`
);
console.info("send request to Draw Things API (img2img)...");
startTime = Date.now();
const response = await this.axios.post(
"/sdapi/v1/img2img",
requestParams
);
endTime = Date.now();
if (!response.data || !response.data.images || response.data.images.length === 0) {
throw new Error("API did not return image data");
}
const imagesArr = response.data.images;
const first = imagesArr[0];
const formattedFirst = first.startsWith("data:image/") ? first : `data:image/png;base64,${first}`;
const cleanBase64 = formattedFirst.includes(",") ? formattedFirst.split(",")[1] : formattedFirst.replace(/^data:image\/\w+;base64,/, "");
const imageBuffer = Buffer.from(cleanBase64, "base64");
try {
audit.setPrompt(String(requestParams.prompt || ""));
audit.setRequested({
source: "http.body",
model: String(requestParams.model || ""),
width: Number(requestParams.width),
height: Number(requestParams.height),
steps: Number(requestParams.steps),
original_width: Number(requestParams.original_width),
original_height: Number(requestParams.original_height),
target_width: Number(requestParams.target_width),
target_height: Number(requestParams.target_height)
});
if (srcW && srcH) {
audit.setExtras({ srcWidth: srcW, srcHeight: srcH });
}
} catch {
}
let backendW;
let backendH;
try {
const meta = await getSize(imageBuffer);
backendW = meta.width;
backendH = meta.height;
} catch {
}
audit.setBackendReturned({ width: backendW, height: backendH });
audit.setPostProcessed({ width: backendW, height: backendH });
audit.setInferenceTime(endTime - startTime);
const result = {
isError: false,
imageData: formattedFirst,
imageBuffer,
images: imagesArr.map(
(img) => img.startsWith("data:image/") ? img : `data:image/png;base64,${img}`
),
metadata: {
alt: `Image-to-image from prompt: ${requestParams.prompt}`,
inference_time_ms: endTime - startTime,
model: effectiveModel,
width: Number(requestParams.width),
height: Number(requestParams.height),
requested_dimensions: {
width: Number(requestParams.width),
height: Number(requestParams.height)
},
image_format: usedImageFormat,
steps: Number(requestParams.steps),
seed: typeof requestParams.seed === "number" && Number.isFinite(requestParams.seed) ? requestParams.seed : void 0,
seed_mode: (() => {
const sm = requestParams.seed_mode ?? requestParams.seedMode;
return typeof sm === "string" && sm.trim() ? sm : void 0;
})(),
prompt_used: String(requestParams.prompt || ""),
prompt_origin: typeof inputParams.prompt === "string" && inputParams.prompt.trim() ? "user" : "default:drawthings:img2img",
transport: "http",
// Overlay source tracking for audit
overlay_source: overlaySource,
...overlayPreset && { overlay_preset: overlayPreset },
...overlayNote && { overlay_note: overlayNote },
defaults_used: defaultsUsed,
overlay_lookup_mode: overlayLookupMode,
i2i_profile: i2iProfile,
strength_used: typeof requestParams.strength === "number" && Number.isFinite(requestParams.strength) ? requestParams.strength : void 0,
steps_used: typeof requestParams.steps === "number" && Number.isFinite(requestParams.steps) ? requestParams.steps : void 0,
sampler_used: typeof requestParams.sampler === "string" && String(requestParams.sampler).trim() ? String(requestParams.sampler) : void 0,
guidance_scale_used: typeof requestParams.guidance_scale === "number" && Number.isFinite(requestParams.guidance_scale) ? requestParams.guidance_scale : void 0,
...effectiveLoras && effectiveLoras.length > 0 && { loras_used: effectiveLoras }
}
};
return result;
} catch (error) {
const errMsg = error instanceof Error ? error.message : String(error);
console.error(`image2image generation error: ${errMsg}`);
const axiosError = error;
let status = void 0;
let rawBody = void 0;
if (axiosError && axiosError.response) {
status = axiosError.response.status;
const data = axiosError.response.data;
if (typeof data === "string") rawBody = data;
else if (data !== void 0) {
try {
rawBody = JSON.stringify(data);
} catch {
rawBody = String(data);
}
}
}
if (!rawBody) {
if (typeof axiosError?.message === "string")
rawBody = axiosError.message;
else if (error instanceof Error && typeof error.message === "string")
rawBody = error.message;
else rawBody = "unknown error";
}
return { isError: true, status, errorMessage: rawBody };
}
}
};
// src/services/drawThingsGrpcService.ts
import path29 from "path";
import fs26 from "fs";
import * as grpc2 from "@grpc/grpc-js";
import * as protoLoader from "@grpc/proto-loader";
import crypto2 from "crypto";
import { spawnSync } from "child_process";
import os8 from "os";
// src/helpers/tensorDecoderProfile.ts
function resolveTensorDecoderProfile(model) {
const modelId = String(model ?? "").trim().toLowerCase();
const capabilityKey = Object.keys(IMAGE_MODEL_CAPABILITY_MAP).find((key) => key.toLowerCase() === modelId) ?? Object.entries(IMAGE_MODEL_CAPABILITY_MAP).find(
([, capabilities]) => capabilities.modelFilenames?.some((filename) => filename.toLowerCase() === modelId)
)?.[0] ?? getCapabilityKeyForPreset(modelId);
if (capabilityKey === "flux-2-klein" || capabilityKey === "flux-3-klein") return "flux2-latent32";
if (capabilityKey === "qwen-image-1.0" || capabilityKey === "qwen-image-2.1" || capabilityKey === "qwen-image-2.1-turbo" || capabilityKey === "qwen-edit" || capabilityKey === "qwen-image-edit-2509" || capabilityKey === "qwen-image-edit-2511") {
return "qwen-argb";
}
return "direct-rgb";
}
// src/services/drawThingsGrpcService.ts
var __rootStartDir;
function setDrawThingsServiceRootStart(dir) {
__rootStartDir = dir && dir.trim() ? dir : void 0;
}
function __svcDir() {
if (__rootStartDir) return __rootStartDir;
try {
const p = process.argv && process.argv[1] ? process.argv[1] : process.cwd();
return path29.dirname(p);
} catch {
return process.cwd();
}
}
function __resolveProjectRootFrom(startDir) {
try {
let dir = startDir;
for (let i = 0; i < 50; i++) {
try {
const hasManifest = fs26.existsSync(path29.join(dir, "manifest.json"));
const hasPkg = fs26.existsSync(path29.join(dir, "package.json"));
if (hasManifest || hasPkg) return dir;
} catch {
}
const parent = path29.dirname(dir);
if (parent === dir) break;
dir = parent;
}
} catch {
}
{
let dir = startDir;
for (let i = 0; i < 20; i++) {
if (path29.basename(dir) === "dist") return path29.dirname(dir);
const parent = path29.dirname(dir);
if (parent === dir) break;
dir = parent;
}
}
{
let dir = startDir;
for (let i = 0; i < 5; i++) {
if (path29.basename(dir) === "src") return path29.dirname(dir);
const parent = path29.dirname(dir);
if (parent === dir) break;
dir = parent;
}
}
return startDir;
}
function __projectRoot() {
return __resolveProjectRootFrom(__svcDir());
}
function __logsDir() {
const dir = path29.join(__projectRoot(), "logs");
try {
if (!fs26.existsSync(dir)) fs26.mkdirSync(dir, { recursive: true });
} catch {
}
return dir;
}
function clientName() {
try {
return getPluginLogFilename().replace(/\.log$/, "");
} catch {
return "draw-things-plugin";
}
}
function logFile2(msg) {
const line = `${logTimestamp()} - ${requestLogPrefix()}${msg}
`;
try {
fs26.appendFileSync(path29.join(__logsDir(), getPluginLogFilename()), line);
} catch {
}
}
function logErr(msg) {
const line = `${logTimestamp()} - ERROR: ${msg}
`;
try {
fs26.appendFileSync(path29.join(__logsDir(), "error.log"), line);
} catch {
}
try {
console.error(`[${clientName()}] ${msg}`);
} catch {
}
}
function getTensorHelpersMode() {
const raw = String(process.env.DT_TENSOR_HELPERS_MODE || "auto").trim().toLowerCase();
if (raw === "ts" || raw === "node" || raw === "js") return "ts";
if (raw === "bin" || raw === "binary" || raw === "native") return "bin";
return "auto";
}
function buildTensorHelperCandidates(projectRoot, helperName, envCmd) {
const jsPath = path29.resolve(
projectRoot,
"dist",
"helpers",
`${helperName}.js`
);
const binDistPath = path29.resolve(projectRoot, "dist", "helpers", helperName);
const mode = getTensorHelpersMode();
const ordered = mode === "bin" ? [envCmd, binDistPath, jsPath] : [envCmd, jsPath, binDistPath];
return ordered.filter(Boolean);
}
function logToolSelection(context, tool3) {
if (!tool3) {
logFile2(`[tool] ${context} not found (no decoder/encoder available)`);
return;
}
logFile2(
`[tool] ${context} origin=${tool3.origin} impl=${tool3.impl} path=${tool3.display}`
);
}
function resolveExternalToolCandidates(projectRoot, helperName, envCmd) {
const candidates = buildTensorHelperCandidates(
projectRoot,
helperName,
envCmd
);
const tools = [];
for (const c of candidates) {
try {
const abs = path29.isAbsolute(c) ? c : path29.resolve(projectRoot, c);
if (!fs26.existsSync(abs)) continue;
const origin = c === envCmd ? "env" : "auto";
if (abs.endsWith(".js")) {
tools.push({
cmd: process.execPath,
argsPrefix: [abs],
display: abs,
impl: "ts",
origin
});
continue;
}
try {
const st = fs26.statSync(abs);
if ((st.mode & 73) === 0) {
try {
fs26.chmodSync(abs, 493);
} catch {
}
}
} catch {
}
tools.push({
cmd: abs,
argsPrefix: [],
display: abs,
impl: "mac-bin",
origin
});
} catch {
}
}
return tools;
}
function logToolCandidates(context, tools) {
if (!tools.length) {
logFile2(`[tool] ${context} not found (no decoder/encoder available)`);
return;
}
logFile2(
`[tool] ${context} candidates=${tools.length} primary=${tools[0].display}`
);
}
function logTensorSource(context, finals, preview, model) {
const describe = (b) => b.length >= 68 ? `${b.readUInt32LE(28)}x${b.readUInt32LE(24)}x${b.readUInt32LE(32)}ch bytes=${b.length}` : `bytes=${b.length}`;
const finalInfo = finals.length ? finals.map(describe).join(" | ") : "none";
const previewInfo = preview ? describe(preview) : "none";
const source = finals.length ? "final" : preview ? "PREVIEW-FALLBACK" : "empty";
logFile2(
`[result-source] ${context} model=${model ?? "?"} source=${source} final=[${finalInfo}] preview=[${previewInfo}]`
);
}
function normalizeNumFrames(n) {
if (n <= 1) return { value: 1 };
if ((n - 1) % 32 === 0) return { value: n };
if (n % 32 === 0) return { value: n + 1 };
const rounded = Math.round(n / 32) * 32 + 1;
const clamped = Math.max(33, Math.min(641, rounded));
return {
value: clamped,
hint: `numFrames adjusted to ${clamped} (must be multiple of 32 + 1).`
};
}
var DrawThingsGrpcService = class {
name = "drawthings";
baseUrl;
// target address host:port
client = null;
serviceName;
methodGenerate;
grpcCompression;
tlsMode = "auto";
currentSecurity = "unknown";
constructor(target2) {
this.baseUrl = target2 || process.env.DRAWTHINGS_GRPC_TARGET || `127.0.0.1:${process.env.DRAWTHINGS_GRPC_PORT || 7859}`;
this.serviceName = process.env.DRAWTHINGS_GRPC_SERVICE || "ImageGenerationService";
this.methodGenerate = "generateImage";
this.grpcCompression = (process.env.DRAWTHINGS_GRPC_COMPRESSION || "identity").toLowerCase();
this.loadClient();
}
registerInventoryFetcher() {
const client = this.client;
registerInventoryFetcher(echoFetcherForClient(client, clientName(), process.env.DRAWTHINGS_SHARED_SECRET));
}
setBaseUrl(url) {
this.baseUrl = url;
this.loadClient();
}
loadClient() {
try {
const projectRoot = __projectRoot();
const resolveProtoPath = () => {
const fromEnv = process.env.DRAWTHINGS_GRPC_PROTO;
if (fromEnv && fs26.existsSync(fromEnv)) return fromEnv;
const candidates = [
path29.resolve(projectRoot, "dist", "interfaces", "imageService.proto"),
path29.resolve(projectRoot, "src", "interfaces", "imageService.proto"),
path29.resolve(
projectRoot,
"dist",
"src",
"interfaces",
"imageService.proto"
),
path29.resolve(__svcDir(), "..", "interfaces", "imageService.proto")
];
for (const p of candidates) if (fs26.existsSync(p)) return p;
return candidates[0];
};
const protoPath = resolveProtoPath();
const opts = {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
};
const packageDef = protoLoader.loadSync(protoPath, opts);
const grpcObj = grpc2.loadPackageDefinition(packageDef) || {};
const SvcCtor = grpcObj[this.serviceName];
if (!SvcCtor) {
console.error(
`[DrawThingsGrpcService] Service not found: ${this.serviceName} (proto: ${protoPath})`
);
logErr(
`gRPC service not found: ${this.serviceName} (proto: ${protoPath})`
);
try {
const available = Object.keys(grpcObj || {});
console.error(
`[DrawThingsGrpcService] Available services: ${available.join(
", "
)}`
);
logFile2(`[gRPC] Available services: ${available.join(", ")}`);
} catch {
}
this.client = null;
return;
}
const channelOptions = {
"grpc.max_receive_message_length": 64 * 1024 * 1024,
"grpc.max_send_message_length": 64 * 1024 * 1024,
"grpc.ssl_target_name_override": "localhost",
"grpc.default_authority": "localhost"
};
const loadRootCAs = () => {
const tlsDirs = [
path29.resolve(projectRoot, "src", "interfaces", "tls"),
path29.resolve(projectRoot, "dist", "interfaces", "tls"),
path29.resolve(__svcDir(), "..", "interfaces", "tls")
];
const baseDir = tlsDirs.find((d) => {
try {
return fs26.existsSync(d);
} catch {
return false;
}
});
if (!baseDir) return void 0;
const serverPath = path29.join(baseDir, "server_crt.crt");
const rootPath = path29.join(baseDir, "root_ca.crt");
if (!fs26.existsSync(serverPath) || !fs26.existsSync(rootPath))
return void 0;
const serverTxt = fs26.readFileSync(serverPath, "utf8").replace(/\r\n/g, "\n").trim();
const rootTxt = fs26.readFileSync(rootPath, "utf8").replace(/\r\n/g, "\n").trim();
if (!/-----BEGIN CERTIFICATE-----/.test(serverTxt) || !/-----BEGIN CERTIFICATE-----/.test(rootTxt))
return void 0;
const bundle = `${serverTxt}
${rootTxt}
`;
try {
const out = path29.join(baseDir, "server.pem");
const prev = fs26.existsSync(out) ? fs26.readFileSync(out, "utf8").replace(/\r\n/g, "\n").trim() : "";
if (prev !== bundle.trim()) {
fs26.writeFileSync(out, bundle, "utf8");
console.log(`[TLS] Generated bundle: ${out}`);
} else {
console.log(`[TLS] Using existing bundle: ${out}`);
}
} catch {
}
return Buffer.from(bundle, "utf8");
};
const creds = grpc2.credentials.createSsl(loadRootCAs());
this.client = new SvcCtor(this.baseUrl, creds, channelOptions);
this.registerInventoryFetcher();
this.currentSecurity = "tls";
try {
globalThis.__DT_GRPC_TLS_MODE__ = this.tlsMode || "auto";
globalThis.__DT_GRPC_TLS_SELECTED__ = this.currentSecurity;
} catch {
}
try {
const proto = Object.getPrototypeOf(this.client) || {};
const methods = Object.getOwnPropertyNames(proto).filter(
(k) => typeof this.client[k] === "function" && k !== "constructor"
);
console.log(
`[DrawThingsGrpcService] client methods: ${methods.join(", ")}`
);
logFile2(`[gRPC] client methods: ${methods.join(", ")}`);
} catch {
}
} catch (e) {
console.error(
`[DrawThingsGrpcService] loadClient error: ${e instanceof Error ? e.message : String(e)}`
);
logErr(`loadClient error: ${e instanceof Error ? e.message : String(e)}`);
this.client = null;
}
}
async checkApiConnection() {
if (!this.client) return false;
try {
const echo = this.client["echo"]?.bind(this.client);
if (typeof echo === "function") {
const sharedSecret = process.env.DRAWTHINGS_SHARED_SECRET;
const req = { name: clientName() };
if (sharedSecret) req.sharedSecret = sharedSecret;
await new Promise((resolve, reject) => {
const started = Date.now();
echo(req, (err, resp) => {
if (err) return reject(err);
primeInventoryFromEcho(resp, Date.now() - started);
resolve();
});
});
return true;
}
} catch (e) {
try {
const msg = e && e.message ? String(e.message) : String(e);
const code = e?.code;
console.error(
`[gRPC check] echo failed (mode=${this.currentSecurity}) code=${code ?? "?"} msg=${msg}`
);
logErr(
`gRPC echo failed (mode=${this.currentSecurity}) code=${code ?? "?"} msg=${msg}`
);
} catch {
}
if (this.tlsMode === "auto") {
try {
const __dirname2 = __svcDir();
const projectRoot = __resolveProjectRootFrom(__dirname2);
const protoPath = (() => {
const fromEnv = process.env.DRAWTHINGS_GRPC_PROTO;
if (fromEnv && fs26.existsSync(fromEnv)) return fromEnv;
const c1 = path29.resolve(
projectRoot,
"src",
"interfaces",
"imageService.proto"
);
if (fs26.existsSync(c1)) return c1;
const c3 = path29.resolve(
projectRoot,
"dist",
"interfaces",
"imageService.proto"
);
if (fs26.existsSync(c3)) return c3;
return c1;
})();
const packageDef = protoLoader.loadSync(protoPath, {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
});
const grpcObj = grpc2.loadPackageDefinition(packageDef) || {};
const SvcCtor = grpcObj[this.serviceName];
if (SvcCtor) {
const root = (() => {
const pieces = [];
const tlsDirCandidates = [
path29.resolve(projectRoot, "src", "interfaces", "tls"),
path29.resolve(projectRoot, "dist", "interfaces", "tls")
];
const names = [
"ca.crt",
"ca.pem",
"server.crt",
"server.pem",
"rootCA.crt",
"rootCA.pem"
];
for (const d of tlsDirCandidates) {
for (const n of names) {
try {
const p = path29.join(d, n);
if (fs26.existsSync(p)) pieces.push(fs26.readFileSync(p));
} catch {
}
}
}
return pieces.length ? Buffer.concat(pieces) : void 0;
})();
const hostname = String(this.baseUrl || "").split(":")[0] || "localhost";
const candidateSet = /* @__PURE__ */ new Set([
hostname,
"localhost",
"server",
"drawthings",
"draw-things"
]);
try {
const { X509Certificate } = await import("crypto");
const protoDirs = [
path29.resolve(projectRoot, "src", "interfaces", "tls"),
path29.resolve(projectRoot, "dist", "interfaces", "tls")
];
const certFiles = [
"server_crt.crt",
"server_cert.crt",
"server.crt",
"server.pem",
"root_ca.crt",
"rootCA.crt",
"ca.crt",
"ca.pem"
];
for (const d of protoDirs) {
for (const f of certFiles) {
const p = path29.join(d, f);
try {
if (!fs26.existsSync(p)) continue;
const txt = fs26.readFileSync(p, "utf8");
const blocks = txt.split(/-----END CERTIFICATE-----/g).map(
(b) => b.includes("BEGIN CERTIFICATE") ? b + "-----END CERTIFICATE-----\n" : ""
).filter((b) => b.trim().length > 0);
for (const pem of blocks) {
try {
const x = new X509Certificate(pem);
const subj = x.subject || "";
const san = x.subjectAltName || "";
const m = subj.match(/CN=([^,\n]+)/);
if (m && m[1]) candidateSet.add(m[1].trim());
if (san) {
san.split(/[,]/).map((s) => s.trim()).filter((s) => /^DNS:/i.test(s)).map((s) => s.replace(/^DNS:\s*/i, "")).forEach(
(dname) => candidateSet.add(dname)
);
}
} catch {
}
}
} catch {
}
}
}
} catch {
}
const authCandidates = Array.from(candidateSet);
for (const auth of authCandidates) {
const channelOptions = {
"grpc.max_receive_message_length": 64 * 1024 * 1024,
"grpc.max_send_message_length": 64 * 1024 * 1024,
"grpc.ssl_target_name_override": auth,
"grpc.default_authority": auth
};
const creds = grpc2.credentials.createSsl(root);
this.client = new SvcCtor(this.baseUrl, creds, channelOptions);
this.registerInventoryFetcher();
this.currentSecurity = "tls";
try {
globalThis.__DT_GRPC_TLS_SELECTED__ = this.currentSecurity;
} catch {
}
try {
const echo2 = this.client["echo"]?.bind(this.client);
if (typeof echo2 === "function") {
const sharedSecret = process.env.DRAWTHINGS_SHARED_SECRET;
const req = { name: clientName() };
if (sharedSecret) req.sharedSecret = sharedSecret;
await new Promise((resolve2, reject2) => {
echo2(
req,
(err2) => err2 ? reject2(err2) : resolve2()
);
});
return true;
}
} catch (e2) {
try {
const msg = e2 && e2.message ? String(e2.message) : String(e2);
const code = e2?.code;
console.error(
`[gRPC check] TLS echo failed (authority=${auth}) code=${code ?? "?"} msg=${msg}`
);
} catch {
}
}
}
{
const channelOptions = {
"grpc.max_receive_message_length": 64 * 1024 * 1024,
"grpc.max_send_message_length": 64 * 1024 * 1024
};
const creds = grpc2.credentials.createInsecure();
this.client = new SvcCtor(this.baseUrl, creds, channelOptions);
this.registerInventoryFetcher();
this.currentSecurity = "insecure";
try {
globalThis.__DT_GRPC_TLS_SELECTED__ = this.currentSecurity;
} catch (e3) {
try {
const msg = e3 && e3.message ? String(e3.message) : String(e3);
const code = e3?.code;
console.error(
`[gRPC check] insecure echo retry failed code=${code ?? "?"} msg=${msg}`
);
} catch {
}
}
try {
const echo3 = this.client["echo"]?.bind(this.client);
if (typeof echo3 === "function") {
const sharedSecret = process.env.DRAWTHINGS_SHARED_SECRET;
const req = { name: clientName() };
if (sharedSecret) req.sharedSecret = sharedSecret;
await new Promise((resolve3, reject3) => {
echo3(
req,
(err3) => err3 ? reject3(err3) : resolve3()
);
});
return true;
}
} catch {
}
}
}
} catch {
}
}
}
const deadline = new Date(Date.now() + 8e3);
return new Promise((resolve) => {
try {
this.client.waitForReady(deadline, (err) => {
resolve(!err);
});
} catch {
resolve(false);
}
});
}
/** The generate RPC; every stream it returns is cancelled when the current render's cancel signal fires. */
cancellableGenerateCall() {
const rpc = this.client[this.methodGenerate]?.bind(this.client);
if (typeof rpc !== "function") return void 0;
return (...args) => {
const stream = rpc(...withProxyMarks(args, clientName()));
const signal = getCancelSignal();
if (signal) {
const cancel = () => stream.cancel?.();
if (signal.aborted) setImmediate(cancel);
else signal.addEventListener("abort", cancel, { once: true });
}
return stream;
};
}
ensureClient() {
if (!this.client)
throw new Error(
"gRPC client not configured. Set DRAWTHINGS_GRPC_* envs."
);
}
toBackendError(e) {
let status = void 0;
let msg = "unknown error";
if (e && typeof e === "object") {
if (typeof e.code === "number") status = e.code;
if (typeof e.details === "string") msg = e.details;
else if (typeof e.message === "string") msg = e.message;
}
return { isError: true, status, errorMessage: msg };
}
async generateImage(inputParams = {}, onProgress) {
try {
const __tmpDirs = [];
const __registerTmp = (d) => {
try {
__tmpDirs.push(d);
} catch {
}
};
const __cleanupTmp = () => {
for (const d of __tmpDirs) {
try {
fs26.rmSync(d, { recursive: true, force: true });
} catch {
}
}
};
const isVideoTxt2Vid = inputParams?._dt_video_mode === "txt2vid";
const baseDefaults = isVideoTxt2Vid ? defaultParamsText2Video : defaultParams;
const baseOverlayMode = isVideoTxt2Vid ? "txt2vid" : "txt2img";
const audit = buildAuditLogger({ backend: this.name, mode: baseOverlayMode });
this.ensureClient();
let configBytes = void 0;
let payloadWidth;
let payloadHeight;
let payloadSteps;
let payloadSeed;
let payloadSeedMode;
let payloadModel;
let payloadNumFrames = 1;
let payloadFps = 24;
let requiredModelFile;
let requiredLoraFiles;
let overlaySource = "default";
let overlayPreset;
let overlayNote;
let seedSource = "default";
let seedModeSource = "default";
let defaultsUsed;
let overlayLookupMode;
let strengthUsed;
let stepsUsed;
let samplerUsed;
let guidanceScaleUsed;
let shiftUsed;
let resolutionDependentShiftUsed;
let compressionArtifactsUsed;
let compressionArtifactsQualityUsed;
let params = {};
try {
const r = validateImageGenerationParams(inputParams);
if (r.valid) params = inputParams;
} catch {
}
if (params.random_string && (!params.prompt || Object.keys(params).length === 1)) {
params.prompt = params.random_string;
delete params.random_string;
}
if (!params.prompt)
params.prompt = inputParams.prompt || baseDefaults.prompt;
const promptOriginTxt = typeof inputParams?.prompt === "string" && String(inputParams.prompt).trim() ? "user" : `default:drawthings:${baseOverlayMode}`;
let usedImageFormat = void 0;
try {
const fmt = inputParams.imageFormat;
if (params.width == null && params.height == null) {
if (fmt === "square") {
params.width = 1024;
params.height = 1024;
usedImageFormat = "square";
} else if (fmt === "landscape") {
params.width = 1024;
params.height = 768;
usedImageFormat = "landscape";
} else if (fmt === "portrait") {
params.width = 768;
params.height = 1024;
usedImageFormat = "portrait";
} else if (fmt === "16:9") {
params.width = 1024;
params.height = 576;
usedImageFormat = "16:9";
}
}
const variants = inputParams.variants;
if (typeof variants === "number") {
const v = Math.max(1, Math.min(4, Math.round(variants)));
params.batch_size = v;
params.batch_count = 1;
}
if (isVideoTxt2Vid) {
const rawNumFrames = inputParams.numFrames;
if (typeof rawNumFrames === "number" && rawNumFrames > 1) {
const normalized = normalizeNumFrames(rawNumFrames);
params.num_frames = normalized.value;
if (normalized.hint) console.info(`[txt2vid] ${normalized.hint}`);
}
}
} catch {
}
try {
const allowedKeys = new Set(Object.keys(baseDefaults));
const filtered = {};
for (const [k, v] of Object.entries(params)) {
if (allowedKeys.has(k)) filtered[k] = v;
}
const modelId = params.model;
const {
source,
presetName,
note,
params: overlayParams
} = getEffectiveOverlay(modelId, baseOverlayMode);
const overlayParamsNoSize = (() => {
if (!overlayParams) return overlayParams;
const o = { ...overlayParams };
delete o.batch_count;
delete o.batch_size;
delete o.batchCount;
delete o.batchSize;
delete o.upscaler;
delete o.upscaler_scale;
delete o.upscalerScale;
delete o.fps;
return o;
})();
overlaySource = source;
overlayPreset = presetName;
overlayNote = note;
if (!modelId || !modelId.trim() || modelId === "auto") {
delete filtered.model;
}
if (overlayParams) {
const msg = `Applying ${source} overlay for '${modelId ?? "auto"}' (${baseOverlayMode}, gRPC)${presetName ? ` preset=${presetName}` : ""}`;
logFile2(msg);
console.info(msg);
delete filtered.model;
}
audit.setOutput({
overlay_source: source,
...presetName && { overlay_preset: presetName },
...note && { overlay_note: note }
});
const effectiveSeed = source === "custom" && typeof overlayParamsNoSize?.seed === "number" && Number.isFinite(overlayParamsNoSize?.seed) ? overlayParamsNoSize.seed : baseDefaults.seed;
const effectiveSeedMode = source === "custom" && typeof overlayParamsNoSize?.seed_mode === "string" && String(overlayParamsNoSize.seed_mode).trim() ? String(overlayParamsNoSize.seed_mode) : baseDefaults.seed_mode;
seedSource = source === "custom" && typeof overlayParamsNoSize?.seed === "number" && Number.isFinite(overlayParamsNoSize?.seed) ? "custom" : "default";
seedModeSource = source === "custom" && typeof overlayParamsNoSize?.seed_mode === "string" && String(overlayParamsNoSize.seed_mode).trim() ? "custom" : "default";
const effective = {
...baseDefaults,
...overlayParamsNoSize || {},
...filtered,
seed: effectiveSeed,
seed_mode: effectiveSeedMode
};
{
const sub = overlaySource === "custom" ? { file: "", substituted: false } : substituteInstalledPrecision(String(effective.model ?? ""), await currentInventory());
if (sub.substituted) {
const note2 = substitutionNote(String(effective.model), sub.file);
effective.model = sub.file;
overlayNote = overlayNote ? `${overlayNote} ${note2}` : note2;
logFile2(note2);
}
}
defaultsUsed = isVideoTxt2Vid ? "defaultParamsDrawThingsText2Video" : "defaultParamsDrawThingsTxt2Img";
overlayLookupMode = baseOverlayMode;
strengthUsed = typeof effective.strength === "number" && Number.isFinite(effective.strength) ? effective.strength : void 0;
stepsUsed = typeof effective.steps === "number" && Number.isFinite(effective.steps) ? effective.steps : void 0;
samplerUsed = typeof effective.sampler === "string" && String(effective.sampler).trim() ? String(effective.sampler) : void 0;
guidanceScaleUsed = typeof effective.guidance_scale === "number" && Number.isFinite(effective.guidance_scale) ? effective.guidance_scale : void 0;
shiftUsed = typeof effective.shift === "number" && Number.isFinite(effective.shift) ? effective.shift : void 0;
resolutionDependentShiftUsed = typeof effective.resolution_dependent_shift === "boolean" ? effective.resolution_dependent_shift : void 0;
compressionArtifactsUsed = typeof effective.compressionArtifacts === "string" ? effective.compressionArtifacts : typeof effective.compression_artifacts === "string" ? effective.compression_artifacts : null;
compressionArtifactsQualityUsed = typeof effective.compressionArtifactsQuality === "number" ? effective.compressionArtifactsQuality : typeof effective.compression_artifacts_quality === "number" ? effective.compression_artifacts_quality : null;
audit.setOutput({
overlay_lookup_mode: baseOverlayMode,
defaults_used: isVideoTxt2Vid ? "defaultParamsDrawThingsText2Video" : "defaultParamsDrawThingsTxt2Img",
strength_used: typeof effective.strength === "number" && Number.isFinite(effective.strength) ? effective.strength : void 0,
steps_used: typeof effective.steps === "number" && Number.isFinite(effective.steps) ? effective.steps : void 0,
sampler_used: typeof effective.sampler === "string" && String(effective.sampler).trim() ? String(effective.sampler) : void 0,
guidance_scale_used: typeof effective.guidance_scale === "number" && Number.isFinite(effective.guidance_scale) ? effective.guidance_scale : void 0,
shift_used: typeof effective.shift === "number" && Number.isFinite(effective.shift) ? effective.shift : void 0,
resolution_dependent_shift_used: typeof effective.resolution_dependent_shift === "boolean" ? effective.resolution_dependent_shift : void 0,
num_frames_used: typeof effective.num_frames === "number" ? effective.num_frames : null,
compression_artifacts_used: typeof effective.compressionArtifacts === "string" ? effective.compressionArtifacts : typeof effective.compression_artifacts === "string" ? effective.compression_artifacts : null,
compression_artifacts_quality_used: typeof effective.compressionArtifactsQuality === "number" ? effective.compressionArtifactsQuality : typeof effective.compression_artifacts_quality === "number" ? effective.compression_artifacts_quality : null
});
try {
if (typeof effective.model === "string" && effective.model.trim()) {
requiredModelFile = String(effective.model).trim();
}
const userSpecifiedLoras = Object.prototype.hasOwnProperty.call(
filtered,
"loras"
);
const overlaySelected = !!overlayParams;
if (userSpecifiedLoras) {
const ls = Array.isArray(filtered.loras) ? filtered.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else if (overlaySelected) {
const ls = Array.isArray(overlayParams?.loras) ? overlayParams.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else {
const ls = Array.isArray(effective?.loras) ? effective.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
}
} catch {
}
const cfg = buildDtGenerationConfiguration(effective);
configBytes = cfg.bytes && cfg.bytes.length ? cfg.bytes : void 0;
try {
payloadWidth = cfg?.view?.width;
payloadHeight = cfg?.view?.height;
payloadSteps = cfg?.view?.steps;
payloadSeed = cfg?.view?.seed;
payloadSeedMode = cfg?.view?.seed_mode;
payloadModel = String(effective.model || "");
payloadNumFrames = typeof effective.num_frames === "number" ? effective.num_frames : 1;
payloadFps = (typeof filtered.fps === "number" ? filtered.fps : void 0) ?? getDefaultFpsForModel(payloadModel) ?? (typeof effective.fps === "number" ? effective.fps : 24);
} catch {
}
try {
const view = cfg.view || {};
audit.setOutput({
flatbuf_num_frames: typeof view.num_frames === "number" ? view.num_frames : null
});
console.info(
`[grpc-config] fields=${Object.keys(view).join(",")}`
);
} catch {
}
} catch {
}
try {
const echo = this.client["echo"]?.bind(this.client);
if (typeof echo === "function") {
const sharedSecret2 = process.env.DRAWTHINGS_SHARED_SECRET;
const req = { name: clientName() };
if (sharedSecret2) req.sharedSecret = sharedSecret2;
const echoStarted = Date.now();
await new Promise((resolve, reject) => {
echo(req, (err, resp) => {
if (err) return reject(err);
if (resp?.sharedSecretMissing && !sharedSecret2)
return reject(
new Error(
"gRPC requires sharedSecret. Set DRAWTHINGS_SHARED_SECRET."
)
);
const echoMs = Date.now() - echoStarted;
primeInventoryFromEcho(resp, echoMs);
runInventoryShadow(resp, echoMs);
resolve();
});
});
}
} catch (e) {
throw e;
}
try {
const sharedSecret2 = process.env.DRAWTHINGS_SHARED_SECRET;
const chk = await checkDrawThingsGrpcAssets({
client: this.client,
sharedSecret: sharedSecret2 || void 0,
modelFile: requiredModelFile,
loraFiles: requiredLoraFiles
});
if (!chk.ok) {
const overlayCtx = overlaySource && overlaySource !== "default" ? `overlay=${overlaySource}${overlayPreset ? ` preset=${overlayPreset}` : ""}` : "";
logErr(
`[asset-check] ${chk.details.split("\n")[0]}${overlayCtx ? ` (${overlayCtx})` : ""}`
);
const why = chk.missingModel && requiredModelFile ? await explainRequiredFile(requiredModelFile) : null;
const details = why ? `${chk.details}
${why}` : chk.details;
return {
isError: true,
status: 400,
errorMessage: overlayCtx ? `${overlayCtx}
${details}` : details
};
}
} catch (e) {
try {
logErr(
`[asset-check] warning: ${e instanceof Error ? e.message : String(e)}`
);
} catch {
}
}
const sharedSecret = process.env.DRAWTHINGS_SHARED_SECRET;
const request = {
prompt: String(params.prompt || baseDefaults.prompt),
negativePrompt: String(params.negative_prompt || ""),
scaleFactor: 1,
keywords: [],
user: clientName(),
device: "LAPTOP",
chunked: true,
...sharedSecret ? { sharedSecret } : {}
};
if (configBytes) request.configuration = configBytes;
const cfgB64 = process.env.DRAWTHINGS_CONFIG_B64;
if (cfgB64 && typeof cfgB64 === "string" && cfgB64.trim()) {
try {
request.configuration = Buffer.from(cfgB64.trim(), "base64");
} catch {
}
}
const call = this.cancellableGenerateCall();
if (typeof call !== "function")
throw new Error(`gRPC method not found: ${this.methodGenerate}`);
const startTime = Date.now();
const imagesBuffers = [];
const audioBuffers = [];
let chunkAccum = null;
let previewBuf = null;
let lastSeenStep = 0;
const handleData = (resp) => {
try {
if (resp?.currentSignpost?.sampling?.step) {
const currentStep = resp.currentSignpost.sampling.step;
lastSeenStep = currentStep;
console.info(
`gRPC progress: sampling step=${currentStep}`
);
logFile2(
`t2i progress: sampling step=${currentStep}`
);
if (onProgress) {
try {
onProgress(
currentStep,
payloadSteps,
`Sampling step ${currentStep}${payloadSteps ? `/${payloadSteps}` : ""}`
);
} catch {
}
}
} else if (resp?.currentSignpost != null && onProgress) {
const sp = resp.currentSignpost;
let label;
if (lastSeenStep === 0) {
if (sp.textEncoded != null) label = "Loading...";
else if (sp.imageEncoded != null) label = "Processing...";
} else {
label = "Finishing...";
}
if (label) {
try {
onProgress(-1, payloadSteps, label);
} catch {
}
}
}
if (resp?.generatedImages && Array.isArray(resp.generatedImages)) {
const list = resp.generatedImages.map(
(b) => Buffer.isBuffer(b) ? b : Buffer.from(b)
);
const cs = resp?.chunkState;
const isMore = cs === 1 || cs === "MORE_CHUNKS";
const isLast = cs === 0 || cs === "LAST_CHUNK";
if (isMore) {
if (list.length > 0) {
chunkAccum = chunkAccum ? Buffer.concat([chunkAccum, list[0]]) : Buffer.from(list[0]);
}
} else if (isLast && list.length > 0) {
if (chunkAccum) {
const full = Buffer.concat([chunkAccum, list[0]]);
imagesBuffers.push(full);
chunkAccum = null;
} else {
for (const buf of list) imagesBuffers.push(buf);
}
} else {
for (const buf of list) imagesBuffers.push(buf);
}
}
if (resp?.previewImage) {
const b = resp.previewImage;
previewBuf = Buffer.isBuffer(b) ? b : Buffer.from(b);
}
if (resp?.generatedAudio && Array.isArray(resp.generatedAudio)) {
for (const a of resp.generatedAudio) {
const ab = Buffer.isBuffer(a) ? a : Buffer.from(a);
if (ab.length > 0) audioBuffers.push(ab);
}
}
} catch {
}
};
await new Promise((resolve, reject) => {
try {
const accept = process.env.DRAWTHINGS_GRPC_ACCEPT_ENCODING;
const md = new grpc2.Metadata();
if (accept && accept.trim()) {
md.add("grpc-accept-encoding", accept.trim());
}
const stream = md.get("grpc-accept-encoding").length > 0 ? call(request, md) : call(request);
stream.on("data", handleData);
stream.on("error", (err) => reject(err));
stream.on("end", () => resolve());
} catch (e) {
reject(e);
}
});
const endTime = Date.now();
let primaryBuf;
logTensorSource("t2i", imagesBuffers, previewBuf, payloadModel);
if (imagesBuffers.length > 0) primaryBuf = imagesBuffers[0];
else if (previewBuf) primaryBuf = previewBuf;
if (!primaryBuf) throw new Error("gRPC stream yielded no image data");
const decoderTools = resolveExternalToolCandidates(
__projectRoot(),
"GRPCBin2PNG",
process.env.DT_DECODER_CMD
);
logToolCandidates("t2i decode", decoderTools);
const decoderProfile = resolveTensorDecoderProfile(payloadModel);
const decodedBuffers = [];
if (decoderTools.length) {
const finalW = Number(params.width || baseDefaults.width || 1024);
const finalH = Number(params.height || baseDefaults.height || 1024);
for (let i = 0; i < imagesBuffers.length; i++) {
try {
const tmpDir = fs26.mkdtempSync(
path29.join(os8.tmpdir(), `${clientName()}-dt-`)
);
__registerTmp(tmpDir);
const inPath = path29.join(tmpDir, `img-${i + 1}.bin`);
const outPath = path29.join(tmpDir, `img-${i + 1}.png`);
fs26.writeFileSync(inPath, imagesBuffers[i]);
const args = [
"--in",
inPath,
"--out",
outPath,
"--profile",
decoderProfile
];
let decoded = null;
for (const tool3 of decoderTools) {
const proc = spawnSync(tool3.cmd, [...tool3.argsPrefix, ...args], {
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env }
});
if (proc.error) {
logErr(
`[decoder] exception via ${tool3.display}: ${proc.error.message}`
);
continue;
}
if (proc.status !== 0) {
logErr(
`[decoder] exit=${proc.status} via ${tool3.display} stderr=${proc.stderr?.toString?.() || ""}`
);
continue;
}
if (fs26.existsSync(outPath) && fs26.statSync(outPath).size > 0) {
decoded = fs26.readFileSync(outPath);
break;
}
logErr(
`[decoder] no output via ${tool3.display}; outPath missing/empty`
);
}
if (decoded) decodedBuffers.push(decoded);
else decodedBuffers.push(imagesBuffers[i]);
} catch {
decodedBuffers.push(imagesBuffers[i]);
logErr(
`[decoder] exception decoding t2i img-${i + 1}.bin; kept raw`
);
}
}
if (decodedBuffers.length > 0) {
logFile2(
`[decoder] t2i: decoded ${decodedBuffers.length} frame(s) \u2192 PNG via ${decoderTools[0].display}`
);
}
}
let finalBuffers = decoderTools.length ? decodedBuffers : imagesBuffers;
if ((!finalBuffers || finalBuffers.length === 0) && previewBuf) {
if (decoderTools.length) {
try {
const tmpDir = fs26.mkdtempSync(
path29.join(os8.tmpdir(), `${clientName()}-dt-`)
);
__registerTmp(tmpDir);
const inPath = path29.join(tmpDir, `preview.bin`);
const outPath = path29.join(tmpDir, `preview.png`);
fs26.writeFileSync(inPath, previewBuf);
const finalW = Number(params.width || baseDefaults.width || 1024);
const finalH = Number(
params.height || baseDefaults.height || 1024
);
const args = [
"--in",
inPath,
"--out",
outPath,
"--profile",
decoderProfile
];
let decodedPrev = null;
for (const tool3 of decoderTools) {
const proc = spawnSync(tool3.cmd, [...tool3.argsPrefix, ...args], {
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env }
});
if (proc.error) continue;
if (proc.status !== 0) continue;
if (fs26.existsSync(outPath) && fs26.statSync(outPath).size > 0) {
decodedPrev = fs26.readFileSync(outPath);
logFile2(
`[decoder] decoded preview.bin \u2192 PNG (${decodedPrev.length} bytes) via ${tool3.display}`
);
break;
}
}
finalBuffers = decodedPrev ? [decodedPrev] : [previewBuf];
} catch {
finalBuffers = [previewBuf];
}
} else {
finalBuffers = [previewBuf];
}
}
const pngCandidate = finalBuffers[0];
const effW = Number(
payloadWidth ?? params.width ?? baseDefaults.width ?? 1024
);
const effH = Number(
payloadHeight ?? params.height ?? baseDefaults.height ?? 1024
);
const dataUrl = `data:image/png;base64,${pngCandidate.toString(
"base64"
)}`;
logFile2(
`t2i completed: variants=${finalBuffers.length}, chunks=${imagesBuffers.length}, bytes=${pngCandidate.length}`
);
const result = {
isError: false,
imageBuffer: pngCandidate,
imageData: dataUrl,
images: finalBuffers.length ? finalBuffers.map(
(b) => `data:image/png;base64,${b.toString("base64")}`
) : void 0,
metadata: {
alt: `Image generated from prompt: ${request.prompt}`,
inference_time_ms: endTime - startTime,
model: payloadModel,
width: effW,
height: effH,
requested_dimensions: {
width: effW,
height: effH
},
steps: Number.isFinite(Number(payloadSteps)) ? Number(payloadSteps) : void 0,
seed: typeof payloadSeed === "number" && Number.isFinite(payloadSeed) ? payloadSeed : void 0,
seed_mode: typeof payloadSeedMode === "string" && payloadSeedMode.trim() ? payloadSeedMode : void 0,
seed_source: seedSource,
seed_mode_source: seedModeSource,
prompt_used: String(request.prompt || ""),
prompt_origin: promptOriginTxt,
...configBytes && { config_v2: generationConfigBytesToV2(configBytes) },
transport: "grpc",
stream_chunks: imagesBuffers.length,
num_frames: payloadNumFrames,
fps: payloadFps,
// Overlay source tracking for audit
overlay_source: overlaySource,
...overlayPreset && { overlay_preset: overlayPreset },
...overlayNote && { overlay_note: overlayNote },
...defaultsUsed && { defaults_used: defaultsUsed },
...overlayLookupMode && { overlay_lookup_mode: overlayLookupMode },
...typeof strengthUsed === "number" && { strength_used: strengthUsed },
...typeof stepsUsed === "number" && { steps_used: stepsUsed },
...samplerUsed && { sampler_used: samplerUsed },
...typeof guidanceScaleUsed === "number" && {
guidance_scale_used: guidanceScaleUsed
},
...typeof shiftUsed === "number" && { shift_used: shiftUsed },
...typeof resolutionDependentShiftUsed === "boolean" && {
resolution_dependent_shift_used: resolutionDependentShiftUsed
},
...compressionArtifactsUsed != null && {
compression_artifacts_used: compressionArtifactsUsed
},
...compressionArtifactsQualityUsed != null && {
compression_artifacts_quality_used: compressionArtifactsQualityUsed
},
...requiredLoraFiles && requiredLoraFiles.length > 0 && { loras_used: requiredLoraFiles }
},
audioBuffers: audioBuffers.length > 0 ? audioBuffers : void 0
};
__cleanupTmp();
return result;
} catch (e) {
try {
} catch {
}
return this.toBackendError(e);
}
}
async generateImageImg2Img(inputParams = {}, sourceBuffer, onProgress, maskBuffer) {
try {
const __tmpDirs = [];
const __registerTmp = (d) => {
try {
__tmpDirs.push(d);
} catch {
}
};
const __cleanupTmp = () => {
for (const d of __tmpDirs) {
try {
fs26.rmSync(d, { recursive: true, force: true });
} catch {
}
}
};
const isVideoImg2Vid = inputParams?._dt_video_mode === "img2vid";
const i2iProfile = isVideoImg2Vid ? void 0 : inputParams?._dt_i2i_profile;
const auditMode = isVideoImg2Vid ? "img2vid" : i2iProfile === "zoom" ? "zoom" : i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint" || i2iProfile === "restore" ? "edit" : "img2img";
const audit = buildAuditLogger({ backend: this.name, mode: auditMode });
this.ensureClient();
const baseDefaults = isVideoImg2Vid ? defaultParamsImage2Video : i2iProfile === "zoom" ? defaultParamsZoom : i2iProfile === "restore" ? defaultParamsImg2Img3 : i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint" ? defaultParamsImg2Img2 : defaultParamsImg2Img;
const baseLimits = isVideoImg2Vid ? drawthingsLimits : i2iProfile === "restore" || i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint" ? drawthingsLimits : drawthingsLimits;
let params = {};
try {
const r = validateImageGenerationParams(inputParams);
if (r.valid) params = inputParams;
} catch {
}
if (params.random_string && (!params.prompt || Object.keys(params).length === 1)) {
params.prompt = params.random_string;
delete params.random_string;
}
if (!params.prompt)
params.prompt = inputParams.prompt || baseDefaults.prompt;
const promptOriginI2I = typeof inputParams?.prompt === "string" && String(inputParams.prompt).trim() ? "user" : `default:drawthings:${isVideoImg2Vid ? "img2vid" : "img2img"}`;
let usedImageFormat = void 0;
try {
const fmt = inputParams.imageFormat;
if (fmt === "square") {
params.width = 1024;
params.height = 1024;
usedImageFormat = "square";
} else if (fmt === "landscape") {
params.width = 1024;
params.height = 768;
usedImageFormat = "landscape";
} else if (fmt === "portrait") {
params.width = 768;
params.height = 1024;
usedImageFormat = "portrait";
} else if (fmt === "16:9") {
params.width = 1024;
params.height = 576;
usedImageFormat = "16:9";
}
const variants = inputParams.variants;
if (typeof variants === "number") {
const v = Math.max(1, Math.min(4, Math.round(variants)));
params.batch_size = v;
params.batch_count = 1;
}
if (isVideoImg2Vid) {
const rawNumFrames = inputParams.numFrames;
if (typeof rawNumFrames === "number" && rawNumFrames > 1) {
const normalized = normalizeNumFrames(rawNumFrames);
params.num_frames = normalized.value;
if (normalized.hint) console.info(`[img2vid] ${normalized.hint}`);
}
}
} catch {
}
let initPng = sourceBuffer;
let srcW;
let srcH;
try {
const meta = await getSize(sourceBuffer);
srcW = meta.width;
srcH = meta.height;
initPng = await toPng(sourceBuffer);
} catch {
}
const userReqW = (() => {
const v = inputParams?.width;
return typeof v === "number" && Number.isFinite(v) ? Math.round(v) : void 0;
})();
const userReqH = (() => {
const v = inputParams?.height;
return typeof v === "number" && Number.isFinite(v) ? Math.round(v) : void 0;
})();
if (srcW && srcH) {
params.original_width = srcW;
params.original_height = srcH;
const hasW = typeof params.width === "number" && Number.isFinite(params.width);
const hasH = typeof params.height === "number" && Number.isFinite(params.height);
if (!hasW) params.width = userReqW ?? srcW;
if (!hasH) params.height = userReqH ?? srcH;
const hasTW = typeof params.target_width === "number" && Number.isFinite(params.target_width);
const hasTH = typeof params.target_height === "number" && Number.isFinite(params.target_height);
if (!hasTW) params.target_width = params.width;
if (!hasTH) params.target_height = params.height;
}
let configBytes = void 0;
let payloadWidth;
let payloadHeight;
let payloadSteps;
let payloadSeed;
let payloadSeedMode;
let payloadModel;
let payloadNumFrames = 1;
let payloadFps = 24;
let requiredModelFile;
let requiredLoraFiles;
let overlaySource = "default";
let overlayPreset;
let overlayNote;
let defaultsUsed;
let overlayLookupMode;
let i2iProfileUsed;
let strengthUsed;
let stepsUsed;
let samplerUsed;
let guidanceScaleUsed;
let shiftUsed;
let resolutionDependentShiftUsed;
let compressionArtifactsUsed;
let compressionArtifactsQualityUsed;
try {
const allowedKeys = new Set(Object.keys(baseDefaults));
const filtered = {};
for (const [k, v] of Object.entries(params)) {
if (allowedKeys.has(k)) filtered[k] = v;
}
const modelId = i2iProfile === "zoom" ? void 0 : params.model;
const overlayMode = isVideoImg2Vid ? "img2vid" : i2iProfile === "zoom" ? "zoom" : i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint" || i2iProfile === "restore" ? i2iProfile : "img2img";
const {
source,
presetName,
note,
params: overlayParams
} = getEffectiveOverlay(modelId, overlayMode === "inpaint" || overlayMode === "outpaint" ? "edit" : overlayMode);
const overlayParamsNoSize = (() => {
if (!overlayParams) return overlayParams;
const o = { ...overlayParams };
delete o.width;
delete o.height;
delete o.batch_count;
delete o.batch_size;
delete o.batchCount;
delete o.batchSize;
delete o.upscaler;
delete o.upscaler_scale;
delete o.upscalerScale;
delete o.fps;
return o;
})();
overlaySource = source;
overlayPreset = presetName;
overlayNote = note;
if (!modelId || !modelId.trim() || modelId === "auto") {
delete filtered.model;
}
if (overlayParams) {
const msg = `Applying ${source} overlay for '${modelId ?? "auto"}' (${overlayMode}, gRPC)${presetName ? ` preset=${presetName}` : ""}`;
logFile2(msg);
console.info(msg);
delete filtered.model;
}
if (i2iProfile === "zoom") {
delete filtered.model;
delete filtered.strength;
if (overlayParamsNoSize) delete overlayParamsNoSize.strength;
}
audit.setOutput({
overlay_source: source,
...presetName && { overlay_preset: presetName },
...note && { overlay_note: note }
});
const effectiveSeed = source === "custom" && typeof overlayParamsNoSize?.seed === "number" && Number.isFinite(overlayParamsNoSize?.seed) ? overlayParamsNoSize.seed : baseDefaults.seed;
const effective = {
...baseDefaults,
...overlayParamsNoSize || {},
...filtered,
seed: effectiveSeed
};
{
const sub = overlaySource === "custom" ? { file: "", substituted: false } : substituteInstalledPrecision(String(effective.model ?? ""), await currentInventory());
if (sub.substituted) {
const note2 = substitutionNote(String(effective.model), sub.file);
effective.model = sub.file;
overlayNote = overlayNote ? `${overlayNote} ${note2}` : note2;
logFile2(note2);
}
}
if ((i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint") && (typeof effective.model !== "string" || !effective.model.trim())) {
throw new Error(
`No usable edit model found. Requested model: '${modelId ?? "auto"}'. Check that a custom config or model overlay is registered for mode='edit'.`
);
}
defaultsUsed = isVideoImg2Vid ? "defaultParamsDrawThingsImage2Video" : i2iProfile === "zoom" ? "defaultParamsZoom" : i2iProfile === "restore" ? "defaultParamsDrawThingsRestore" : i2iProfile === "edit" || i2iProfile === "inpaint" || i2iProfile === "outpaint" ? "defaultParamsDrawThingsEdit" : "defaultParamsDrawThingsImg2Img";
overlayLookupMode = overlayMode;
i2iProfileUsed = isVideoImg2Vid ? void 0 : i2iProfile;
strengthUsed = typeof effective.strength === "number" && Number.isFinite(effective.strength) ? effective.strength : void 0;
stepsUsed = typeof effective.steps === "number" && Number.isFinite(effective.steps) ? effective.steps : void 0;
samplerUsed = typeof effective.sampler === "string" && String(effective.sampler).trim() ? String(effective.sampler) : void 0;
guidanceScaleUsed = typeof effective.guidance_scale === "number" && Number.isFinite(effective.guidance_scale) ? effective.guidance_scale : void 0;
shiftUsed = typeof effective.shift === "number" && Number.isFinite(effective.shift) ? effective.shift : void 0;
resolutionDependentShiftUsed = typeof effective.resolution_dependent_shift === "boolean" ? effective.resolution_dependent_shift : void 0;
compressionArtifactsUsed = typeof effective.compressionArtifacts === "string" ? effective.compressionArtifacts : typeof effective.compression_artifacts === "string" ? effective.compression_artifacts : null;
compressionArtifactsQualityUsed = typeof effective.compressionArtifactsQuality === "number" ? effective.compressionArtifactsQuality : typeof effective.compression_artifacts_quality === "number" ? effective.compression_artifacts_quality : null;
{
const defaultsUsed2 = isVideoImg2Vid ? "defaultParamsDrawThingsImage2Video" : i2iProfile === "zoom" ? "defaultParamsZoom" : i2iProfile === "restore" ? "defaultParamsDrawThingsRestore" : i2iProfile === "edit" ? "defaultParamsDrawThingsEdit" : "defaultParamsDrawThingsImg2Img";
audit.setOutput({
overlay_lookup_mode: overlayMode === "inpaint" || overlayMode === "outpaint" ? "edit" : overlayMode,
defaults_used: defaultsUsed2,
i2i_profile: i2iProfile,
strength_used: typeof effective.strength === "number" && Number.isFinite(effective.strength) ? effective.strength : void 0,
steps_used: typeof effective.steps === "number" && Number.isFinite(effective.steps) ? effective.steps : void 0,
sampler_used: typeof effective.sampler === "string" && String(effective.sampler).trim() ? String(effective.sampler) : void 0,
guidance_scale_used: typeof effective.guidance_scale === "number" && Number.isFinite(effective.guidance_scale) ? effective.guidance_scale : void 0,
shift_used: typeof effective.shift === "number" && Number.isFinite(effective.shift) ? effective.shift : void 0,
resolution_dependent_shift_used: typeof effective.resolution_dependent_shift === "boolean" ? effective.resolution_dependent_shift : void 0,
num_frames_used: typeof effective.num_frames === "number" ? effective.num_frames : null,
compression_artifacts_used: typeof effective.compressionArtifacts === "string" ? effective.compressionArtifacts : typeof effective.compression_artifacts === "string" ? effective.compression_artifacts : null,
compression_artifacts_quality_used: typeof effective.compressionArtifactsQuality === "number" ? effective.compressionArtifactsQuality : typeof effective.compression_artifacts_quality === "number" ? effective.compression_artifacts_quality : null
});
}
try {
if (typeof effective.model === "string" && effective.model.trim()) {
requiredModelFile = String(effective.model).trim();
}
const userSpecifiedLoras = Object.prototype.hasOwnProperty.call(
filtered,
"loras"
);
const overlaySelected = !!overlayParams;
if (userSpecifiedLoras) {
const ls = Array.isArray(filtered.loras) ? filtered.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else if (overlaySelected) {
const ls = Array.isArray(overlayParams?.loras) ? overlayParams.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else {
const ls = Array.isArray(effective?.loras) ? effective.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
}
} catch {
}
{
const needs = inputParams?._dt_needs_upscaler;
if (typeof needs !== "boolean") {
throw new Error(
`Invariant failed: _dt_needs_upscaler must be provided by core for ${i2iProfile}`
);
}
if (needs && i2iProfile !== "zoom" && baseLimits.upscaleMethod !== "zoom-pass") {
effective.upscaler = baseLimits.upscaler;
effective.upscaler_scale = baseLimits.upscalerScaleFactor;
console.info(`DT gRPC ${i2iProfile} upscaler enabled (core)`);
} else {
effective.upscaler = null;
effective.upscaler_scale = 0;
console.info(`DT gRPC ${i2iProfile} upscaler disabled (core)`);
}
}
const cfg = buildDtGenerationConfiguration(effective);
configBytes = cfg.bytes && cfg.bytes.length ? cfg.bytes : void 0;
try {
const view = cfg?.view || {};
payloadWidth = view.width;
payloadHeight = view.height;
payloadSteps = view.steps;
payloadSeed = view.seed;
payloadSeedMode = view.seed_mode;
payloadModel = String(effective.model || "");
payloadNumFrames = typeof effective.num_frames === "number" ? effective.num_frames : 1;
payloadFps = (typeof filtered.fps === "number" ? filtered.fps : void 0) ?? getDefaultFpsForModel(payloadModel) ?? (typeof effective.fps === "number" ? effective.fps : 24);
} catch {
}
try {
const view = cfg.view || {};
audit.setOutput({
flatbuf_num_frames: typeof view.num_frames === "number" ? view.num_frames : null
});
console.info(
`[grpc-config] fields=${Object.keys(view).join(",")}`
);
} catch {
}
} catch {
}
try {
const sharedSecret = process.env.DRAWTHINGS_SHARED_SECRET;
const chk = await checkDrawThingsGrpcAssets({
client: this.client,
sharedSecret: sharedSecret || void 0,
modelFile: requiredModelFile,
loraFiles: requiredLoraFiles
});
if (!chk.ok) {
logErr(`[asset-check] ${chk.details.split("\n")[0]}`);
__cleanupTmp();
const why = chk.missingModel && requiredModelFile ? await explainRequiredFile(requiredModelFile) : null;
const details = why ? `${chk.details}
${why}` : chk.details;
return {
isError: true,
status: 400,
errorMessage: overlaySource && overlaySource !== "default" ? `overlay=${overlaySource}${overlayPreset ? ` preset=${overlayPreset}` : ""}
${details}` : details
};
}
} catch (e) {
try {
logErr(
`[asset-check] warning: ${e instanceof Error ? e.message : String(e)}`
);
} catch {
}
}
try {
const sharedSecret = process.env.DRAWTHINGS_SHARED_SECRET;
const chk = await checkDrawThingsGrpcAssets({
client: this.client,
sharedSecret: sharedSecret || void 0,
modelFile: requiredModelFile,
loraFiles: requiredLoraFiles
});
if (!chk.ok) {
logErr(`[asset-check] ${chk.details.split("\n")[0]}`);
const why = chk.missingModel && requiredModelFile ? await explainRequiredFile(requiredModelFile) : null;
const details = why ? `${chk.details}
${why}` : chk.details;
return {
isError: true,
status: 400,
errorMessage: overlaySource && overlaySource !== "default" ? `overlay=${overlaySource}${overlayPreset ? ` preset=${overlayPreset}` : ""}
${details}` : details
};
}
} catch (e) {
try {
logErr(
`[asset-check] warning: ${e instanceof Error ? e.message : String(e)}`
);
} catch {
}
}
const sharedSecret2 = process.env.DRAWTHINGS_SHARED_SECRET;
const request = {
prompt: String(params.prompt || defaultParamsImg2Img.prompt),
negativePrompt: String(params.negative_prompt || ""),
scaleFactor: 1,
keywords: [],
user: clientName(),
device: "LAPTOP",
chunked: true,
...sharedSecret2 ? { sharedSecret: sharedSecret2 } : {}
};
if (configBytes) request.configuration = configBytes;
const projectRoot2 = __resolveProjectRootFrom(__svcDir());
const encoderTools = resolveExternalToolCandidates(
projectRoot2,
"PNG2GRPCBin",
process.env.DT_ENCODER_CMD
);
logToolCandidates("i2i encode", encoderTools);
if (encoderTools.length) {
try {
const tmpDir = fs26.mkdtempSync(
path29.join(os8.tmpdir(), `${clientName()}-enc-`)
);
__registerTmp(tmpDir);
const pngPath = path29.join(tmpDir, "input.png");
const imgBinPath = path29.join(tmpDir, "image.bin");
fs26.writeFileSync(pngPath, initPng);
const args = ["--in", pngPath, "--out", imgBinPath];
let lastStdout = "";
let lastStderr = "";
let blob = null;
let toolUsed = null;
for (const tool3 of encoderTools) {
try {
try {
if (fs26.existsSync(imgBinPath)) fs26.unlinkSync(imgBinPath);
} catch {
}
const proc = spawnSync(tool3.cmd, [...tool3.argsPrefix, ...args], {
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env }
});
if (proc.error) {
lastStderr = proc.error.message;
logErr(
`[i2i-encode] exception via ${tool3.display}: ${lastStderr}`
);
continue;
}
lastStdout = (proc.stdout || Buffer.alloc(0)).toString("utf8").trim();
lastStderr = (proc.stderr || Buffer.alloc(0)).toString("utf8").trim();
if (typeof proc.status === "number" && proc.status !== 0) {
logErr(
`[i2i-encode] exit=${proc.status} via ${tool3.display} stderr=${lastStderr}`
);
continue;
}
if (fs26.existsSync(imgBinPath) && fs26.statSync(imgBinPath).size > 0) {
blob = fs26.readFileSync(imgBinPath);
toolUsed = tool3;
break;
}
logErr(
`[i2i-encode] no output via ${tool3.display}; image.bin missing/empty stdout=${lastStdout}`
);
} catch (e) {
logErr(
`[i2i-encode] exception via ${tool3.display}: ${e instanceof Error ? e.message : String(e)}`
);
continue;
}
}
if (blob && toolUsed) {
let imgHashBuf = null;
if (/^[0-9a-fA-F]{64}$/.test(lastStdout)) {
imgHashBuf = Buffer.from(lastStdout, "hex");
} else {
const h = crypto2.createHash("sha256").update(blob).digest();
imgHashBuf = h;
}
const hashHex = imgHashBuf.toString("hex");
logFile2(
`[encoder] encoded input.png \u2192 image.bin (${blob.length} bytes) via ${toolUsed.display}`
);
try {
const filesExist2 = this.client["filesExist"]?.bind(
this.client
);
if (typeof filesExist2 === "function") {
await new Promise((resolve) => {
filesExist2(
{
files: [],
filesWithHash: [hashHex],
...sharedSecret2 ? { sharedSecret: sharedSecret2 } : {}
},
(err, resp) => {
if (err) {
logErr(
`FilesExist error: ${err?.message || String(err)}`
);
return resolve();
}
try {
const existArr = Array.isArray(
resp?.existences
) ? resp.existences : [];
const exists = existArr[0] === true;
logFile2(
`[CAS] FilesExist hash=${hashHex} exists=${exists}`
);
if (!exists) {
try {
const upload = this.client["uploadFile"]?.call(this.client);
if (upload && typeof upload.write === "function") {
const fname = `image-${hashHex}.bin`;
upload.write({
initRequest: {
filename: fname,
sha256: imgHashBuf,
totalSize: blob.length
},
...sharedSecret2 ? { sharedSecret: sharedSecret2 } : {}
});
upload.write({
chunk: {
content: blob,
filename: fname,
offset: 0
},
...sharedSecret2 ? { sharedSecret: sharedSecret2 } : {}
});
upload.end();
upload.on(
"end",
() => logFile2(
`[CAS] UploadFile completed hash=${hashHex} size=${blob.length}`
)
);
upload.on(
"error",
(ue) => logErr(
`[CAS] UploadFile error: ${ue?.message || String(ue)}`
)
);
}
} catch (ue) {
logErr(
`[CAS] UploadFile exception: ${ue?.message || String(ue)}`
);
}
}
} catch {
}
resolve();
}
);
});
}
} catch {
}
request.image = imgHashBuf;
request.contents = [blob];
logFile2(
`[i2i-encode] built image.bin (${blob.length} bytes) hash=${imgHashBuf.toString("hex")}`
);
if (maskBuffer) {
try {
const maskPngPath = path29.join(tmpDir, "mask.png");
const maskBinPath = path29.join(tmpDir, "mask.bin");
fs26.writeFileSync(maskPngPath, maskBuffer);
const maskArgs = ["--in", maskPngPath, "--out", maskBinPath, "--mode", "mask"];
let maskStdout = "";
const maskProc = spawnSync(toolUsed.cmd, [...toolUsed.argsPrefix, ...maskArgs], {
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env }
});
maskStdout = (maskProc.stdout || Buffer.alloc(0)).toString("utf8").trim();
if (!maskProc.error && (typeof maskProc.status !== "number" || maskProc.status === 0) && fs26.existsSync(maskBinPath) && fs26.statSync(maskBinPath).size > 0) {
const maskBlob = fs26.readFileSync(maskBinPath);
let maskHashBuf;
if (/^[0-9a-fA-F]{64}$/.test(maskStdout)) {
maskHashBuf = Buffer.from(maskStdout, "hex");
} else {
maskHashBuf = crypto2.createHash("sha256").update(maskBlob).digest();
}
const maskHashHex = maskHashBuf.toString("hex");
try {
const filesExist2 = this.client["filesExist"]?.bind(this.client);
if (typeof filesExist2 === "function") {
await new Promise((resolve) => {
filesExist2(
{
files: [],
filesWithHash: [maskHashHex],
...sharedSecret2 ? { sharedSecret: sharedSecret2 } : {}
},
(err, resp) => {
if (err) {
logErr(`[CAS] FilesExist mask error: ${err?.message || String(err)}`);
return resolve();
}
try {
const existArr = Array.isArray(resp?.existences) ? resp.existences : [];
const exists = existArr[0] === true;
logFile2(`[CAS] FilesExist mask hash=${maskHashHex} exists=${exists}`);
if (!exists) {
try {
const upload = this.client["uploadFile"]?.call(this.client);
if (upload && typeof upload.write === "function") {
const fname = `mask-${maskHashHex}.bin`;
upload.write({
initRequest: {
filename: fname,
sha256: maskHashBuf,
totalSize: maskBlob.length
},
...sharedSecret2 ? { sharedSecret: sharedSecret2 } : {}
});
upload.write({
chunk: {
content: maskBlob,
filename: fname,
offset: 0
},
...sharedSecret2 ? { sharedSecret: sharedSecret2 } : {}
});
upload.end();
upload.on(
"end",
() => logFile2(`[CAS] UploadFile mask completed hash=${maskHashHex} size=${maskBlob.length}`)
);
upload.on(
"error",
(ue) => logErr(`[CAS] UploadFile mask error: ${ue?.message || String(ue)}`)
);
}
} catch (ue) {
logErr(`[CAS] UploadFile mask exception: ${ue?.message || String(ue)}`);
}
}
} catch {
}
resolve();
}
);
});
}
} catch {
}
request.mask = maskHashBuf;
request.contents = [blob, maskBlob];
logFile2(`[i2i-encode] built mask.bin (${maskBlob.length} bytes) hash=${maskHashHex}`);
} else {
logErr(`[i2i-encode] mask encoding failed via ${toolUsed.display}`);
}
try {
fs26.unlinkSync(maskPngPath);
} catch {
}
try {
fs26.unlinkSync(maskBinPath);
} catch {
}
} catch (e) {
logErr(`[i2i-encode] mask encode exception: ${e instanceof Error ? e.message : String(e)}`);
}
}
try {
fs26.unlinkSync(pngPath);
} catch {
}
try {
fs26.unlinkSync(imgBinPath);
} catch {
}
} else {
console.error(
`[i2i-encode] encoder did not produce image.bin; stdout=${lastStdout}`
);
logErr(
`[i2i-encode] encoder did not produce image.bin; stdout=${lastStdout} stderr=${lastStderr}`
);
}
} catch (e) {
console.error(
`[i2i-encode] encoder failed: ${e instanceof Error ? e.message : String(e)}`
);
logErr(
`[i2i-encode] encoder failed: ${e instanceof Error ? e.message : String(e)}`
);
}
}
if (!request.image || !request.contents || !Array.isArray(request.contents) || request.contents.length === 0) {
request.contents = [Buffer.from(initPng)];
}
const call = this.cancellableGenerateCall();
if (typeof call !== "function")
throw new Error(`gRPC method not found: ${this.methodGenerate}`);
const startTime = Date.now();
const imagesBuffers = [];
const audioBuffers = [];
let chunkAccum = null;
let previewBuf = null;
let lastSeenStep = 0;
const handleData = (resp) => {
try {
if (resp?.currentSignpost?.sampling?.step) {
const currentStep = resp.currentSignpost.sampling.step;
lastSeenStep = currentStep;
console.info(
`gRPC progress: sampling step=${currentStep}`
);
logFile2(
`i2i progress: sampling step=${currentStep}`
);
if (onProgress) {
try {
onProgress(
currentStep,
payloadSteps,
`Sampling step ${currentStep}${payloadSteps ? `/${payloadSteps}` : ""}`
);
} catch {
}
}
} else if (resp?.currentSignpost != null && onProgress) {
const sp = resp.currentSignpost;
let label;
if (lastSeenStep === 0) {
if (sp.textEncoded != null) label = "Loading...";
else if (sp.imageEncoded != null) label = "Processing...";
} else {
label = "Finishing...";
}
if (label) {
try {
onProgress(-1, payloadSteps, label);
} catch {
}
}
}
if (resp?.generatedImages && Array.isArray(resp.generatedImages)) {
const list = resp.generatedImages.map(
(b) => Buffer.isBuffer(b) ? b : Buffer.from(b)
);
const cs = resp?.chunkState;
const isMore = cs === 1 || cs === "MORE_CHUNKS";
const isLast = cs === 0 || cs === "LAST_CHUNK";
if (isMore) {
if (list.length > 0) {
chunkAccum = chunkAccum ? Buffer.concat([chunkAccum, list[0]]) : Buffer.from(list[0]);
}
} else if (isLast && list.length > 0) {
if (chunkAccum) {
const full = Buffer.concat([chunkAccum, list[0]]);
imagesBuffers.push(full);
chunkAccum = null;
} else {
for (const buf of list) imagesBuffers.push(buf);
}
} else {
for (const buf of list) imagesBuffers.push(buf);
}
}
if (resp?.previewImage) {
const b = resp.previewImage;
previewBuf = Buffer.isBuffer(b) ? b : Buffer.from(b);
}
if (resp?.generatedAudio && Array.isArray(resp.generatedAudio)) {
for (const a of resp.generatedAudio) {
const ab = Buffer.isBuffer(a) ? a : Buffer.from(a);
if (ab.length > 0) audioBuffers.push(ab);
}
}
} catch {
}
};
await new Promise((resolve, reject) => {
try {
const stream = call(request);
stream.on("data", handleData);
stream.on("error", (err) => reject(err));
stream.on("end", () => resolve());
} catch (e) {
reject(e);
}
});
const endTime = Date.now();
const decoderTools2 = resolveExternalToolCandidates(
__projectRoot(),
"GRPCBin2PNG",
process.env.DT_DECODER_CMD
);
logToolCandidates("i2i decode", decoderTools2);
const decoderProfile = resolveTensorDecoderProfile(payloadModel);
logTensorSource("i2i", imagesBuffers, previewBuf, payloadModel);
if (decoderTools2.length && imagesBuffers.length > 0) {
const finalW = Number(
params.width || defaultParamsImg2Img.width || 1024
);
const finalH = Number(
params.height || defaultParamsImg2Img.height || 1024
);
const decoded = [];
for (let i = 0; i < imagesBuffers.length; i++) {
try {
const tmpDir = fs26.mkdtempSync(
path29.join(os8.tmpdir(), `${clientName()}-dt-`)
);
__registerTmp(tmpDir);
const inPath = path29.join(tmpDir, `img2img-${i + 1}.bin`);
const outPath = path29.join(tmpDir, `img2img-${i + 1}.png`);
fs26.writeFileSync(inPath, imagesBuffers[i]);
const args = [
"--in",
inPath,
"--out",
outPath,
"--profile",
decoderProfile
];
let decodedOne = null;
for (const tool3 of decoderTools2) {
const proc = spawnSync(tool3.cmd, [...tool3.argsPrefix, ...args], {
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env }
});
if (proc.error) {
logErr(
`[decoder] exception via ${tool3.display}: ${proc.error.message}`
);
continue;
}
if (proc.status !== 0) {
logErr(
`[decoder] exit=${proc.status} via ${tool3.display} stderr=${proc.stderr?.toString?.() || ""}`
);
continue;
}
if (fs26.existsSync(outPath) && fs26.statSync(outPath).size > 0) {
decodedOne = fs26.readFileSync(outPath);
break;
}
}
if (decodedOne) {
decoded.push(decodedOne);
try {
fs26.unlinkSync(inPath);
} catch {
}
} else {
decoded.push(imagesBuffers[i]);
}
} catch {
decoded.push(imagesBuffers[i]);
}
}
if (decoded.length > 0) {
imagesBuffers.length = 0;
imagesBuffers.push(...decoded);
logFile2(
`[decoder] i2i: decoded ${decoded.length} frame(s) \u2192 PNG via ${decoderTools2[0].display}`
);
}
}
let primaryBuf;
if (imagesBuffers.length > 0) primaryBuf = imagesBuffers[0];
else if (previewBuf) {
if (decoderTools2.length && previewBuf) {
try {
const tmpDir = fs26.mkdtempSync(
path29.join(os8.tmpdir(), `${clientName()}-dt-`)
);
__registerTmp(tmpDir);
const inPath = path29.join(tmpDir, `preview-i2i.bin`);
const outPath = path29.join(tmpDir, `preview-i2i.png`);
fs26.writeFileSync(inPath, previewBuf);
const finalW = Number(
params.width || defaultParamsImg2Img.width || 1024
);
const finalH = Number(
params.height || defaultParamsImg2Img.height || 1024
);
const args = [
"--in",
inPath,
"--out",
outPath,
"--profile",
decoderProfile
];
let decodedPrev = null;
for (const tool3 of decoderTools2) {
const proc = spawnSync(tool3.cmd, [...tool3.argsPrefix, ...args], {
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env }
});
if (proc.error) continue;
if (proc.status !== 0) continue;
if (fs26.existsSync(outPath) && fs26.statSync(outPath).size > 0) {
decodedPrev = fs26.readFileSync(outPath);
logFile2(
`[decoder] decoded preview-i2i.bin \u2192 PNG (${decodedPrev.length} bytes) via ${tool3.display}`
);
break;
}
}
primaryBuf = decodedPrev ? decodedPrev : previewBuf;
try {
fs26.unlinkSync(inPath);
} catch {
}
} catch {
primaryBuf = previewBuf;
}
} else {
primaryBuf = previewBuf;
}
}
if (!primaryBuf) throw new Error("gRPC stream yielded no image data");
const dataUrl = `data:image/png;base64,${primaryBuf.toString("base64")}`;
logFile2(
`i2i completed: images=${imagesBuffers.length}, bytes=${primaryBuf.length}`
);
const effW = Number(
payloadWidth ?? params.width ?? defaultParamsImg2Img.width ?? 1024
);
const effH = Number(
payloadHeight ?? params.height ?? defaultParamsImg2Img.height ?? 1024
);
const result = {
isError: false,
imageBuffer: primaryBuf,
imageData: dataUrl,
images: imagesBuffers.length ? imagesBuffers.map(
(b) => `data:image/png;base64,${b.toString("base64")}`
) : void 0,
metadata: {
alt: `Image-to-image from prompt: ${request.prompt}`,
inference_time_ms: endTime - startTime,
model: payloadModel,
width: effW,
height: effH,
requested_dimensions: {
width: effW,
height: effH
},
steps: Number.isFinite(Number(payloadSteps)) ? Number(payloadSteps) : void 0,
seed: typeof payloadSeed === "number" && Number.isFinite(payloadSeed) ? payloadSeed : void 0,
seed_mode: typeof payloadSeedMode === "string" && payloadSeedMode.trim() ? payloadSeedMode : void 0,
prompt_used: String(request.prompt || ""),
prompt_origin: promptOriginI2I,
...configBytes && { config_v2: generationConfigBytesToV2(configBytes) },
transport: "grpc",
stream_chunks: imagesBuffers.length,
num_frames: payloadNumFrames,
fps: payloadFps,
// Overlay source tracking for audit
overlay_source: overlaySource,
...overlayPreset && { overlay_preset: overlayPreset },
...overlayNote && { overlay_note: overlayNote },
...defaultsUsed && { defaults_used: defaultsUsed },
...overlayLookupMode && { overlay_lookup_mode: overlayLookupMode },
...i2iProfileUsed && { i2i_profile: i2iProfileUsed },
...typeof strengthUsed === "number" && { strength_used: strengthUsed },
...typeof stepsUsed === "number" && { steps_used: stepsUsed },
...samplerUsed && { sampler_used: samplerUsed },
...typeof guidanceScaleUsed === "number" && {
guidance_scale_used: guidanceScaleUsed
},
...typeof shiftUsed === "number" && { shift_used: shiftUsed },
...typeof resolutionDependentShiftUsed === "boolean" && {
resolution_dependent_shift_used: resolutionDependentShiftUsed
},
...compressionArtifactsUsed != null && {
compression_artifacts_used: compressionArtifactsUsed
},
...compressionArtifactsQualityUsed != null && {
compression_artifacts_quality_used: compressionArtifactsQualityUsed
},
...requiredLoraFiles && requiredLoraFiles.length > 0 && { loras_used: requiredLoraFiles }
},
audioBuffers: audioBuffers.length > 0 ? audioBuffers : void 0
};
__cleanupTmp();
return result;
} catch (e) {
try {
} catch {
}
return this.toBackendError(e);
}
}
/** Edit mode generation with multiple reference images. */
async generateImageEdit(inputParams = {}, referenceBuffers, onProgress, maskBuffer) {
const isVideoEdit = inputParams?._dt_video_mode === "img2vid";
const rawProfile = inputParams?._dt_i2i_profile;
const i2iProfileUsed = rawProfile === "img2img" ? "img2img" : rawProfile === "inpaint" || rawProfile === "outpaint" ? rawProfile : "edit";
const overlayMode = isVideoEdit ? "img2vid" : i2iProfileUsed;
const modeLabel = overlayMode === "img2img" ? "image2image" : overlayMode === "img2vid" ? "image2video" : "edit";
if (!referenceBuffers || referenceBuffers.length === 0) {
return {
isError: true,
errorMessage: "Edit mode requires at least one reference image"
};
}
if (referenceBuffers.length > 1 && !isVideoEdit && rawProfile !== "img2img" && rawProfile !== "edit" && rawProfile !== "inpaint" && rawProfile !== "outpaint") {
try {
logFile2(
"[multi-ref] WARNING: _dt_i2i_profile missing; defaulting to edit profile. This indicates a core/service interface regression."
);
} catch {
}
}
if (referenceBuffers.length === 1) {
const effectiveProfile = rawProfile === "restore" || rawProfile === "img2img" || rawProfile === "inpaint" || rawProfile === "outpaint" ? rawProfile : "edit";
const editParams = { ...inputParams, _dt_i2i_profile: effectiveProfile };
return this.generateImageImg2Img(editParams, referenceBuffers[0], onProgress, maskBuffer);
}
try {
const __tmpDirs = [];
const __registerTmp = (d) => {
try {
__tmpDirs.push(d);
} catch {
}
};
const __cleanupTmp = () => {
for (const d of __tmpDirs) {
try {
fs26.rmSync(d, { recursive: true, force: true });
} catch {
}
}
};
const audit = buildAuditLogger({
backend: this.name,
mode: overlayMode === "inpaint" || overlayMode === "outpaint" ? "edit" : overlayMode
});
this.ensureClient();
let overlaySource = "default";
let overlayPreset;
let overlayNote;
let defaultsUsed;
let overlayLookupMode;
let strengthUsed;
let stepsUsed;
let samplerUsed;
let guidanceScaleUsed;
let shiftUsed;
let resolutionDependentShiftUsed;
let requiredLoraFiles;
const baseDefaults = isVideoEdit ? defaultParamsImage2Video : overlayMode === "edit" || overlayMode === "inpaint" || overlayMode === "outpaint" ? defaultParamsImg2Img2 : defaultParamsImg2Img;
const baseLimits = isVideoEdit ? drawthingsLimits : overlayMode === "edit" || overlayMode === "inpaint" || overlayMode === "outpaint" ? drawthingsLimits : drawthingsLimits;
let params = {};
try {
const r = validateImageGenerationParams(inputParams);
if (r.valid) params = inputParams;
} catch {
}
if (!params.prompt)
params.prompt = inputParams.prompt || baseDefaults.prompt;
try {
const variants = inputParams.variants;
if (typeof variants === "number") {
const v = Math.max(1, Math.min(4, Math.round(variants)));
params.batch_size = v;
params.batch_count = 1;
}
} catch {
}
if (isVideoEdit) {
const rawNumFrames = inputParams.numFrames;
if (typeof rawNumFrames === "number" && rawNumFrames > 1) {
const normalized = normalizeNumFrames(rawNumFrames);
params.num_frames = normalized.value;
if (normalized.hint) console.info(`[img2vid] ${normalized.hint}`);
}
}
const resolveEncoderCmd = () => {
const envCmd = process.env.DT_ENCODER_CMD;
const projectRoot2 = __resolveProjectRootFrom(__svcDir());
const candidates = buildTensorHelperCandidates(
projectRoot2,
"PNG2GRPCBin",
envCmd
);
for (const c of candidates) {
try {
const abs = path29.isAbsolute(c) ? c : path29.resolve(projectRoot2, c);
if (!fs26.existsSync(abs)) continue;
const origin = c === envCmd ? "env" : "auto";
if (abs.endsWith(".js")) {
return {
cmd: process.execPath,
argsPrefix: [abs],
display: abs,
impl: "ts",
origin
};
}
try {
const st = fs26.statSync(abs);
if ((st.mode & 73) === 0) {
try {
fs26.chmodSync(abs, 493);
} catch {
}
}
} catch {
}
return {
cmd: abs,
argsPrefix: [],
display: abs,
impl: "mac-bin",
origin
};
} catch {
}
}
return null;
};
const encoderCmd = resolveEncoderCmd();
logToolSelection("edit encode", encoderCmd);
if (!encoderCmd) {
return {
isError: true,
errorMessage: "PNG2GRPCBin encoder not found for multi-reference edit"
};
}
const contentsTensors = [];
let primaryHash = null;
const moodboardHashes = [];
let canvasW;
let canvasH;
for (let i = 0; i < referenceBuffers.length; i++) {
const refBuf = referenceBuffers[i];
const pngBuf = await toPng(refBuf);
if (i === 0) {
try {
const meta = await getSize(pngBuf);
canvasW = meta.width;
canvasH = meta.height;
} catch {
}
}
const tmpDir = fs26.mkdtempSync(
path29.join(os8.tmpdir(), `${clientName()}-edit-${i}-`)
);
__registerTmp(tmpDir);
const pngPath = path29.join(tmpDir, "input.png");
const imgBinPath = path29.join(tmpDir, "image.bin");
fs26.writeFileSync(pngPath, pngBuf);
const args = ["--in", pngPath, "--out", imgBinPath];
const proc = spawnSync(
encoderCmd.cmd,
[...encoderCmd.argsPrefix, ...args],
{
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env }
}
);
if (proc.error) {
__cleanupTmp();
return {
isError: true,
errorMessage: `Encoder failed for reference ${i + 1}: ${proc.error.message}`
};
}
if (typeof proc.status === "number" && proc.status !== 0) {
const stdout = proc.stdout ? proc.stdout.toString("utf8") : "";
const stderr = proc.stderr ? proc.stderr.toString("utf8") : "";
logErr(
`[edit] encoder exit=${proc.status} ref=${i + 1} cmd=${encoderCmd.cmd} ${[...encoderCmd.argsPrefix, ...args].join(" ")}`
);
if (stdout.trim())
logFile2(`[edit] encoder stdout ref=${i + 1}: ${stdout.trim()}`);
if (stderr.trim())
logErr(`[edit] encoder stderr ref=${i + 1}: ${stderr.trim()}`);
__cleanupTmp();
return {
isError: true,
errorMessage: `Encoder failed for reference ${i + 1} (exit ${proc.status})${stderr.trim() ? `: ${stderr.trim()}` : ""}`
};
}
if (!fs26.existsSync(imgBinPath) || fs26.statSync(imgBinPath).size === 0) {
const stdout = proc.stdout ? proc.stdout.toString("utf8") : "";
const stderr = proc.stderr ? proc.stderr.toString("utf8") : "";
if (stdout.trim())
logFile2(`[edit] encoder stdout ref=${i + 1}: ${stdout.trim()}`);
if (stderr.trim())
logErr(`[edit] encoder stderr ref=${i + 1}: ${stderr.trim()}`);
__cleanupTmp();
return {
isError: true,
errorMessage: `Encoder produced no output for reference ${i + 1}`
};
}
const blob = fs26.readFileSync(imgBinPath);
contentsTensors.push(blob);
const tensorHash = crypto2.createHash("sha256").update(blob).digest();
if (i === 0) {
primaryHash = tensorHash;
} else {
moodboardHashes.push(tensorHash);
}
try {
fs26.unlinkSync(pngPath);
} catch {
}
try {
fs26.unlinkSync(imgBinPath);
} catch {
}
}
logFile2(
`[${modeLabel}] encoded ${contentsTensors.length} reference images for multi-ref`
);
if (canvasW && canvasH) {
params.original_width = canvasW;
params.original_height = canvasH;
const hasW = typeof params.width === "number" && Number.isFinite(params.width);
const hasH = typeof params.height === "number" && Number.isFinite(params.height);
if (!hasW) params.width = canvasW;
if (!hasH) params.height = canvasH;
const hasTW = typeof params.target_width === "number" && Number.isFinite(params.target_width);
const hasTH = typeof params.target_height === "number" && Number.isFinite(params.target_height);
if (!hasTW) params.target_width = params.width;
if (!hasTH) params.target_height = params.height;
}
let configBytes = void 0;
let payloadWidth;
let payloadHeight;
let payloadSteps;
let payloadSeed;
let payloadSeedMode;
let payloadModel;
let payloadNumFrames = 1;
let payloadFps = 24;
try {
const allowedKeys = new Set(Object.keys(baseDefaults));
const filtered = {};
for (const [k, v] of Object.entries(params)) {
if (allowedKeys.has(k)) filtered[k] = v;
}
const modelId = params.model;
const {
source,
presetName,
note,
params: overlayParams
} = getEffectiveOverlay(modelId, overlayMode === "inpaint" || overlayMode === "outpaint" ? "edit" : overlayMode);
const overlayParamsNoSize = (() => {
if (!overlayParams) return overlayParams;
const o = { ...overlayParams };
delete o.width;
delete o.height;
delete o.batch_count;
delete o.batch_size;
delete o.batchCount;
delete o.batchSize;
delete o.upscaler;
delete o.upscaler_scale;
delete o.upscalerScale;
delete o.fps;
return o;
})();
overlaySource = source;
overlayPreset = presetName;
overlayNote = note;
if (modelId === "auto") {
delete filtered.model;
}
if (overlayParams) {
logFile2(
`Applying ${source} overlay for '${modelId ?? "auto"}' (${modeLabel}, gRPC)${presetName ? ` preset=${presetName}` : ""}`
);
delete filtered.model;
}
audit.setOutput({
overlay_source: source,
...presetName && { overlay_preset: presetName },
...note && { overlay_note: note }
});
const effective = {
...baseDefaults,
...overlayParamsNoSize || {},
...filtered,
seed: baseDefaults.seed
};
{
const sub = overlaySource === "custom" ? { file: "", substituted: false } : substituteInstalledPrecision(String(effective.model ?? ""), await currentInventory());
if (sub.substituted) {
const note2 = substitutionNote(String(effective.model), sub.file);
effective.model = sub.file;
overlayNote = overlayNote ? `${overlayNote} ${note2}` : note2;
logFile2(note2);
}
}
defaultsUsed = isVideoEdit ? "defaultParamsDrawThingsImage2Video" : overlayMode === "edit" || overlayMode === "inpaint" || overlayMode === "outpaint" ? "defaultParamsDrawThingsEdit" : "defaultParamsDrawThingsImg2Img";
overlayLookupMode = overlayMode;
strengthUsed = typeof effective.strength === "number" && Number.isFinite(effective.strength) ? effective.strength : void 0;
stepsUsed = typeof effective.steps === "number" && Number.isFinite(effective.steps) ? effective.steps : void 0;
samplerUsed = typeof effective.sampler === "string" && String(effective.sampler).trim() ? String(effective.sampler) : void 0;
guidanceScaleUsed = typeof effective.guidance_scale === "number" && Number.isFinite(effective.guidance_scale) ? effective.guidance_scale : void 0;
shiftUsed = typeof effective.shift === "number" && Number.isFinite(effective.shift) ? effective.shift : void 0;
resolutionDependentShiftUsed = typeof effective.resolution_dependent_shift === "boolean" ? effective.resolution_dependent_shift : void 0;
audit.setOutput({
overlay_lookup_mode: overlayMode === "inpaint" || overlayMode === "outpaint" ? "edit" : overlayMode,
defaults_used: defaultsUsed,
strength_used: typeof effective.strength === "number" && Number.isFinite(effective.strength) ? effective.strength : void 0,
steps_used: typeof effective.steps === "number" && Number.isFinite(effective.steps) ? effective.steps : void 0,
sampler_used: typeof effective.sampler === "string" && String(effective.sampler).trim() ? String(effective.sampler) : void 0,
guidance_scale_used: typeof effective.guidance_scale === "number" && Number.isFinite(effective.guidance_scale) ? effective.guidance_scale : void 0,
shift_used: typeof effective.shift === "number" && Number.isFinite(effective.shift) ? effective.shift : void 0,
resolution_dependent_shift_used: typeof effective.resolution_dependent_shift === "boolean" ? effective.resolution_dependent_shift : void 0
});
try {
const userSpecifiedLoras = Object.prototype.hasOwnProperty.call(
filtered,
"loras"
);
const overlaySelected = !!overlayParams;
if (userSpecifiedLoras) {
const ls = Array.isArray(filtered.loras) ? filtered.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else if (overlaySelected) {
const ls = Array.isArray(overlayParams?.loras) ? overlayParams.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
} else {
const ls = Array.isArray(effective?.loras) ? effective.loras : [];
requiredLoraFiles = ls.map((x) => x?.file).filter((x) => typeof x === "string" && x.trim()).map((x) => String(x).trim());
}
} catch {
}
const cfg = buildDtGenerationConfiguration(effective);
configBytes = cfg.bytes && cfg.bytes.length ? cfg.bytes : void 0;
try {
const view = cfg?.view || {};
payloadWidth = view.width;
payloadHeight = view.height;
payloadSteps = view.steps;
payloadSeed = view.seed;
payloadSeedMode = view.seed_mode;
payloadModel = String(effective.model || "");
payloadNumFrames = typeof effective.num_frames === "number" ? effective.num_frames : 1;
payloadFps = (typeof filtered.fps === "number" ? filtered.fps : void 0) ?? getDefaultFpsForModel(payloadModel) ?? (typeof effective.fps === "number" ? effective.fps : 24);
} catch {
}
} catch {
}
const sharedSecret = process.env.DRAWTHINGS_SHARED_SECRET;
const moodboardWeight = moodboardHashes.length > 0 ? 1 / moodboardHashes.length : 1;
const shuffleHints = moodboardHashes.map((hash) => ({
tensor: hash,
// SHA256 hash (32 bytes) referencing tensor in contents[]
weight: moodboardWeight
}));
const request = {
prompt: String(params.prompt || baseDefaults.prompt),
negativePrompt: String(params.negative_prompt || ""),
scaleFactor: 1,
keywords: [],
user: clientName(),
device: "LAPTOP",
chunked: true,
...sharedSecret ? { sharedSecret } : {},
image: primaryHash,
// Hash of first (canvas) image
contents: contentsTensors,
// All reference tensors (Content-Addressable Storage)
// Moodboard images as shuffle hints
...shuffleHints.length > 0 ? {
hints: [
{
hintType: "shuffle",
// MUST be "shuffle" for moodboard/reference images
tensors: shuffleHints
}
]
} : {}
};
if (configBytes) request.configuration = configBytes;
logFile2(
`[${modeLabel}] request built: canvas=1, moodboard=${shuffleHints.length}, total_contents=${contentsTensors.length}`
);
const call = this.cancellableGenerateCall();
if (typeof call !== "function")
throw new Error(`gRPC method not found: ${this.methodGenerate}`);
const startTime = Date.now();
const imagesBuffers = [];
const audioBuffers = [];
let chunkAccum = null;
let previewBuf = null;
let lastSeenStep = 0;
const handleData = (resp) => {
try {
if (resp?.currentSignpost?.sampling?.step) {
const currentStep = resp.currentSignpost.sampling.step;
lastSeenStep = currentStep;
console.info(
`gRPC progress: sampling step=${currentStep}`
);
logFile2(
`edit progress: sampling step=${currentStep}`
);
if (onProgress) {
try {
onProgress(
currentStep,
payloadSteps,
`Sampling step ${currentStep}${payloadSteps ? `/${payloadSteps}` : ""}`
);
} catch {
}
}
} else if (resp?.currentSignpost != null && onProgress) {
const sp = resp.currentSignpost;
let label;
if (lastSeenStep === 0) {
if (sp.textEncoded != null) label = "Loading...";
else if (sp.imageEncoded != null) label = "Processing...";
} else {
label = "Finishing...";
}
if (label) {
try {
onProgress(-1, payloadSteps, label);
} catch {
}
}
}
if (resp?.generatedImages && Array.isArray(resp.generatedImages)) {
const list = resp.generatedImages.map(
(b) => Buffer.isBuffer(b) ? b : Buffer.from(b)
);
const cs = resp?.chunkState;
const isMore = cs === 1 || cs === "MORE_CHUNKS";
const isLast = cs === 0 || cs === "LAST_CHUNK";
if (isMore) {
if (list.length > 0) {
chunkAccum = chunkAccum ? Buffer.concat([chunkAccum, list[0]]) : Buffer.from(list[0]);
}
} else if (isLast && list.length > 0) {
if (chunkAccum) {
const full = Buffer.concat([chunkAccum, list[0]]);
imagesBuffers.push(full);
chunkAccum = null;
} else {
for (const buf of list) imagesBuffers.push(buf);
}
} else {
for (const buf of list) imagesBuffers.push(buf);
}
}
if (resp?.previewImage) {
const b = resp.previewImage;
previewBuf = Buffer.isBuffer(b) ? b : Buffer.from(b);
}
if (resp?.generatedAudio && Array.isArray(resp.generatedAudio)) {
for (const a of resp.generatedAudio) {
const ab = Buffer.isBuffer(a) ? a : Buffer.from(a);
if (ab.length > 0) audioBuffers.push(ab);
}
}
} catch {
}
};
await new Promise((resolve, reject) => {
try {
const stream = call(request);
stream.on("data", handleData);
stream.on("error", (err) => reject(err));
stream.on("end", () => resolve());
} catch (e) {
reject(e);
}
});
const endTime = Date.now();
const resolveDecoderCmd = () => {
const envCmd = process.env.DT_DECODER_CMD;
const projectRoot2 = __projectRoot();
const candidates = buildTensorHelperCandidates(
projectRoot2,
"GRPCBin2PNG",
envCmd
);
for (const c of candidates) {
try {
const abs = path29.isAbsolute(c) ? c : path29.resolve(projectRoot2, c);
if (!fs26.existsSync(abs)) continue;
const origin = c === envCmd ? "env" : "auto";
if (abs.endsWith(".js")) {
return {
cmd: process.execPath,
argsPrefix: [abs],
display: abs,
impl: "ts",
origin
};
}
try {
const st = fs26.statSync(abs);
if ((st.mode & 73) === 0) {
try {
fs26.chmodSync(abs, 493);
} catch {
}
}
} catch {
}
return {
cmd: abs,
argsPrefix: [],
display: abs,
impl: "mac-bin",
origin
};
} catch {
}
}
return null;
};
const decoderCmd = resolveDecoderCmd();
const decoderProfile = resolveTensorDecoderProfile(payloadModel);
logToolSelection("edit decode", decoderCmd);
let primaryBuf = null;
logTensorSource("edit-multiref", imagesBuffers, previewBuf, payloadModel);
if (decoderCmd && imagesBuffers.length > 0) {
const pngBuffers = [];
for (let i = 0; i < imagesBuffers.length; i++) {
const rawBuf = imagesBuffers[i];
try {
const tmpDir = fs26.mkdtempSync(
path29.join(os8.tmpdir(), `${clientName()}-dec-${i}-`)
);
__registerTmp(tmpDir);
const inPath = path29.join(tmpDir, "input.bin");
const outPath = path29.join(tmpDir, "output.png");
fs26.writeFileSync(inPath, rawBuf);
const proc = spawnSync(
decoderCmd.cmd,
[
...decoderCmd.argsPrefix,
"--in",
inPath,
"--out",
outPath,
"--profile",
decoderProfile
],
{
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env }
}
);
if (!proc.error && fs26.existsSync(outPath) && fs26.statSync(outPath).size > 0) {
pngBuffers.push(fs26.readFileSync(outPath));
}
} catch {
}
}
if (pngBuffers.length > 0) {
primaryBuf = pngBuffers[0];
imagesBuffers.length = 0;
for (const b of pngBuffers) imagesBuffers.push(b);
}
}
if (!primaryBuf && previewBuf) {
primaryBuf = previewBuf;
}
if (!primaryBuf)
throw new Error("gRPC edit stream yielded no image data");
const dataUrl = `data:image/png;base64,${primaryBuf.toString("base64")}`;
logFile2(
`edit completed: refs=${referenceBuffers.length}, images=${imagesBuffers.length}, bytes=${primaryBuf.length}`
);
const effW = Number(payloadWidth ?? params.width ?? 1024);
const effH = Number(payloadHeight ?? params.height ?? 1024);
const result = {
isError: false,
imageBuffer: primaryBuf,
imageData: dataUrl,
images: imagesBuffers.length ? imagesBuffers.map(
(b) => `data:image/png;base64,${b.toString("base64")}`
) : void 0,
metadata: {
alt: overlayMode === "img2img" ? `Image-to-image from prompt: ${request.prompt}` : `Edit from prompt: ${request.prompt}`,
inference_time_ms: endTime - startTime,
model: payloadModel,
width: effW,
height: effH,
requested_dimensions: {
width: effW,
height: effH
},
steps: Number.isFinite(Number(payloadSteps)) ? Number(payloadSteps) : void 0,
seed: typeof payloadSeed === "number" && Number.isFinite(payloadSeed) ? payloadSeed : void 0,
seed_mode: typeof payloadSeedMode === "string" && payloadSeedMode.trim() ? payloadSeedMode : void 0,
prompt_used: String(request.prompt || ""),
reference_count: referenceBuffers.length,
...configBytes && { config_v2: generationConfigBytesToV2(configBytes) },
transport: "grpc",
stream_chunks: imagesBuffers.length,
num_frames: payloadNumFrames,
fps: payloadFps,
// Overlay source tracking for audit
overlay_source: overlaySource,
...overlayPreset && { overlay_preset: overlayPreset },
...overlayNote && { overlay_note: overlayNote },
...defaultsUsed && { defaults_used: defaultsUsed },
...overlayLookupMode && { overlay_lookup_mode: overlayLookupMode },
i2i_profile: i2iProfileUsed,
...typeof strengthUsed === "number" && { strength_used: strengthUsed },
...typeof stepsUsed === "number" && { steps_used: stepsUsed },
...samplerUsed && { sampler_used: samplerUsed },
...typeof guidanceScaleUsed === "number" && {
guidance_scale_used: guidanceScaleUsed
},
...typeof shiftUsed === "number" && { shift_used: shiftUsed },
...typeof resolutionDependentShiftUsed === "boolean" && {
resolution_dependent_shift_used: resolutionDependentShiftUsed
},
...requiredLoraFiles && requiredLoraFiles.length > 0 && { loras_used: requiredLoraFiles }
},
audioBuffers: audioBuffers.length > 0 ? audioBuffers : void 0
};
__cleanupTmp();
return result;
} catch (e) {
return this.toBackendError(e);
}
}
};
// src/helpers/imageModelMeta.ts
import path30 from "node:path";
function normalizeModelFilenameForLookup(value) {
return path30.basename(value).trim().toLowerCase();
}
function resolveModelFamilyFromModelBasename(modelBasename2) {
const normalized = normalizeModelFilenameForLookup(modelBasename2);
if (!normalized) return "unknown";
for (const family2 of ["z-image", "qwen-image", "flux", "ltx"]) {
for (const mode of ["txt2img", "img2img", "edit", "txt2vid", "img2vid"]) {
const m = getModelFilename(family2, mode);
if (typeof m !== "string") continue;
if (normalizeModelFilenameForLookup(m) === normalized) return family2;
}
}
for (const family2 of ["z-image", "qwen-image", "flux", "ltx"]) {
const key = MODEL_PRESET_TO_CAPABILITY_KEY?.[family2];
if (typeof key !== "string") continue;
const cap = IMAGE_MODEL_CAPABILITY_MAP?.[key];
const filenames = cap?.modelFilenames;
if (!Array.isArray(filenames)) continue;
for (const f of filenames) {
if (typeof f !== "string") continue;
if (normalizeModelFilenameForLookup(f) === normalized) return family2;
}
}
const customLabels = getCustomPresetLabelsUsingModelFilename(normalized);
if (customLabels.length > 0) return "custom";
return "unknown";
}
function modeToUserMode(mode) {
switch (mode) {
case "txt2img":
return "text2image";
case "img2img":
return "image2image";
case "txt2vid":
return "text2video";
case "img2vid":
return "image2video";
case "edit":
return "edit";
}
}
function userModeToMode(mode) {
switch (mode) {
case "text2image":
return "txt2img";
case "image2image":
return "img2img";
case "text2video":
return "txt2vid";
case "image2video":
return "img2vid";
case "edit":
return "edit";
}
}
function getDefaultModelForMode2(mode) {
const raw = mode === "txt2img" ? defaultParams?.model : mode === "img2img" ? defaultParamsImg2Img?.model : mode === "txt2vid" ? defaultParamsText2Video?.model : mode === "img2vid" ? defaultParamsImage2Video?.model : defaultParamsImg2Img2?.model;
return typeof raw === "string" ? raw : "";
}
function computeEffectiveModelFilename(modelId, mode) {
const base = getDefaultModelForMode2(mode);
const baseBase = normalizeModelFilenameForLookup(base);
const overlay = getEffectiveOverlay(modelId, mode);
const overlayModel = overlay.params?.model;
const chosen = typeof overlayModel === "string" && overlayModel.trim() ? overlayModel : base;
const chosenBase = normalizeModelFilenameForLookup(chosen);
return {
modelBasename: chosenBase || baseBase,
overlaySource: overlay.source,
presetName: overlay.presetName
};
}
function scorePresetForDisplay(p) {
const isAuto = p.modelId === "auto";
const isCustomConfig = p.overlaySource === "custom";
const isOverlay = p.overlaySource === "modelOverlay";
return (isCustomConfig ? 100 : isOverlay ? 50 : 0) + (isAuto ? 10 : 0);
}
function pickDisplayPreset(presets) {
if (!presets.length) return void 0;
return [...presets].sort((a, b) => scorePresetForDisplay(b) - scorePresetForDisplay(a))[0];
}
function resolveImageModelInfoFromModelUsed(modelFilenameOrPath, opts) {
if (typeof modelFilenameOrPath !== "string") return null;
const base = path30.basename(modelFilenameOrPath).trim();
if (!base) return null;
const normalized = normalizeModelFilenameForLookup(base);
const modes = opts?.mode ? [userModeToMode(opts.mode)] : ["txt2img", "img2img", "edit", "txt2vid", "img2vid"];
const presets = [];
for (const mode of modes) {
for (const modelId of MODEL_IDS) {
const eff = computeEffectiveModelFilename(modelId, mode);
if (!eff.modelBasename) continue;
if (eff.modelBasename !== normalized) continue;
if (eff.overlaySource === "default" && modelId !== "auto") continue;
const userMode = modeToUserMode(mode);
const preset = `${userMode}.${modelId}`;
presets.push({
mode: userMode,
modelId,
preset,
overlaySource: eff.overlaySource,
...eff.presetName ? { customConfig: eff.presetName } : {}
});
}
}
const customConfigLabels = getCustomPresetLabelsUsingModelFilename(base);
const chosen = pickDisplayPreset(presets);
const modelFamily = resolveModelFamilyFromModelBasename(base);
const display = modelFamily && modelFamily !== "unknown" ? `${modelFamily} (${base})` : base;
return {
modelUsedBasename: base,
display,
...chosen ? { chosen_model_id: chosen.modelId } : {},
...modelFamily ? { model_family: modelFamily } : {},
presets,
...customConfigLabels.length ? { custom_config_labels: customConfigLabels } : {}
};
}
function formatImageModelForToolDisplay(modelFilenameOrPath) {
const info = resolveImageModelInfoFromModelUsed(modelFilenameOrPath);
return info?.display ?? "";
}
// src/services/defaultParamsPreviewAnalyse.ts
var previewDefaults = {
previewFormat: "jpeg",
previewMaxWidth: 1024,
previewQuality: 85
};
// src/services/mediaReconcile/reconcile.ts
import path31 from "path";
// src/services/mediaReconcile/types.ts
var DEFAULT_RECONCILE_OPTIONS = {
attachment: {
strategy: "replace",
generatePreviews: true,
maxPreviews: 5
// Only top 5 attachments get previews (for Vision)
},
variant: {
strategy: "merge",
generatePreviews: false
// Previews created by generate_image tool
},
picture: {
strategy: "merge",
generatePreviews: true
// Download and create preview from URL
},
image: {
strategy: "merge",
generatePreviews: false
// Previews created by generating tool
}
};
// src/services/mediaReconcile/reconcile.ts
function getIdentifierKey(mediaType) {
switch (mediaType) {
case "attachment":
return "originAbs";
// Absolute path to original file
case "variant":
return "filename";
// Filename in chatWd
case "picture":
return "sourceUrl";
// Original URL
case "image":
return "filename";
// Filename in chatWd
default:
return "filename";
}
}
function getIndexKey(mediaType) {
const config = MEDIA_SOURCE_REGISTRY[mediaType];
return config?.indexPrefix ?? "n";
}
function normalizeIdentifier(id, mediaType) {
if (mediaType === "attachment") {
try {
return path31.resolve(id);
} catch {
return id;
}
}
return id;
}
function candidateToRecord(candidate, index2, mediaType) {
const indexKey = getIndexKey(mediaType);
const base = {
[indexKey]: index2,
turnId: candidate.turnId
};
switch (mediaType) {
case "attachment":
return {
...base,
originAbs: candidate.identifier
// filename and preview will be set during import
};
case "variant":
return {
...base,
filename: candidate.identifier,
// preview expected to exist alongside original
preview: `preview-${path31.basename(candidate.identifier, ".png")}.jpg`,
// Persist provenance (mirrors "picture"/"image" cases below).
sourceTool: candidate.sourceTool,
pluginId: candidate.pluginId
};
case "picture":
return {
sourceUrl: candidate.identifier,
title: candidate.title,
sourceTool: candidate.sourceTool,
pluginId: candidate.pluginId,
turnId: candidate.turnId,
[indexKey]: index2
};
case "image": {
const sourceTool = candidate.pluginId && candidate.sourceTool ? `${candidate.pluginId}, ${candidate.sourceTool}` : candidate.sourceTool;
return {
filename: candidate.identifier,
preview: `preview-${path31.basename(
candidate.identifier,
path31.extname(candidate.identifier)
)}.jpg`,
sourceTool,
// kind: undefined - set by caller if needed
turnId: candidate.turnId,
// createdAt: undefined - set by appendImages if missing
[indexKey]: index2
};
}
default:
return base;
}
}
async function reconcileMedia(chatWd, stateArray, mediaType, candidates, options) {
const { strategy, debug } = options;
const identifierKey = getIdentifierKey(mediaType);
const indexKey = getIndexKey(mediaType);
if (debug) {
console.info(
`[reconcileMedia] ${mediaType}: ${candidates.length} candidates, strategy=${strategy}`
);
}
if (strategy === "replace") {
return reconcileReplace(
chatWd,
stateArray,
mediaType,
candidates,
identifierKey,
indexKey,
options
);
} else {
return reconcileMerge(
chatWd,
stateArray,
mediaType,
candidates,
identifierKey,
indexKey,
options
);
}
}
async function reconcileReplace(chatWd, stateArray, mediaType, candidates, identifierKey, indexKey, options) {
const { debug } = options;
if (candidates.length === 0) {
if (debug) {
console.info(
`[reconcileMedia] ${mediaType}: No candidates, keeping existing state`
);
}
return {
result: {
added: 0,
removed: 0,
unchanged: stateArray.length,
stateChanged: false
},
newArray: stateArray
};
}
const existingByIdentifier = /* @__PURE__ */ new Map();
for (const record of stateArray) {
const id = record[identifierKey];
if (typeof id === "string") {
existingByIdentifier.set(normalizeIdentifier(id, mediaType), record);
}
}
const newArray = [];
let added = 0;
let unchanged = 0;
for (let i = 0; i < candidates.length; i++) {
const candidate = candidates[i];
const normalizedId = normalizeIdentifier(candidate.identifier, mediaType);
const existing = existingByIdentifier.get(normalizedId);
if (existing) {
const updated = { ...existing };
updated[indexKey] = i + 1;
if (candidate.turnId !== void 0) {
updated.turnId = candidate.turnId;
}
newArray.push(updated);
unchanged++;
} else {
const record = candidateToRecord(candidate, i + 1, mediaType);
newArray.push(record);
added++;
}
}
const removed = stateArray.length - unchanged;
const stateChanged = added > 0 || removed > 0;
if (debug) {
console.info(
`[reconcileMedia] ${mediaType}: added=${added}, removed=${removed}, unchanged=${unchanged}`
);
}
return {
result: { added, removed, unchanged, stateChanged },
newArray
};
}
async function reconcileMerge(chatWd, stateArray, mediaType, candidates, identifierKey, indexKey, options) {
const { debug } = options;
if (candidates.length === 0) {
if (debug) {
console.info(
`[reconcileMedia] ${mediaType}: No candidates, keeping existing state (merge)`
);
}
return {
result: {
added: 0,
removed: 0,
unchanged: stateArray.length,
stateChanged: false
},
newArray: stateArray
};
}
const candidateIds = /* @__PURE__ */ new Set();
for (const c of candidates) {
candidateIds.add(normalizeIdentifier(c.identifier, mediaType));
}
const existingByIdentifier = /* @__PURE__ */ new Map();
for (const record of stateArray) {
const id = record[identifierKey];
if (typeof id === "string") {
existingByIdentifier.set(normalizeIdentifier(id, mediaType), record);
}
}
const newArray = [];
let removed = 0;
let unchanged = 0;
for (const record of stateArray) {
const id = record[identifierKey];
if (typeof id !== "string") {
removed++;
continue;
}
const normalizedId = normalizeIdentifier(id, mediaType);
if (candidateIds.has(normalizedId)) {
newArray.push(record);
unchanged++;
} else {
if (debug) {
console.info(
`[reconcileMedia] ${mediaType}: Removing deleted item: ${id}`
);
}
removed++;
}
}
let added = 0;
let nextIndex = Math.max(
0,
...newArray.map((r) => {
const idx = r[indexKey];
return typeof idx === "number" ? idx : 0;
})
) + 1;
for (const candidate of candidates) {
const normalizedId = normalizeIdentifier(candidate.identifier, mediaType);
if (!existingByIdentifier.has(normalizedId)) {
const record = candidateToRecord(candidate, nextIndex, mediaType);
newArray.push(record);
added++;
nextIndex++;
}
}
const stateChanged = added > 0 || removed > 0;
if (debug) {
console.info(
`[reconcileMedia] ${mediaType}: added=${added}, removed=${removed}, unchanged=${unchanged}`
);
}
return {
result: { added, removed, unchanged, stateChanged },
newArray
};
}
function getStateArrayKey(mediaType) {
switch (mediaType) {
case "attachment":
return "attachments";
case "variant":
return "variants";
case "picture":
return "pictures";
case "image":
return "images";
default:
return `${mediaType}s`;
}
}
// src/tools/review_image.ts
import { tool } from "@lmstudio/sdk";
import { z as z2 } from "zod";
import path32 from "path";
import fs27 from "fs";
var FlexibleTargetsList = z2.union([
// String form: split by comma/space
z2.string().transform(
(s) => s.split(/[\s,]+/).map((x) => x.trim()).filter((x) => x.length > 0)
),
// Array form: pass through
z2.array(z2.string())
]).refine((arr) => arr.length >= 1, "targets must contain at least one notation").refine((arr) => arr.length <= 32, "targets must contain at most 32 notations");
var ReviewImageParamsShape = {
targets: FlexibleTargetsList
};
function normalizeTargetNotationToken(raw) {
let s = String(raw ?? "").trim();
if (!s) return "";
s = s.replace(/^[\[{(]+/, "").replace(/[\]})]+$/, "");
s = s.replace(/^['"`]+|['"`]+$/g, "");
s = s.replace(/[;:.!?]+$/, "");
s = s.trim().toLowerCase();
if (/^[avip]$/i.test(s)) return `${s}1`;
return s;
}
function normalizeTargetsArg(rawTargets) {
const fromArray = (arr) => arr.map((x) => typeof x === "string" ? x : String(x ?? "")).map((x) => x.trim()).filter((x) => x.length > 0);
if (Array.isArray(rawTargets)) {
return fromArray(rawTargets);
}
if (typeof rawTargets === "string") {
const t = rawTargets.trim();
if (!t) return [];
if (t.startsWith("[") && t.endsWith("]")) {
try {
const parsed = JSON.parse(t);
if (Array.isArray(parsed)) {
return fromArray(parsed);
}
} catch {
}
}
return t.split(/[\s,]+/).map((x) => x.trim()).filter((x) => x.length > 0);
}
if (rawTargets == null) return [];
return [String(rawTargets)];
}
function parseTargets(targets) {
const parsed = { a: [], v: [], i: [], p: [] };
const invalid = [];
for (const raw of targets) {
const s = normalizeTargetNotationToken(raw);
const m = /^([avip])(\d+)$/i.exec(s);
if (!m) {
invalid.push(String(raw));
continue;
}
const kind = m[1].toLowerCase();
const n = parseInt(m[2], 10);
if (!Number.isFinite(n) || n <= 0) {
invalid.push(String(raw));
continue;
}
parsed[kind].push(n);
}
Object.keys(parsed).forEach((k) => {
parsed[k] = Array.from(new Set(parsed[k])).sort((a, b) => a - b);
});
return { parsed, invalid };
}
function normalizeAliasRef(input) {
const raw = String(input ?? "");
let s = raw.trim();
s = s.replace(/[)\],.;]+$/g, "");
s = s.replace(/^"(.+)"$/g, "$1");
s = s.replace(/^'(.+)'$/g, "$1");
let url;
try {
if (/^https?:\/\//i.test(s)) url = new URL(s);
} catch {
url = void 0;
}
const basename5 = (() => {
try {
if (url) return path32.posix.basename(url.pathname || "") || void 0;
return path32.basename(s) || void 0;
} catch {
return void 0;
}
})();
return { raw, trimmed: s, basename: basename5, url };
}
function resolveAliasTargets(state, refs) {
const resolved = [];
const unresolved = [];
const pushUnique = (arr, v) => {
const s = String(v || "").trim();
if (!s) return;
if (!arr.includes(s)) arr.push(s);
};
const matchByExactOrBasename = (candidate, basename5, field) => {
const v = typeof field === "string" ? field.trim() : "";
if (!v) return false;
if (v === candidate) return true;
if (!basename5) return false;
try {
return path32.basename(v) === basename5;
} catch {
return false;
}
};
for (const r of refs) {
const n = normalizeAliasRef(r);
const s = n.trimmed;
if (!s) {
unresolved.push(String(r));
continue;
}
const candidates = /* @__PURE__ */ new Set();
for (const rec of state.pictures || []) {
if (!rec || typeof rec.p !== "number") continue;
const pVal = rec.p;
if (!Number.isFinite(pVal) || pVal <= 0) continue;
if (matchByExactOrBasename(s, n.basename, rec.sourceUrl))
candidates.add(`p${pVal}`);
else if (matchByExactOrBasename(s, n.basename, rec.preview))
candidates.add(`p${pVal}`);
else if (matchByExactOrBasename(s, n.basename, rec.filename))
candidates.add(`p${pVal}`);
}
for (const rec of state.images || []) {
if (!rec || typeof rec.i !== "number") continue;
const iVal = rec.i;
if (!Number.isFinite(iVal) || iVal <= 0) continue;
if (matchByExactOrBasename(s, n.basename, rec.preview))
candidates.add(`i${iVal}`);
else if (matchByExactOrBasename(s, n.basename, rec.filename))
candidates.add(`i${iVal}`);
}
for (const rec of state.variants || []) {
if (!rec || typeof rec.v !== "number") continue;
const vVal = rec.v;
if (!Number.isFinite(vVal) || vVal <= 0) continue;
if (matchByExactOrBasename(s, n.basename, rec.preview))
candidates.add(`v${vVal}`);
else if (matchByExactOrBasename(s, n.basename, rec.filename))
candidates.add(`v${vVal}`);
else if (matchByExactOrBasename(s, n.basename, rec.sourceUrl))
candidates.add(`v${vVal}`);
}
for (const rec of state.attachments || []) {
if (!rec || typeof rec.a !== "number") continue;
const aVal = rec.a;
if (!Number.isFinite(aVal) || aVal <= 0) continue;
if (matchByExactOrBasename(s, n.basename, rec.originAbs))
candidates.add(`a${aVal}`);
else if (matchByExactOrBasename(s, n.basename, rec.preview))
candidates.add(`a${aVal}`);
else if (matchByExactOrBasename(s, n.basename, rec.filename))
candidates.add(`a${aVal}`);
}
if (candidates.size === 1) {
pushUnique(resolved, Array.from(candidates)[0]);
continue;
}
unresolved.push(String(r));
}
return { resolved, unresolved };
}
function getAvailable(state) {
const availableA = (state.attachments || []).map((x) => typeof x?.a === "number" ? x.a : void 0).filter((x) => typeof x === "number" && x > 0).sort((a, b) => a - b);
const availableV = (state.variants || []).map((x) => typeof x?.v === "number" ? x.v : void 0).filter((x) => typeof x === "number" && x > 0).sort((a, b) => a - b);
const availableI = (state.images || []).map((x) => typeof x?.i === "number" ? x.i : void 0).filter((x) => typeof x === "number" && x > 0).sort((a, b) => a - b);
const availableP = (state.pictures || []).map((x) => typeof x?.p === "number" ? x.p : void 0).filter((x) => typeof x === "number" && x > 0).sort((a, b) => a - b);
return { availableA, availableV, availableI, availableP };
}
async function ensurePreviewExists(chatWd, previewRel) {
const pAbs = path32.join(chatWd, previewRel);
await fs27.promises.access(pAbs, fs27.constants.F_OK);
}
function appendReviewToPluginLog(line) {
try {
const logsDir2 = getLogsDir();
if (!fs27.existsSync(logsDir2)) fs27.mkdirSync(logsDir2, { recursive: true });
fs27.appendFileSync(
path32.join(logsDir2, getPluginLogFilename()),
`${localTimestamp()} - ${line}
`
);
} catch {
}
}
function createReviewImageTool(ctl) {
return tool({
name: "review_image",
description: `Request visual inspection of one or more media items for the agent's analysis.
Visibility rules: This tool shows images to the agent only (for internal review/analysis). The user doesn't see anything from this call.
There are three distinct media classes, each with different visibility behaviour:
- Attachments (aN): Images provided by the user. Displayed automatically on first appearance. Use review_image to re-examine them \u2014 for a closer look, re-evaluation, or comparison.
- Variants (vN): Images or video previews produced by generate_image. Also displayed automatically once. Use review_image to return them to the agent's view for inspection or side-by-side comparison.
- Pictures (pN): A separate class \u2014 typically search results returned by image-index tools such as find_image or index_image, often in larger quantities. Pictures are NEVER shown automatically and are only made visible on explicit request via this tool.
Since each attachment and variant renders only once automatically, review_image is also the reliable way to place any selection of results side-by-side for direct visual comparison.
Parameters:
- targets: Field in the JSON argument object. Pass a JSON array of media notations, e.g. {"targets":["v1", "v2"]}.
- aN \u2014 Attachment N (e.g. a1, a2)
- vN \u2014 Generated variant N (e.g. v1, v3)
- pN \u2014 Picture / index result N (e.g. p1, p2)
Examples:
- {"targets":["v1", "v2", "v3"]} \u2014 Compare three generated variants side-by-side
- {"targets":["p1", "p2", "p3"]} \u2014 Inspect the top results from a find_image or index_image search
- {"targets":["a1", "v1"]} \u2014 Compare the original attachment with a generated result
- {"targets":["v1"]} \u2014 Re-examine a single variant for closer review
${formatToolMetaBlock()}`,
parameters: ReviewImageParamsShape,
implementation: async (args, ctx) => {
try {
try {
const workingDir2 = ctl.getWorkingDirectory();
if (typeof workingDir2 === "string" && workingDir2.trim().length > 0) {
const chatId2 = path32.basename(workingDir2);
if (/^\d+$/.test(chatId2)) {
setActiveChatContext({
chatId: chatId2,
workingDir: workingDir2,
requestId: `tool-${Date.now()}`
});
}
}
} catch {
}
const previewInChat = String(process.env.PREVIEW_IN_CHAT || "").toLowerCase() === "true";
if (previewInChat) {
const msg = 'review_image can\u2019t be used while "Simple Previews in Chat" is enabled. In that mode the plugin does not keep the local preview/index files required for re-view. Turn OFF "Simple Previews in Chat" in Global Plugin Settings, then call review_image again.';
try {
ctx.status(
"review_image unavailable: Simple Previews in Chat is enabled"
);
} catch {
}
return msg;
}
const strict = args?.strict !== void 0 ? !!args.strict : true;
const targets = normalizeTargetsArg(args?.targets);
const { parsed, invalid: invalidRaw } = parseTargets(targets);
const workingDir = ctl.getWorkingDirectory();
if (typeof workingDir !== "string" || !workingDir.trim()) {
return "review_image failed: working directory not available.";
}
const chatWd = workingDir;
const chatId = (() => {
try {
return path32.basename(chatWd);
} catch {
return "(unknown)";
}
})();
const state = await readState(chatWd);
const { resolved: resolvedAliases, unresolved: unresolvedAliases } = invalidRaw.length > 0 ? resolveAliasTargets(state, invalidRaw) : { resolved: [], unresolved: [] };
if (resolvedAliases.length > 0) {
const { parsed: parsed2, invalid: stillInvalid } = parseTargets(
resolvedAliases
);
parsed.a.push(...parsed2.a);
parsed.v.push(...parsed2.v);
parsed.i.push(...parsed2.i);
parsed.p.push(...parsed2.p);
unresolvedAliases.push(...stillInvalid);
}
Object.keys(parsed).forEach((k) => {
parsed[k] = Array.from(new Set(parsed[k])).sort((a, b) => a - b);
});
if (unresolvedAliases.length > 0 && strict) {
return `review_image failed: invalid targets: ${unresolvedAliases.map((s) => JSON.stringify(s)).join(", ")}`;
}
const { availableA, availableV, availableI, availableP } = getAvailable(state);
const missingNotations = /* @__PURE__ */ new Set();
const missingDetails = [];
for (const n of parsed.a) {
const rec = (state.attachments || []).find((x) => x?.a === n);
if (!rec) {
missingNotations.add(`a${n}`);
missingDetails.push(`a${n}`);
continue;
}
const previewRel = typeof rec.preview === "string" ? String(rec.preview) : "";
if (!previewRel.trim()) {
missingNotations.add(`a${n}`);
missingDetails.push(`a${n} (missing preview)`);
continue;
}
try {
await ensurePreviewExists(chatWd, previewRel);
} catch {
missingNotations.add(`a${n}`);
missingDetails.push(`a${n} (preview file missing)`);
}
}
for (const n of parsed.v) {
const rec = (state.variants || []).find((x) => x?.v === n);
if (!rec) {
missingNotations.add(`v${n}`);
missingDetails.push(`v${n}`);
continue;
}
const previewRel = typeof rec.preview === "string" ? String(rec.preview) : "";
if (!previewRel.trim()) {
missingNotations.add(`v${n}`);
missingDetails.push(`v${n} (missing preview)`);
continue;
}
try {
await ensurePreviewExists(chatWd, previewRel);
} catch {
missingNotations.add(`v${n}`);
missingDetails.push(`v${n} (preview file missing)`);
}
}
for (const n of parsed.i) {
const rec = (state.images || []).find((x) => x?.i === n);
if (!rec) {
missingNotations.add(`i${n}`);
missingDetails.push(`i${n}`);
continue;
}
const previewRel = typeof rec.preview === "string" ? String(rec.preview) : "";
if (!previewRel.trim()) {
missingNotations.add(`i${n}`);
missingDetails.push(`i${n} (missing preview)`);
continue;
}
try {
await ensurePreviewExists(chatWd, previewRel);
} catch {
missingNotations.add(`i${n}`);
missingDetails.push(`i${n} (preview file missing)`);
}
}
for (const n of parsed.p) {
const rec = (state.pictures || []).find((x) => x?.p === n);
if (!rec) {
missingNotations.add(`p${n}`);
missingDetails.push(`p${n}`);
continue;
}
const previewRel = typeof rec.preview === "string" ? String(rec.preview) : "";
if (!previewRel.trim()) {
missingNotations.add(`p${n}`);
missingDetails.push(`p${n} (missing preview)`);
continue;
}
try {
await ensurePreviewExists(chatWd, previewRel);
} catch {
missingNotations.add(`p${n}`);
missingDetails.push(`p${n} (preview file missing)`);
}
}
if (missingDetails.length > 0 && strict) {
const hint = `Available: a=[${availableA.map((x) => `a${x}`).join(", ") || "(none)"}] v=[${availableV.map((x) => `v${x}`).join(", ") || "(none)"}] i=[${availableI.map((x) => `i${x}`).join(", ") || "(none)"}] p=[${availableP.map((x) => `p${x}`).join(", ") || "(none)"}]`;
return `review_image failed: unknown/invalid targets: ${missingDetails.join(", ")}. ${hint}`;
}
if (!strict && missingNotations.size > 0) {
parsed.a = parsed.a.filter((n) => !missingNotations.has(`a${n}`));
parsed.v = parsed.v.filter((n) => !missingNotations.has(`v${n}`));
parsed.i = parsed.i.filter((n) => !missingNotations.has(`i${n}`));
parsed.p = parsed.p.filter((n) => !missingNotations.has(`p${n}`));
}
const requestedByToolCallId = (() => {
try {
const anyCtx = ctx;
const v = anyCtx?.toolCallId ?? anyCtx?.tool_call_id ?? anyCtx?.id ?? anyCtx?.callId;
return typeof v === "string" && v.trim() ? v.trim() : void 0;
} catch {
return void 0;
}
})();
state.pendingReviewPromotion = {
requestedAt: localTimestamp(),
requestedByToolCallId,
ttlMs: 5 * 60 * 1e3,
targets: {
a: parsed.a.length ? parsed.a : void 0,
v: parsed.v.length ? parsed.v : void 0,
i: parsed.i.length ? parsed.i : void 0,
p: parsed.p.length ? parsed.p : void 0
}
};
await writeStateAtomic(chatWd, state);
const scheduled = [];
scheduled.push(...parsed.a.map((n) => `a${n}`));
scheduled.push(...parsed.v.map((n) => `v${n}`));
scheduled.push(...parsed.i.map((n) => `i${n}`));
scheduled.push(...parsed.p.map((n) => `p${n}`));
try {
appendReviewToPluginLog(
`VIP review scheduled: chatId=${chatId} targets=[${scheduled.join(",")}]` + (requestedByToolCallId ? ` toolCallId=${requestedByToolCallId}` : "")
);
} catch {
}
try {
ctx.status(`Scheduled re-view for: ${scheduled.join(", ")}`);
} catch {
}
return `Scheduled re-view for: ${scheduled.join(", ")}`;
} catch (e) {
return `review_image failed: ${String(e?.message || e)}`;
}
}
});
}
// src/tools/review_sequence.ts
import { tool as tool2 } from "@lmstudio/sdk";
import { z as z3 } from "zod";
import path33 from "path";
import fs28 from "fs";
var ReviewSequenceParamsShape = {
variant: z3.coerce.string().describe(
"Reference to the video to review. Use standard media notation: vN for variants, iN for images, pN for pictures (e.g. v1, i3). A bare integer N is also accepted and treated as vN. Must correspond to a generated video."
),
fps: z3.coerce.number().min(0.1).max(30).optional().default(2).describe(
"Frame sampling rate in fps. Default: 2. Higher values send more frames to the model."
)
};
function appendReviewSequenceToPluginLog(line) {
try {
const logsDir2 = getLogsDir();
if (!fs28.existsSync(logsDir2)) fs28.mkdirSync(logsDir2, { recursive: true });
fs28.appendFileSync(
path33.join(logsDir2, getPluginLogFilename()),
`${localTimestamp()} - ${line}
`
);
} catch {
}
}
function createReviewSequenceTool(ctl) {
return tool2({
name: "review_sequence",
description: `Send a frame sequence of a generated video to the model for visual review.
Use this when the user asks you to watch, review or analyse the content of a generated video.
LM Studio does not support native video objects; this tool compensates by sampling frames at a configurable fps and transmitting them as a labelled image sequence.
Parameters:
- variant: Media reference for the video \u2014 vN, iN, or pN notation (e.g. v1, i3).
- fps: Frame sampling rate (default: 2). Higher \u2192 more frames \u2192 larger context.
${formatToolMetaBlock()}`,
parameters: ReviewSequenceParamsShape,
implementation: async (args, ctx) => {
try {
try {
const workingDir2 = ctl.getWorkingDirectory();
if (typeof workingDir2 === "string" && workingDir2.trim().length > 0) {
const chatId2 = path33.basename(workingDir2);
if (/^\d+$/.test(chatId2)) {
setActiveChatContext({
chatId: chatId2,
workingDir: workingDir2,
requestId: `tool-${Date.now()}`
});
}
}
} catch {
}
const workingDir = ctl.getWorkingDirectory();
if (typeof workingDir !== "string" || !workingDir.trim()) {
return "review_sequence failed: working directory not available.";
}
const chatWd = workingDir;
const rawRef = typeof args?.variant === "string" ? args.variant.trim() : String(args?.variant ?? "").trim();
let refType = "v";
let refNum = 0;
const refMatch = /^([vip])(\d+)$/i.exec(rawRef);
if (refMatch) {
refType = refMatch[1].toLowerCase();
refNum = parseInt(refMatch[2], 10);
} else if (/^\d+$/.test(rawRef)) {
refType = "v";
refNum = parseInt(rawRef, 10);
}
if (refNum <= 0) {
return "review_sequence failed: variant must be a media reference like 'v1', 'i3', 'p2', or a positive integer.";
}
const displayRef = `${refType}${refNum}`;
const fps = typeof args?.fps === "number" && args.fps > 0 ? args.fps : 2;
const state = await readState(chatWd);
let movAbs;
if (refType === "v") {
const rec = (state.variants || []).find(
(x) => typeof x?.v === "number" && x.v === refNum
);
if (!rec) {
const available = [
...(state.variants || []).map((x) => typeof x?.v === "number" ? `v${x.v}` : null),
...(state.images || []).map((x) => typeof x?.i === "number" ? `i${x.i}` : null)
].filter(Boolean).join(", ");
return `review_sequence failed: ${displayRef} not found in state.` + (available ? ` Available: ${available}.` : " No variants or images recorded yet.");
}
const fn = typeof rec.filename === "string" ? String(rec.filename) : "";
if (!fn) return `review_sequence failed: ${displayRef} has no filename recorded.`;
movAbs = path33.join(chatWd, fn.replace(/\.png$/i, ".mov"));
} else if (refType === "i") {
const rec = (state.images || []).find(
(x) => typeof x?.i === "number" && x.i === refNum
);
if (!rec) {
const available = [
...(state.variants || []).map((x) => typeof x?.v === "number" ? `v${x.v}` : null),
...(state.images || []).map((x) => typeof x?.i === "number" ? `i${x.i}` : null)
].filter(Boolean).join(", ");
return `review_sequence failed: ${displayRef} not found in state.` + (available ? ` Available: ${available}.` : " No variants or images recorded yet.");
}
const fn = typeof rec.filename === "string" ? String(rec.filename) : "";
if (!fn) return `review_sequence failed: ${displayRef} has no filename recorded.`;
movAbs = path33.join(chatWd, fn.replace(/\.png$/i, ".mov"));
} else {
const rec = (state.pictures || []).find(
(x) => typeof x?.p === "number" && x.p === refNum
);
if (!rec) {
const available = (state.pictures || []).map((x) => typeof x?.p === "number" ? `p${x.p}` : null).filter(Boolean).join(", ");
return `review_sequence failed: ${displayRef} not found in state.` + (available ? ` Available: ${available}.` : " No pictures recorded yet.");
}
const src = typeof rec.sourceUrl === "string" ? String(rec.sourceUrl) : "";
if (!src) return `review_sequence failed: ${displayRef} has no sourceUrl recorded.`;
movAbs = src;
}
let movExists = false;
try {
await fs28.promises.access(movAbs, fs28.constants.F_OK);
movExists = true;
} catch {
movExists = false;
}
if (!movExists) {
return `review_sequence failed: no video file found for ${displayRef}. Expected: ${movAbs}. ${displayRef} may be a still image, not a video.`;
}
state.pendingSequenceReview = {
requestedAt: localTimestamp(),
movAbs,
variant: refNum,
variantLabel: displayRef,
fps,
ttlMs: 5 * 60 * 1e3
};
await writeStateAtomic(chatWd, state);
const chatId = (() => {
try {
return path33.basename(chatWd);
} catch {
return "(unknown)";
}
})();
try {
appendReviewSequenceToPluginLog(
`Sequence review scheduled: chatId=${chatId} ref=${displayRef} fps=${fps}`
);
} catch {
}
try {
ctx.status(`Extracting frames for ${displayRef} at ${fps} fps\u2026`);
} catch {
}
return `Scheduled sequence review for ${displayRef} at ${fps} fps.`;
} catch (e) {
return `review_sequence failed: ${String(e?.message || e)}`;
}
}
});
}
export {
AGENT_MODE_ORDER,
AGENT_NAMES,
ALLOWED_GEN_INPUT_KEYS,
ATTACHMENT_CONFIG,
ATTACHMENT_FULL_CONFIG,
BOX_MATCH_IOU,
ColorCalibration,
CompressionMethod,
Control,
ControlInputType,
ControlMode,
CropToolParamsShape,
CropToolSchemaStrict,
DEFAULT_MAX_REFERENCE_IMAGES,
DEFAULT_RECONCILE_OPTIONS,
DrawThingsGrpcService,
DrawThingsService,
FASTVLM_DEFAULT_ENDPOINT,
GenerateToolParamsSchema,
GenerateToolParamsSchemaBase,
GenerateToolParamsSchemaMinimalStrict,
GenerateToolParamsShapeMinimal,
GenerationConfiguration,
IMAGE_CONFIG,
IMAGE_FULL_CONFIG,
IMAGE_MODEL_CAPABILITY_MAP,
INJECTION_END,
INJECTION_START,
InpaintToolParamsShape,
InpaintToolSchemaStrict,
LoRA,
LoRAMode,
MEDIA_HARVESTING_CONFIG,
MEDIA_SOURCE_REGISTRY,
MLX_VISION_ANALYZE_IMAGE_PROMPT,
MLX_VISION_INDEX_IMAGE_PROMPT,
MODEL_FAMILIES,
MODEL_IDS,
MODEL_PRESET_TO_CAPABILITY_KEY,
OVERLAY_REGISTRY,
OutpaintToolParamsShape,
OutpaintToolSchemaStrict,
PICTURE_CONFIG,
PICTURE_FULL_CONFIG,
PROMPT_UPSAMPLER_APIS,
PROMPT_UPSAMPLER_FAMILY_SPECS,
PROMPT_UPSAMPLING_MODEL_FAMILIES,
Reason,
SamplerType,
SeedMode,
TensorHistoryNode,
TextHistoryNode,
TextModification,
TextRange,
TextType,
ThumbnailHistoryNode,
UpscaleToolParamsShape,
UpscaleToolSchemaStrict,
VARIANT_CONFIG,
VARIANT_FULL_CONFIG,
VISION_WINDOW_SIZES,
ZoomInToolParamsShape,
ZoomInToolSchemaStrict,
agentNameOfFamily,
agentNameOfModel,
appendErrorRaw,
appendImages,
appendMediaItems,
appendModelHint,
appendPictures,
appendPluginLog,
appendVariants,
appendVisionPromotionJsonl,
applyPromptUpsampling,
autoFallbackFor,
bitmapToLab,
boxesFromMask,
buildAuditLogger,
buildDtGenerationConfiguration,
buildDtcModelMappingSnapshot,
buildInventory,
buildLockedInstruction,
buildModelListText,
buildPlainRows,
buildPromotionItems,
buildPromptUpsamplingAudit,
cancelBackgroundRequest,
catalogModeFor,
catalogModelById,
catalogModelOfFile,
catalogOverlayFor,
checkCustomConfigs,
checkDrawThingsGrpcAssets,
checkDrawThingsGrpcFilesExist,
checkFreshness,
checkModeSupport,
checkModeSupportWithCustom,
checkProfileModels,
checkVisionPrimerStatus,
chooseAlignedCanvas,
clampNumber,
clearCustomConfigsCache,
clearInjections,
compareInventoryWithRegistry,
configSchematics,
correctMaskColorDrift,
correctMaskColorDriftPng,
createBackgroundRequestId,
createInventoryProvider,
createMcpProgressSender,
createProgressReporter,
createReviewImageTool,
createReviewSequenceTool,
createSaveOriginalPng,
createStatusProgressCallback,
cropToPng,
currentInventory,
currentRequestLogId,
currentToolName,
decodeToRgba,
deepParseMaybeJson,
defaultParams,
defaultParamsImg2Img2 as defaultParamsEdit,
defaultParamsImage2Video,
defaultParamsImg2Img,
defaultParamsImg2Img3 as defaultParamsRestore,
defaultParamsText2Video,
defaultParamsZoom,
derivativeSourceRef,
describeMissingProfileModel,
detectCapabilities,
detectImageMimeType,
detectImageModelCapabilities,
detectProjectImageType,
diffProjectGenerationSnapshots,
drawthingsLimits as drawthingsEditLimits,
drawthingsLimits,
drawthingsLimits as drawthingsRestoreLimits,
drawthingsLimits as drawthingsZoomLimits,
echoFetcherForClient,
encodeFileUrl,
encodeJpegPreview,
encodeJpegPreviewFromBuffer,
encodeRgbaToPng,
engineConnectionDefaults,
ensureAgentModelLoaded,
ensureLlamaServerRouterRunning,
ensureLogsDir,
explainFile,
explainRequiredFile,
extractPendingAttachments,
extractSequenceFrames,
extractToolCalls,
extractToolResultImageCandidates,
extractUserAttachments,
fileInWd,
findAllAttachmentsLegacy,
findAllImages,
findAllMedia,
findAllMediaAllTypes,
findAllPictures,
findAllVariantsLegacy,
findConversationPath,
findCustomPresetsByModelFile,
findImageModelCapabilitiesByFilename,
findLMStudioHome,
findLastAttachmentLegacy,
findLastImages,
findLastMedia,
findLastPictures,
findLmsCli,
findMessagesArray,
findStateRecord,
formatEta,
formatImageModelForToolDisplay,
formatModelHint,
formatToolMetaBlock,
formatZodError,
generatePreview,
generatePreviewFromBuffer,
generateRuntimeDefaults,
generationConfigBytesToV2,
getActiveChatContext,
getAllMediaTypeConfigs,
getAllMediaTypeFullConfigs,
getAllowlistedPictureTools,
getAttachmentWindowSize,
getAudioSampleRateForModel,
getAvailableCustomCombinations,
getBackgroundRequest,
getCancelSignal,
getCapabilityKeyForPreset,
getConfiguredCustomConfigsPath,
getCurrentConnectionSettings,
getCustomPreset,
getCustomPresetLabelsUsingModelFilename,
getDefaultFpsForModel,
getDefaultPreviewOptions,
getDrawThingsGenerationMetadata,
getEffectiveOverlay,
getEngineConnectionDefaults,
getEverythingElseWindowSize,
getHealthyServerBaseUrl,
getInjectionCount,
getLMConversationFilePath,
getLMStudioFileMetadata,
getLMStudioUserFilePath,
getLMStudioWorkingDir,
getLogsDir,
getMaxReferenceImages,
getMediaTypeConfig,
getMediaTypeForTool,
getMediaTypeForToolCall,
getMediaTypeFullConfig,
getMessageRole,
getModelFilename,
getModelListText,
getModelOverlay,
getModelRequiredFiles,
getOriginalFileName,
getPluginLogFilename,
getPluginMeta,
getProjectRoot,
getPromotableAttachmentNs,
getPromotableEverythingElse,
getPromotableImageIs,
getPromotableVariantVs,
getSelfPluginIdentifier,
getSize,
getStateArrayKey,
getThumbnailFromProject,
getThumbnailsFromProject,
getToolExtractor,
getUndeliveredCompletedBackgroundRequests,
getWindowSizeForKind,
globalConfigSchematics,
gridBoxIoU,
guessExtForOriginal,
harvestToolResultImages,
hasInjections,
hasInventoryFetcher,
hasTrackedInjections,
image2imageAlternatives,
image2imagePresetOf,
image2imageUnavailable,
importAttachmentBatch,
injectLastUsedModelIntoNewestChat,
injectXmpIntoBuffer,
installedAgentNames,
installedFileOf,
isAllowedOriginalExt,
isAllowlistedSsotToolCall,
isBackgroundCall,
isDerivativeToolRecord,
isHttpServerHealthy,
isImage2ImageMode,
isKnownModel,
isLegacyPresetName,
isLocalLmApiBaseUrl,
isModelInstalled,
isModelLoaded,
isPictureToolAllowlisted,
isPng,
isPresetName,
isProjectUri,
isSupportedImageBuffer,
isToolAllowlistedForMediaType,
isValidModelId,
isoStamp,
legacyNamesOf,
listAvailable,
listBackgroundRequests,
listImage2ImageModels,
listUsablePresets,
loadCustomConfigs,
loadVisionPrimerModel,
localTimestamp,
log,
logError,
logShadowReport,
logTimestamp,
loraFallbackOverlay,
markBackgroundRequestDelivered,
markBackgroundRequestFailed,
markBackgroundRequestQueued,
materializeToolResultImageToFiles,
modelLine,
modelOverlays,
normalizeInputBuffer,
normalizeModelId,
normalizeModelName,
normalizeQualityToInt,
normalizeSourceNotation,
normalizeToolPluginId,
officialNameFor,
parseDigitOnlyNotation,
parseEchoResponse,
parseMessages,
parsePrefixedNotation,
parseProjectUri,
parseThinkingToolCalls,
parseToolResultPayload,
parseVisionPromotionJsonlText,
peekInventory,
pickFallbackModel,
prepareInventoryFetcher,
preprocess,
presetAvailability,
previewDefaults,
previewFilenameFrom,
primeInventoryFromEcho,
primeVisionCapability,
projectGenerationFingerprint,
projectGenerationIdentity,
proxyMarks,
pyJson,
readBackgroundRequests,
readCameraImageMetadata,
readConversation,
readLastAttachmentRef,
readPromptUpsamplerConfigFromEnv,
readState,
readVisionPromotionJsonlEntries,
recommendedParamsFor,
reconcileMedia,
recordGeneratedVariants,
rectMask,
referencedFiles,
registerInventoryFetcher,
rehydrateLastAttachment,
reimposeBoxes,
renderPictureMarkdown,
requestBelongsToScope,
requestLogPrefix,
requiredFileForProfile,
resizeAndEncode,
resizeAndEncodeByHeight,
resizeAndEncodeBySum,
resizeCanvasAndMask,
resizeCoverToPng,
resizeFillToPng,
resizeInsideToPng,
resolveActions,
resolveActiveLMStudioChatId,
resolveAutoFallback,
resolveEffectiveSourceToken,
resolveImageModelInfoFromModelUsed,
resolveImg2ImgSourceLMStudio,
resolveInjection,
resolveLatestLmStudioLlamaServer,
resolveMessageVersion,
resolveModelArgument,
resolveOriginalReference,
resolveProjectGenerationMetadata,
resolveProjectUri,
resolveRequestedModel,
resolveRequestedOutputDims,
resolveTensorDecoderProfile,
runAsBackgroundCall,
runBackgroundJobAwaited,
runInBackgroundJob,
runInventoryShadow,
runWithCancelSignal,
runWithRequestLogId,
runWithToolName,
runWithToolPass,
runtimeCatalog,
scanMedia,
selectAutoModel,
setActiveChatContext,
setDrawThingsServiceRootStart,
shouldPromoteAttachments,
shouldPromoteEverythingElseIdempotent,
shouldPromoteVariantsIdempotent,
shouldUseFilesApiForModel,
splitCaptionAndRows,
stateOfFile,
stopLlamaServerRouter,
stripInjections,
stripInternalToolKeys,
substituteInstalledPrecision,
substitutionNote,
supportsMode,
syncAttachmentsToState,
toHttpOriginalUrl,
toHttpPreviewUrl,
toOpenAIPromptParts,
toOverlayMode,
toPng,
trackInjection,
tsForFilename,
tunedPresetFor,
unloadAgentModel,
unloadVisionPrimer,
updateLastUsedModelForAgentModel,
upsertAttachment,
validateImageGenerationParams,
withInstalledPrecision,
withProxyMarks,
wrapInjection,
writeBackgroundRequestsAtomic,
writeStateAtomic
};