bleam 0.0.11 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/ai.cjs +2314 -2173
  2. package/dist/ai.d.cts +227 -322
  3. package/dist/ai.d.ts +227 -322
  4. package/dist/ai.js +2309 -2159
  5. package/dist/cli.d.cts +1 -1
  6. package/dist/cli.d.ts +1 -1
  7. package/dist/config.d.cts +1 -1
  8. package/dist/config.d.ts +1 -1
  9. package/dist/{files-Ds1wT8C2.js → files-BXVkPrPN.js} +6 -1
  10. package/dist/{files-Bo7h9fik.cjs → files-DxaQ-Nv0.cjs} +11 -0
  11. package/dist/files.cjs +1 -1
  12. package/dist/files.d.cts +1 -1
  13. package/dist/files.d.ts +1 -1
  14. package/dist/files.js +1 -1
  15. package/dist/index.d.cts +1 -1
  16. package/dist/index.d.ts +1 -1
  17. package/dist/schema-B5BfdswF.js +226 -0
  18. package/dist/schema-BnVZOXfu.cjs +286 -0
  19. package/dist/schema-D5eImHxu.d.cts +125 -0
  20. package/dist/schema-SSjokbtw.d.ts +125 -0
  21. package/dist/schema.cjs +10 -2
  22. package/dist/schema.d.cts +2 -2
  23. package/dist/schema.d.ts +2 -2
  24. package/dist/schema.js +2 -2
  25. package/dist/state-Dh3HLixb.js +874 -0
  26. package/dist/state-LssDgpff.cjs +973 -0
  27. package/dist/state.cjs +16 -12
  28. package/dist/state.d.cts +144 -140
  29. package/dist/state.d.ts +145 -140
  30. package/dist/state.js +3 -3
  31. package/dist/{ui-CHc4xEs_.d.ts → ui-D7bRLYee.d.ts} +7 -7
  32. package/dist/ui.d.ts +1 -1
  33. package/dist/window.d.ts +1 -1
  34. package/package.json +3 -1
  35. package/templates/foundation-models/app/index.tsx +77 -15
  36. package/templates/image-generation/app/index.tsx +2 -2
  37. package/templates/native/ios/Bleam.xcodeproj/project.pbxproj +46 -46
  38. package/templates/native/ios/Podfile.lock +173 -173
  39. package/templates/native/modules/bleam-runtime/ios/AIModule.swift +35 -357
  40. package/templates/text-generation/app/index.tsx +81 -50
  41. package/templates/updates/README.md +1 -1
  42. package/dist/schema-Bo5Jvqus.js +0 -90
  43. package/dist/schema-CYh6n8GS.d.ts +0 -58
  44. package/dist/schema-oeOrd3i1.d.cts +0 -58
  45. package/dist/schema-rQ13mrpD.cjs +0 -102
  46. package/dist/state-Bx0VlTlO.cjs +0 -852
  47. package/dist/state-CAwe-Vw1.js +0 -767
  48. /package/dist/{config-Cms0rvqg.d.ts → config-COcRnn5a.d.cts} +0 -0
  49. /package/dist/{config-CufOVJV3.d.cts → config-Chi-flpJ.d.ts} +0 -0
  50. /package/dist/{files-4ZEoAWiv.d.ts → files-DwA7pzr3.d.cts} +0 -0
  51. /package/dist/{files-Dt5mbzLq.d.cts → files-VrkQlKIT.d.ts} +0 -0
package/dist/ai.js CHANGED
@@ -1,11 +1,10 @@
1
1
  import "./native-runtime-C85Nuc4F.js";
2
2
  import "./crypto-BB92-Upx.js";
3
- import { i as files } from "./files-Ds1wT8C2.js";
4
- import { f as atom, p as useAtom } from "./state-CAwe-Vw1.js";
5
- import "./schema-Bo5Jvqus.js";
3
+ import { a as nativeCopy, i as files } from "./files-BXVkPrPN.js";
4
+ import { c as object, s as number, u as string } from "./schema-B5BfdswF.js";
5
+ import { a as transactionAtom, d as internalJotaiWritableAtom, f as internalStore, g as currentAppStorageKey, i as queryAtom, n as atomCollection, r as mutateAtom, u as internalJotaiAtom } from "./state-Dh3HLixb.js";
6
6
  import { requireNativeModule } from "expo";
7
- import { useRef, useState } from "react";
8
- import { Image } from "react-native";
7
+ import { use, useSyncExternalStore } from "react";
9
8
 
10
9
  //#region src/ai/bonsai.ts
11
10
  const internalTextModelCatalog = [
@@ -305,486 +304,344 @@ async function deleteBonsaiTextModel(model, options = {}) {
305
304
  }
306
305
 
307
306
  //#endregion
308
- //#region src/ai/image-batch.ts
309
- function batchImageSeeds(count, seed) {
310
- if (!Number.isInteger(count) || count < 1 || count > 64) throw new AIError("invalid_message", "Batch count must be an integer from 1 to 64");
311
- const first = seed ?? Math.floor(Math.random() * 4294967296);
312
- return Array.from({ length: count }, (_, index) => first + index >>> 0);
313
- }
314
-
315
- //#endregion
316
- //#region src/ai/image-jobs.ts
317
- var ImageGenerationQueue = class {
318
- jobs = /* @__PURE__ */ new Map();
319
- pending = [];
320
- running;
321
- constructor(executor) {
307
+ //#region src/ai/chat-manager.ts
308
+ const missingSnapshot = {
309
+ chat: null,
310
+ messages: []
311
+ };
312
+ var ChatManager = class {
313
+ snapshots = /* @__PURE__ */ new Map();
314
+ chatListeners = /* @__PURE__ */ new Map();
315
+ listListeners = /* @__PURE__ */ new Set();
316
+ controllers = /* @__PURE__ */ new Map();
317
+ listSnapshot = [];
318
+ operation = Promise.resolve();
319
+ ready;
320
+ constructor(repository, executor) {
321
+ this.repository = repository;
322
322
  this.executor = executor;
323
+ this.ready = this.initialize();
323
324
  }
324
325
  setExecutor(executor) {
325
326
  this.executor = executor;
326
327
  }
327
- schedule(options) {
328
- const id = crypto.randomUUID();
329
- let resolve;
330
- let reject;
331
- const promise = new Promise((onResolve, onReject) => {
332
- resolve = onResolve;
333
- reject = onReject;
328
+ async create(input = {}) {
329
+ await this.ready;
330
+ return this.mutate(async () => {
331
+ const chat$1 = await this.repository.create({ title: validTitle(input.title ?? "New Chat") });
332
+ this.set({
333
+ chat: chat$1,
334
+ messages: []
335
+ });
336
+ return chat$1;
334
337
  });
335
- const record = {
336
- snapshot: {
337
- id,
338
- status: "queued",
339
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
340
- },
341
- options,
342
- controller: new AbortController(),
343
- listeners: /* @__PURE__ */ new Set(),
344
- promise,
345
- resolve,
346
- reject
347
- };
348
- this.jobs.set(id, record);
349
- this.pending.push(record);
350
- if (options.signal) {
351
- const cancel = () => this.cancel(id);
352
- options.signal.addEventListener("abort", cancel, { once: true });
353
- record.removeSignalListener = () => options.signal?.removeEventListener("abort", cancel);
354
- if (options.signal.aborted) cancel();
355
- }
356
- this.runNext();
357
- return this.handle(record);
358
- }
359
- get(id) {
360
- const record = this.jobs.get(id);
361
- return record ? this.handle(record) : void 0;
362
338
  }
363
- list() {
364
- return [...this.jobs.values()].map(({ snapshot }) => ({ ...snapshot }));
339
+ async get(id) {
340
+ await this.ready;
341
+ return this.snapshots.get(id)?.chat ?? null;
342
+ }
343
+ async list() {
344
+ await this.ready;
345
+ return this.listSnapshot;
346
+ }
347
+ async send(id, content, options = {}, callbacks = {}) {
348
+ await this.ready;
349
+ if (options.signal?.aborted) throw canceledException();
350
+ const value = content.trim();
351
+ if (!value) throw new AIError("invalid_message", "Message must not be empty");
352
+ const controller = new AbortController();
353
+ const accepted = await this.mutate(async () => {
354
+ if (this.controllers.has(id)) throw new AIError("concurrent_request", "This chat already has an active generation");
355
+ const next = await this.repository.acceptSend(id, value);
356
+ this.controllers.set(id, controller);
357
+ this.setAccepted(next);
358
+ return next;
359
+ });
360
+ this.run(accepted, options, callbacks, controller);
361
+ return resultFromAccepted(accepted);
362
+ }
363
+ async cancel(id) {
364
+ await this.ready;
365
+ return this.mutate(async () => {
366
+ const controller = this.controllers.get(id);
367
+ const assistant = this.snapshots.get(id)?.messages.findLast((message) => message.role === "assistant");
368
+ if (!controller || !assistant || !isActiveMessage(assistant)) return false;
369
+ const next = await this.repository.markCanceling(id, assistant.id);
370
+ this.setAccepted(next);
371
+ controller.abort();
372
+ return true;
373
+ });
365
374
  }
366
- cancel(id) {
367
- const record = this.jobs.get(id);
368
- if (!record || !["queued", "running"].includes(record.snapshot.status)) return false;
369
- record.controller.abort();
370
- if (record.snapshot.status === "queued") {
371
- const index = this.pending.indexOf(record);
372
- if (index >= 0) this.pending.splice(index, 1);
373
- const error = canceledError();
374
- this.update(record, {
375
- status: "canceled",
376
- error
375
+ async retry(id, messageId, options = {}, callbacks = {}) {
376
+ await this.ready;
377
+ if (options.signal?.aborted) throw canceledException();
378
+ const controller = new AbortController();
379
+ const accepted = await this.mutate(async () => {
380
+ if (this.controllers.has(id)) throw new AIError("concurrent_request", "This chat already has an active generation");
381
+ const next = await this.repository.retry(id, messageId);
382
+ this.controllers.set(id, controller);
383
+ this.setAccepted(next);
384
+ return next;
385
+ });
386
+ this.run(accepted, options, callbacks, controller);
387
+ return resultFromAccepted(accepted);
388
+ }
389
+ async setTitle(id, title) {
390
+ await this.ready;
391
+ return this.mutate(async () => {
392
+ const chat$1 = await this.repository.setTitle(id, validTitle(title));
393
+ this.set({
394
+ chat: chat$1,
395
+ messages: this.snapshots.get(id)?.messages ?? []
377
396
  });
378
- record.removeSignalListener?.();
379
- record.reject(error);
380
- }
381
- return true;
397
+ return chat$1;
398
+ });
382
399
  }
383
- handle(record) {
384
- return {
385
- id: record.snapshot.id,
386
- promise: record.promise,
387
- cancel: () => this.cancel(record.snapshot.id),
388
- getSnapshot: () => ({ ...record.snapshot }),
389
- subscribe: (listener) => {
390
- record.listeners.add(listener);
391
- listener({ ...record.snapshot });
392
- return () => record.listeners.delete(listener);
400
+ async remove(id) {
401
+ await this.ready;
402
+ return this.mutate(async () => {
403
+ if (this.controllers.has(id)) throw new AIError("concurrent_request", "Cancel the generation before removing this chat");
404
+ const removed = await this.repository.remove(id);
405
+ if (removed) {
406
+ this.snapshots.delete(id);
407
+ this.refreshList();
408
+ this.emit(id);
393
409
  }
410
+ return removed;
411
+ });
412
+ }
413
+ getChatSnapshot(id) {
414
+ return this.snapshots.get(id) ?? missingSnapshot;
415
+ }
416
+ getListSnapshot() {
417
+ return this.listSnapshot;
418
+ }
419
+ subscribeChat(id, listener) {
420
+ const listeners = this.chatListeners.get(id) ?? /* @__PURE__ */ new Set();
421
+ listeners.add(listener);
422
+ this.chatListeners.set(id, listeners);
423
+ return () => {
424
+ listeners.delete(listener);
425
+ if (listeners.size === 0) this.chatListeners.delete(id);
394
426
  };
395
427
  }
396
- async runNext() {
397
- if (this.running) return;
398
- const record = this.pending.shift();
399
- if (!record) return;
400
- this.running = record;
401
- this.update(record, {
402
- status: "running",
403
- startedAt: (/* @__PURE__ */ new Date()).toISOString()
428
+ subscribeList(listener) {
429
+ this.listListeners.add(listener);
430
+ return () => this.listListeners.delete(listener);
431
+ }
432
+ async initialize() {
433
+ await this.repository.recoverActive();
434
+ const chats$1 = await this.repository.list();
435
+ const transcripts = await Promise.all(chats$1.map((chat$1) => this.repository.messages(chat$1.id)));
436
+ chats$1.forEach((chat$1, index) => {
437
+ this.snapshots.set(chat$1.id, {
438
+ chat: chat$1,
439
+ messages: transcripts[index] ?? []
440
+ });
404
441
  });
442
+ this.refreshList();
443
+ }
444
+ run(accepted, options, callbacks, controller) {
445
+ const externalAbort = () => void this.cancel(accepted.chatId);
446
+ options.signal?.addEventListener("abort", externalAbort, { once: true });
447
+ if (options.signal?.aborted) externalAbort();
448
+ this.generate(accepted, options, callbacks, controller).finally(() => {
449
+ options.signal?.removeEventListener("abort", externalAbort);
450
+ }).catch(() => void 0);
451
+ }
452
+ async generate(accepted, options, callbacks, controller) {
453
+ let current = accepted.assistantMessage;
454
+ let content = "";
455
+ let lastPersistedAt = 0;
405
456
  try {
406
- const result = await this.executor({
407
- ...record.options,
408
- signal: record.controller.signal,
409
- onProgress: (progress) => {
410
- record.options.onProgress?.(progress);
411
- this.progress(record, progress);
412
- }
457
+ const started = await this.mutate(async () => {
458
+ const next = await this.repository.start(accepted.chatId, accepted.assistantMessageId);
459
+ this.setAccepted(next);
460
+ return next;
413
461
  });
414
- this.update(record, {
415
- status: "completed",
416
- result,
417
- completedAt: (/* @__PURE__ */ new Date()).toISOString()
462
+ current = started.assistantMessage;
463
+ const messages = historyBefore(started.messages, current, options.system);
464
+ const executorOptions = {
465
+ ...options,
466
+ messages,
467
+ signal: controller.signal
468
+ };
469
+ delete executorOptions.system;
470
+ for await (const snapshot of this.executor.stream(executorOptions)) {
471
+ content = snapshot;
472
+ await this.mutate(async () => {
473
+ current = {
474
+ ...current,
475
+ content,
476
+ updatedAt: now$1()
477
+ };
478
+ this.replaceMessage(started.chatId, current);
479
+ const timestamp$1 = Date.now();
480
+ if (timestamp$1 - lastPersistedAt >= 100) {
481
+ current = await this.repository.updateContent(current);
482
+ lastPersistedAt = timestamp$1;
483
+ }
484
+ });
485
+ }
486
+ await this.mutate(async () => {
487
+ const next = await this.repository.finish(started.chatId, current.id, controller.signal.aborted ? "canceled" : "completed", content, controller.signal.aborted ? canceledError$1() : void 0);
488
+ this.controllers.delete(started.chatId);
489
+ this.setAccepted(next);
490
+ if (next.assistantMessage.status === "completed") notify(callbacks.onFinish, next.assistantMessage);
491
+ else notify(callbacks.onError, next.assistantMessage.error);
418
492
  });
419
- record.resolve(result);
420
493
  } catch (error) {
421
- const canceled = record.controller.signal.aborted;
422
- const failure = canceled ? canceledError(error) : error;
423
- this.update(record, {
424
- status: canceled ? "canceled" : "failed",
425
- error: failure,
426
- completedAt: (/* @__PURE__ */ new Date()).toISOString()
494
+ const serialized = controller.signal.aborted ? canceledError$1() : serializeError(error);
495
+ await this.mutate(async () => {
496
+ const next = await this.repository.finish(accepted.chatId, accepted.assistantMessageId, controller.signal.aborted ? "canceled" : "failed", content, serialized);
497
+ this.controllers.delete(accepted.chatId);
498
+ this.setAccepted(next);
499
+ notify(callbacks.onError, serialized);
427
500
  });
428
- record.reject(failure);
429
501
  } finally {
430
- record.removeSignalListener?.();
431
- this.running = void 0;
432
- this.runNext();
502
+ if (this.controllers.get(accepted.chatId) === controller) this.controllers.delete(accepted.chatId);
433
503
  }
434
504
  }
435
- progress(record, progress) {
436
- this.update(record, { progress });
505
+ mutate(action) {
506
+ const result = this.operation.then(action, action);
507
+ this.operation = result.then(() => void 0, () => void 0);
508
+ return result;
437
509
  }
438
- update(record, update) {
439
- record.snapshot = {
440
- ...record.snapshot,
441
- ...update
442
- };
443
- for (const listener of record.listeners) listener({ ...record.snapshot });
510
+ setAccepted(value) {
511
+ this.set({
512
+ chat: value.chat,
513
+ messages: value.messages
514
+ });
515
+ }
516
+ replaceMessage(chatId, message) {
517
+ const snapshot = this.snapshots.get(chatId);
518
+ if (!snapshot) return;
519
+ this.set({
520
+ chat: snapshot.chat,
521
+ messages: snapshot.messages.map((item) => item.id === message.id ? message : item)
522
+ });
523
+ }
524
+ set(snapshot) {
525
+ if (!snapshot.chat) return;
526
+ const previous = this.snapshots.get(snapshot.chat.id);
527
+ this.snapshots.set(snapshot.chat.id, snapshot);
528
+ if (previous?.chat !== snapshot.chat) this.refreshList();
529
+ this.emit(snapshot.chat.id);
530
+ }
531
+ refreshList() {
532
+ this.listSnapshot = [...this.snapshots.values()].flatMap((snapshot) => snapshot.chat ? [snapshot.chat] : []).sort((left, right) => left.updatedAt === right.updatedAt ? right.id.localeCompare(left.id) : right.updatedAt.localeCompare(left.updatedAt));
533
+ for (const listener of this.listListeners) listener();
534
+ }
535
+ emit(id) {
536
+ for (const listener of this.chatListeners.get(id) ?? []) listener();
444
537
  }
445
538
  };
446
- function canceledError(cause) {
447
- return new AIError("generation_canceled", "Image generation canceled", cause);
539
+ function historyBefore(messages, target, system) {
540
+ return [...system?.trim() ? [{
541
+ role: "system",
542
+ content: system
543
+ }] : [], ...messages.filter((message) => message.sequence < target.sequence && (message.role === "user" || message.status === "completed")).map((message) => ({
544
+ role: message.role,
545
+ content: message.content
546
+ }))];
547
+ }
548
+ function isActiveMessage(message) {
549
+ return message.role === "assistant" && (message.status === "queued" || message.status === "generating" || message.status === "canceling");
550
+ }
551
+ function resultFromAccepted(value) {
552
+ return {
553
+ chatId: value.chatId,
554
+ userMessageId: value.userMessageId,
555
+ assistantMessageId: value.assistantMessageId
556
+ };
557
+ }
558
+ function validTitle(title) {
559
+ const value = title.trim();
560
+ if (!value) throw new AIError("invalid_message", "Title must not be empty");
561
+ return value;
562
+ }
563
+ function serializeError(error) {
564
+ const value = error instanceof Error ? error : new Error(String(error));
565
+ const details = value;
566
+ return {
567
+ name: value.name,
568
+ message: value.message,
569
+ code: typeof details.code === "string" ? details.code : void 0,
570
+ stage: typeof details.stage === "string" ? details.stage : void 0
571
+ };
572
+ }
573
+ function canceledError$1() {
574
+ return {
575
+ name: "AIError",
576
+ code: "generation_canceled",
577
+ message: "Generation canceled"
578
+ };
579
+ }
580
+ function canceledException() {
581
+ return new AIError("generation_canceled", "Generation canceled");
582
+ }
583
+ function notify(callback, value) {
584
+ if (!callback) return;
585
+ Promise.resolve().then(() => callback(value)).catch(() => void 0);
586
+ }
587
+ function now$1() {
588
+ return (/* @__PURE__ */ new Date()).toISOString();
448
589
  }
449
590
 
450
591
  //#endregion
451
- //#region src/ai/image-models.ts
452
- const flux2Klein4B8BitAbliterated = {
453
- formatVersion: 1,
454
- model: "flux2-klein-4b-8bit-abliterated",
455
- directory: "flux2-klein-4b-8bit-abliterated",
456
- metadata: {
457
- displayName: "Flux.2 Klein 4B Abliterated",
458
- family: "flux2-klein",
459
- precision: "8-bit",
460
- estimatedMemoryGB: 12,
461
- quality: "high",
462
- speed: "fast",
463
- capabilities: [
464
- "text-to-image",
465
- "image-to-image",
466
- "inpainting",
467
- "outpainting",
468
- "references",
469
- "lora"
470
- ]
471
- },
472
- components: {
473
- textEncoder: {
474
- repo: "mlx-community/Josiefied-Qwen3-4B-abliterated-v1-8bit",
475
- revision: "main",
476
- path: "text-encoder",
477
- files: [
478
- "config.json",
479
- "tokenizer.json",
480
- "tokenizer_config.json",
481
- "*.safetensors",
482
- "*.safetensors.index.json"
483
- ]
484
- },
485
- transformer: {
486
- repo: "moxin-org/FLUX.2-klein-4B-8bit-mlx",
487
- revision: "main",
488
- path: "transformer",
489
- files: ["config.json", "quantized_8bit.safetensors"]
490
- },
491
- vae: {
492
- repo: "black-forest-labs/FLUX.2-klein-4B",
493
- revision: "main",
494
- path: "vae",
495
- files: [
496
- "config.json",
497
- "diffusion_pytorch_model.safetensors",
498
- "diffusion_pytorch_model.safetensors.index.json",
499
- "diffusion_pytorch_model-*.safetensors"
500
- ]
592
+ //#region src/ai/tokenizers.mjs
593
+ var DictionarySplitter = class {
594
+ /**
595
+ * @param dictionary The dictionary of words to use for splitting.
596
+ */
597
+ constructor(dictionary) {
598
+ this.trie = this._build_trie(dictionary);
599
+ }
600
+ /**
601
+ * Builds a trie from the given dictionary.
602
+ * @param dictionary The dictionary of words to build the trie from.
603
+ * @returns The root node of the trie.
604
+ * @private
605
+ */
606
+ _build_trie(dictionary) {
607
+ const trie = /* @__PURE__ */ Object.create(null);
608
+ for (const word of dictionary) {
609
+ let node = trie;
610
+ for (let i = 0; i < word.length; ++i) {
611
+ const char = word[i];
612
+ node = node[char] ??= /* @__PURE__ */ Object.create(null);
613
+ }
614
+ node.end = word;
501
615
  }
616
+ return trie;
502
617
  }
503
- };
504
- const ternaryBonsaiImage4B = {
505
- formatVersion: 1,
506
- model: "ternary-bonsai-image-4b",
507
- directory: "ternary-bonsai-image-4b",
508
- metadata: {
509
- displayName: "Ternary Bonsai Image 4B",
510
- family: "bonsai-image",
511
- precision: "2-bit",
512
- estimatedMemoryGB: 8,
513
- quality: "high",
514
- speed: "fast",
515
- capabilities: ["text-to-image"]
516
- },
517
- components: {
518
- textEncoder: {
519
- repo: "prism-ml/bonsai-image-ternary-4B-mlx-2bit",
520
- revision: "2c24c81b934a658ba5590cf39088ba929985b4a8",
521
- path: "text-encoder",
522
- files: [
523
- "text_encoder-mlx-4bit/config.json",
524
- "text_encoder-mlx-4bit/tokenizer.json",
525
- "text_encoder-mlx-4bit/tokenizer_config.json",
526
- "text_encoder-mlx-4bit/model.safetensors",
527
- "text_encoder-mlx-4bit/model.safetensors.index.json"
528
- ]
529
- },
530
- transformer: {
531
- repo: "prism-ml/bonsai-image-ternary-4B-mlx-2bit",
532
- revision: "2c24c81b934a658ba5590cf39088ba929985b4a8",
533
- path: "transformer",
534
- files: [
535
- "transformer-packed-mflux/config.json",
536
- "transformer-packed-mflux/diffusion_pytorch_model.safetensors",
537
- "transformer-packed-mflux/quantization_config.json"
538
- ]
539
- },
540
- vae: {
541
- repo: "prism-ml/bonsai-image-ternary-4B-mlx-2bit",
542
- revision: "2c24c81b934a658ba5590cf39088ba929985b4a8",
543
- path: "vae",
544
- files: ["vae/config.json", "vae/diffusion_pytorch_model.safetensors"]
618
+ /**
619
+ * Splits the input text into tokens based on the dictionary.
620
+ * @param text The input text to split.
621
+ * @returns An array of tokens.
622
+ */
623
+ split(text) {
624
+ const result = [];
625
+ const n = text.length;
626
+ let start = 0;
627
+ let i = 0;
628
+ while (i < n) {
629
+ let node = this.trie;
630
+ let match = null;
631
+ let j = i;
632
+ while (j < n && (node = node[text[j]])) {
633
+ if (node.end) match = node.end;
634
+ ++j;
635
+ }
636
+ if (match) {
637
+ if (i > start) result.push(text.slice(start, i));
638
+ result.push(match);
639
+ i += match.length;
640
+ start = i;
641
+ } else ++i;
545
642
  }
546
- }
547
- };
548
- const imageModelManifests = [flux2Klein4B8BitAbliterated, ternaryBonsaiImage4B];
549
- function imageModelManifest(model) {
550
- return imageModelManifests.find((manifest) => manifest.model === model);
551
- }
552
- const flux2KleinModelFiles = [
553
- {
554
- repo: flux2Klein4B8BitAbliterated.components.textEncoder.repo,
555
- revision: flux2Klein4B8BitAbliterated.components.textEncoder.revision,
556
- source: "config.json",
557
- destination: "text-encoder/config.json",
558
- bytes: 937
559
- },
560
- {
561
- repo: flux2Klein4B8BitAbliterated.components.textEncoder.repo,
562
- revision: flux2Klein4B8BitAbliterated.components.textEncoder.revision,
563
- source: "tokenizer.json",
564
- destination: "text-encoder/tokenizer.json",
565
- bytes: 11422654
566
- },
567
- {
568
- repo: flux2Klein4B8BitAbliterated.components.textEncoder.repo,
569
- revision: flux2Klein4B8BitAbliterated.components.textEncoder.revision,
570
- source: "tokenizer_config.json",
571
- destination: "text-encoder/tokenizer_config.json",
572
- bytes: 9706
573
- },
574
- {
575
- repo: flux2Klein4B8BitAbliterated.components.textEncoder.repo,
576
- revision: flux2Klein4B8BitAbliterated.components.textEncoder.revision,
577
- source: "model.safetensors",
578
- destination: "text-encoder/model.safetensors",
579
- bytes: 4274158989
580
- },
581
- {
582
- repo: flux2Klein4B8BitAbliterated.components.textEncoder.repo,
583
- revision: flux2Klein4B8BitAbliterated.components.textEncoder.revision,
584
- source: "model.safetensors.index.json",
585
- destination: "text-encoder/model.safetensors.index.json",
586
- bytes: 63924
587
- },
588
- {
589
- repo: flux2Klein4B8BitAbliterated.components.transformer.repo,
590
- revision: flux2Klein4B8BitAbliterated.components.transformer.revision,
591
- source: "transformer/config.json",
592
- destination: "transformer/config.json",
593
- bytes: 541
594
- },
595
- {
596
- repo: flux2Klein4B8BitAbliterated.components.transformer.repo,
597
- revision: flux2Klein4B8BitAbliterated.components.transformer.revision,
598
- source: "transformer/quantized_8bit.safetensors",
599
- destination: "transformer/quantized_8bit.safetensors",
600
- bytes: 4360050983
601
- },
602
- {
603
- repo: flux2Klein4B8BitAbliterated.components.vae.repo,
604
- revision: flux2Klein4B8BitAbliterated.components.vae.revision,
605
- source: "vae/config.json",
606
- destination: "vae/config.json",
607
- bytes: 821
608
- },
609
- {
610
- repo: flux2Klein4B8BitAbliterated.components.vae.repo,
611
- revision: flux2Klein4B8BitAbliterated.components.vae.revision,
612
- source: "vae/diffusion_pytorch_model.safetensors",
613
- destination: "vae/diffusion_pytorch_model.safetensors",
614
- bytes: 168120878
615
- }
616
- ];
617
- const flux2KleinTotalBytes = flux2KleinModelFiles.reduce((total, file) => total + file.bytes, 0);
618
- const bonsaiRepo = ternaryBonsaiImage4B.components.textEncoder.repo;
619
- const bonsaiRevision = ternaryBonsaiImage4B.components.textEncoder.revision;
620
- const ternaryBonsaiImageModelFiles = [
621
- {
622
- repo: bonsaiRepo,
623
- revision: bonsaiRevision,
624
- source: "text_encoder-mlx-4bit/config.json",
625
- destination: "text-encoder/config.json",
626
- bytes: 937
627
- },
628
- {
629
- repo: bonsaiRepo,
630
- revision: bonsaiRevision,
631
- source: "text_encoder-mlx-4bit/tokenizer.json",
632
- destination: "text-encoder/tokenizer.json",
633
- bytes: 11422654
634
- },
635
- {
636
- repo: bonsaiRepo,
637
- revision: bonsaiRevision,
638
- source: "text_encoder-mlx-4bit/tokenizer_config.json",
639
- destination: "text-encoder/tokenizer_config.json",
640
- bytes: 9706
641
- },
642
- {
643
- repo: bonsaiRepo,
644
- revision: bonsaiRevision,
645
- source: "text_encoder-mlx-4bit/model.safetensors",
646
- destination: "text-encoder/model.safetensors",
647
- bytes: 2263022529
648
- },
649
- {
650
- repo: bonsaiRepo,
651
- revision: bonsaiRevision,
652
- source: "text_encoder-mlx-4bit/model.safetensors.index.json",
653
- destination: "text-encoder/model.safetensors.index.json",
654
- bytes: 63924
655
- },
656
- {
657
- repo: bonsaiRepo,
658
- revision: bonsaiRevision,
659
- source: "transformer-packed-mflux/config.json",
660
- destination: "transformer/config.json",
661
- bytes: 619
662
- },
663
- {
664
- repo: bonsaiRepo,
665
- revision: bonsaiRevision,
666
- source: "transformer-packed-mflux/diffusion_pytorch_model.safetensors",
667
- destination: "transformer/diffusion_pytorch_model.safetensors",
668
- bytes: 1425271472
669
- },
670
- {
671
- repo: bonsaiRepo,
672
- revision: bonsaiRevision,
673
- source: "transformer-packed-mflux/quantization_config.json",
674
- destination: "transformer/quantization_config.json",
675
- bytes: 5054
676
- },
677
- {
678
- repo: bonsaiRepo,
679
- revision: bonsaiRevision,
680
- source: "vae/config.json",
681
- destination: "vae/config.json",
682
- bytes: 821
683
- },
684
- {
685
- repo: bonsaiRepo,
686
- revision: bonsaiRevision,
687
- source: "vae/diffusion_pytorch_model.safetensors",
688
- destination: "vae/diffusion_pytorch_model.safetensors",
689
- bytes: 168120878
690
- }
691
- ];
692
- const ternaryBonsaiImageTotalBytes = ternaryBonsaiImageModelFiles.reduce((total, file) => total + file.bytes, 0);
693
- function joinModelPath(root, component) {
694
- return `${root.replace(/\/+$/, "")}/${component.replace(/^\/+/, "")}`;
695
- }
696
- function fluxImageModelPaths(path, manifest = flux2Klein4B8BitAbliterated) {
697
- return {
698
- path,
699
- textEncoderPath: joinModelPath(path, manifest.components.textEncoder.path),
700
- transformerPath: joinModelPath(path, manifest.components.transformer.path),
701
- vaePath: joinModelPath(path, manifest.components.vae.path)
702
- };
703
- }
704
-
705
- //#endregion
706
- //#region src/ai/image-schedule.ts
707
- function imageSigmaSchedule(schedules) {
708
- const configured = schedules.filter((schedule) => schedule !== void 0);
709
- if (configured.length === 0) return void 0;
710
- const first = configured[0];
711
- if (first.length === 0 || first.some((sigma, index) => !Number.isFinite(sigma) || sigma <= 0 || sigma > 1 || index > 0 && sigma >= first[index - 1])) throw new AIError("invalid_model", "LoRA sigmaSchedule must contain descending values greater than 0 and at most 1");
712
- if (configured.some((schedule) => schedule.length !== first.length || schedule.some((sigma, index) => sigma !== first[index]))) throw new AIError("invalid_model", "Selected LoRAs require conflicting sigma schedules");
713
- return [...first];
714
- }
715
-
716
- //#endregion
717
- //#region src/ai/image-upscale.ts
718
- function normalizeUpscaleScale(value) {
719
- const scale = value ?? 2;
720
- if (!Number.isFinite(scale) || scale <= 1 || scale > 4) throw new AIError("invalid_model", "Upscale scale must be greater than 1 and at most 4");
721
- return scale;
722
- }
723
-
724
- //#endregion
725
- //#region src/ai/native.ts
726
- function bridge() {
727
- try {
728
- return requireNativeModule("AI");
729
- } catch (error) {
730
- throw new AIError("unsupported_runtime", "bleam/ai requires the Bleam native runtime", error);
731
- }
732
- }
733
-
734
- //#endregion
735
- //#region src/ai/tokenizers.mjs
736
- var DictionarySplitter = class {
737
- /**
738
- * @param dictionary The dictionary of words to use for splitting.
739
- */
740
- constructor(dictionary) {
741
- this.trie = this._build_trie(dictionary);
742
- }
743
- /**
744
- * Builds a trie from the given dictionary.
745
- * @param dictionary The dictionary of words to build the trie from.
746
- * @returns The root node of the trie.
747
- * @private
748
- */
749
- _build_trie(dictionary) {
750
- const trie = /* @__PURE__ */ Object.create(null);
751
- for (const word of dictionary) {
752
- let node = trie;
753
- for (let i = 0; i < word.length; ++i) {
754
- const char = word[i];
755
- node = node[char] ??= /* @__PURE__ */ Object.create(null);
756
- }
757
- node.end = word;
758
- }
759
- return trie;
760
- }
761
- /**
762
- * Splits the input text into tokens based on the dictionary.
763
- * @param text The input text to split.
764
- * @returns An array of tokens.
765
- */
766
- split(text) {
767
- const result = [];
768
- const n = text.length;
769
- let start = 0;
770
- let i = 0;
771
- while (i < n) {
772
- let node = this.trie;
773
- let match = null;
774
- let j = i;
775
- while (j < n && (node = node[text[j]])) {
776
- if (node.end) match = node.end;
777
- ++j;
778
- }
779
- if (match) {
780
- if (i > start) result.push(text.slice(start, i));
781
- result.push(match);
782
- i += match.length;
783
- start = i;
784
- } else ++i;
785
- }
786
- if (start < n) result.push(text.slice(start));
787
- return result;
643
+ if (start < n) result.push(text.slice(start));
644
+ return result;
788
645
  }
789
646
  };
790
647
  var DictionarySplitter_default = DictionarySplitter;
@@ -869,7 +726,7 @@ var create_pattern = (pattern, invert = true) => {
869
726
  return null;
870
727
  }
871
728
  };
872
- var escape_reg_exp = (string) => string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
729
+ var escape_reg_exp = (string$1) => string$1.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
873
730
  var fuse_unk = (arr, tokens_to_ids, unk_token_id) => {
874
731
  const fused = [];
875
732
  let i = 0;
@@ -2591,16 +2448,16 @@ var ByteFallback = class extends Decoder_default {
2591
2448
  if (bytes !== null) previous_byte_tokens.push(bytes);
2592
2449
  else {
2593
2450
  if (previous_byte_tokens.length > 0) {
2594
- const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));
2595
- new_tokens.push(string);
2451
+ const string$1 = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));
2452
+ new_tokens.push(string$1);
2596
2453
  previous_byte_tokens = [];
2597
2454
  }
2598
2455
  new_tokens.push(token);
2599
2456
  }
2600
2457
  }
2601
2458
  if (previous_byte_tokens.length > 0) {
2602
- const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));
2603
- new_tokens.push(string);
2459
+ const string$1 = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));
2460
+ new_tokens.push(string$1);
2604
2461
  previous_byte_tokens = [];
2605
2462
  }
2606
2463
  return new_tokens;
@@ -2796,1849 +2653,2142 @@ var Tokenizer = class {
2796
2653
  var Tokenizer_default = Tokenizer;
2797
2654
 
2798
2655
  //#endregion
2799
- //#region src/ai/image.ts
2800
- function imageModelId(model) {
2801
- return typeof model === "string" ? model : model.id;
2802
- }
2803
- function imageModelDefinition(model) {
2804
- const id = imageModelId(model);
2805
- if (id === flux2Klein4B8BitAbliterated.model) return {
2806
- manifest: flux2Klein4B8BitAbliterated,
2807
- files: flux2KleinModelFiles,
2808
- totalBytes: flux2KleinTotalBytes
2809
- };
2810
- if (id === ternaryBonsaiImage4B.model) return {
2811
- manifest: ternaryBonsaiImage4B,
2812
- files: ternaryBonsaiImageModelFiles,
2813
- totalBytes: ternaryBonsaiImageTotalBytes
2656
+ //#region src/ai/bonsai-generation.ts
2657
+ async function prepareBonsaiGeneration(input) {
2658
+ const state = await verifyBonsaiTextModel(input.model, { path: input.path });
2659
+ if (!state.verified) throw new AIError("model_unavailable", `${input.model.id} is not prepared. Call prepareTextModel() before generation.`);
2660
+ const tokenizer = new Tokenizer_default(await files.file(state.path, "tokenizer.json").json(), await files.file(state.path, "tokenizer_config.json").json());
2661
+ const inputIds = tokenizer.encode(formatMessages(messagesFromInput(input))).ids.map(Number);
2662
+ if (!inputIds.length || inputIds.some((token) => !Number.isInteger(token))) throw new AIError("invalid_message", "Tokenizer returned invalid token ids");
2663
+ return {
2664
+ request: {
2665
+ id: input.id,
2666
+ model: input.model.id,
2667
+ modelPath: state.path,
2668
+ inputIds,
2669
+ endTokenIds: endTokenIds(input.model.id),
2670
+ maxTokens: input.maxTokens,
2671
+ temperature: input.temperature,
2672
+ seed: input.seed
2673
+ },
2674
+ decode(tokenIds) {
2675
+ return tokenIds.length ? tokenizer.decode(tokenIds, { skip_special_tokens: true }) : "";
2676
+ }
2814
2677
  };
2815
- throw new AIError("invalid_model", `Unsupported image model: ${id}`);
2816
2678
  }
2817
- function modelCacheRoot(manifest) {
2818
- return files.directory(files.paths.models, manifest.directory);
2679
+ function messagesFromInput(input) {
2680
+ if (input.messages) {
2681
+ if (input.system !== void 0 || input.prompt !== void 0) throw new AIError("invalid_message", "messages cannot be combined with system or prompt");
2682
+ if (!input.messages.length) throw new AIError("invalid_message", "Expected at least one message");
2683
+ return input.messages;
2684
+ }
2685
+ if (!input.prompt?.trim()) throw new AIError("invalid_message", "Expected prompt");
2686
+ return [...input.system ? [{
2687
+ role: "system",
2688
+ content: input.system
2689
+ }] : [], {
2690
+ role: "user",
2691
+ content: input.prompt
2692
+ }];
2819
2693
  }
2820
- function assertImageModel(model) {
2821
- imageModelDefinition(model);
2694
+ function formatMessages(messages) {
2695
+ if (messages[0]?.role === "assistant") throw new AIError("invalid_message", "Conversation cannot begin with assistant");
2696
+ const parts = messages.map((message, index) => {
2697
+ if (!message.content.trim()) throw new AIError("invalid_message", `Message ${index + 1} is empty`);
2698
+ if (message.role === "system" && index !== 0) throw new AIError("invalid_message", "System message must be first");
2699
+ return `<|im_start|>${message.role}\n${message.content}<|im_end|>\n`;
2700
+ });
2701
+ parts.push("<|im_start|>assistant\n<think>\n\n</think>\n\n");
2702
+ return parts.join("");
2822
2703
  }
2823
- function modelPathFromOptions(definition, path) {
2824
- return path ?? modelCacheRoot(definition.manifest).path;
2704
+ function endTokenIds(model) {
2705
+ return model === "ternary-bonsai-27b" ? [248044, 248046] : [151643, 151645];
2825
2706
  }
2826
- function downloadConcurrency(value) {
2827
- if (value === void 0) return 2;
2828
- if (!Number.isInteger(value)) throw new AIError("invalid_model", "concurrency must be an integer");
2829
- return Math.min(4, Math.max(1, value));
2707
+
2708
+ //#endregion
2709
+ //#region src/ai/native.ts
2710
+ function bridge() {
2711
+ try {
2712
+ return requireNativeModule("AI");
2713
+ } catch (error) {
2714
+ throw new AIError("unsupported_runtime", "bleam/ai requires the Bleam native runtime", error);
2715
+ }
2830
2716
  }
2831
- async function runConcurrent(items, concurrency, worker) {
2832
- let nextIndex = 0;
2833
- const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
2834
- while (nextIndex < items.length) {
2835
- const item = items[nextIndex];
2836
- nextIndex += 1;
2837
- await worker(item);
2838
- }
2717
+
2718
+ //#endregion
2719
+ //#region src/ai/chat-executor.ts
2720
+ function generationId() {
2721
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
2722
+ }
2723
+ function foundationRequest(options, id) {
2724
+ if (options.temperature !== void 0 && (!Number.isFinite(options.temperature) || options.temperature < 0)) throw new AIError("invalid_message", "temperature must be a non-negative number");
2725
+ if (options.maxTokens !== void 0 && (!Number.isInteger(options.maxTokens) || options.maxTokens <= 0)) throw new AIError("invalid_message", "maxTokens must be a positive integer");
2726
+ if (options.messages.length === 0) throw new AIError("invalid_message", "Expected at least one message");
2727
+ let system;
2728
+ const conversation = [];
2729
+ for (const [index, message] of options.messages.entries()) {
2730
+ if (!message.content.trim()) throw new AIError("invalid_message", `Message ${index + 1} is empty`);
2731
+ if (message.role === "system") {
2732
+ if (index !== 0 || system !== void 0) throw new AIError("invalid_message", "System message must be first");
2733
+ system = message.content;
2734
+ } else conversation.push({
2735
+ role: message.role,
2736
+ content: message.content
2737
+ });
2738
+ }
2739
+ if (conversation[0]?.role === "assistant") throw new AIError("invalid_message", "Conversation cannot begin with assistant");
2740
+ const final = conversation.at(-1);
2741
+ if (final?.role !== "user") throw new AIError("invalid_message", "Conversation must end with a user message");
2742
+ return {
2743
+ id,
2744
+ system,
2745
+ prompt: final.content,
2746
+ messages: conversation.slice(0, -1),
2747
+ temperature: options.temperature,
2748
+ maxTokens: options.maxTokens
2749
+ };
2750
+ }
2751
+ async function* streamChat(options) {
2752
+ if (options.model) {
2753
+ yield* streamBonsaiChat(options);
2754
+ return;
2755
+ }
2756
+ const id = generationId();
2757
+ const native = bridge();
2758
+ const updates = [];
2759
+ let wake;
2760
+ let settled = false;
2761
+ let failure;
2762
+ const updateSubscription = native.addListener?.("textGenerationUpdate", (event) => {
2763
+ if (event.id !== id) return;
2764
+ updates.push(event.content);
2765
+ wake?.();
2766
+ wake = void 0;
2839
2767
  });
2840
- await Promise.all(workers);
2768
+ const abort = () => void native.cancelTextGeneration?.(id);
2769
+ options.signal.addEventListener("abort", abort, { once: true });
2770
+ const completion = native.streamGenerate?.(foundationRequest(options, id)).catch((error) => {
2771
+ failure = error;
2772
+ }).finally(() => {
2773
+ settled = true;
2774
+ wake?.();
2775
+ wake = void 0;
2776
+ });
2777
+ try {
2778
+ if (options.signal.aborted) {
2779
+ abort();
2780
+ throw new AIError("generation_canceled", "Generation canceled");
2781
+ }
2782
+ if (!completion) throw new AIError("unsupported_runtime", "Streaming is unavailable in this runtime");
2783
+ while (!settled || updates.length > 0) if (updates.length > 0) yield updates.shift();
2784
+ else await new Promise((resolve) => {
2785
+ wake = resolve;
2786
+ });
2787
+ await completion;
2788
+ if (failure) throw mapNativeError(failure);
2789
+ } finally {
2790
+ if (!settled) await native.cancelTextGeneration?.(id);
2791
+ options.signal.removeEventListener("abort", abort);
2792
+ updateSubscription?.remove();
2793
+ }
2841
2794
  }
2842
- function hfResolveUrl(repo, revision, path) {
2843
- const encodedRepo = repo.split("/").map(encodeURIComponent).join("/");
2844
- const encodedPath = path.split("/").map(encodeURIComponent).join("/");
2845
- return `https://huggingface.co/${encodedRepo}/resolve/${encodeURIComponent(revision)}/${encodedPath}`;
2795
+ async function* streamBonsaiChat(options) {
2796
+ const id = generationId();
2797
+ const native = bridge();
2798
+ if (options.signal.aborted) throw new AIError("generation_canceled", "Generation canceled");
2799
+ const prepared = await prepareBonsaiGeneration({
2800
+ id,
2801
+ model: options.model,
2802
+ path: options.path,
2803
+ messages: options.messages,
2804
+ temperature: options.temperature,
2805
+ maxTokens: options.maxTokens,
2806
+ seed: options.seed
2807
+ });
2808
+ if (options.signal.aborted) throw new AIError("generation_canceled", "Generation canceled");
2809
+ const updates = [];
2810
+ let wake;
2811
+ let settled = false;
2812
+ let failure;
2813
+ const updateSubscription = native.addListener?.("localTextGenerationUpdate", (event) => {
2814
+ if (event.id !== id) return;
2815
+ updates.push(event.tokenIds);
2816
+ wake?.();
2817
+ wake = void 0;
2818
+ });
2819
+ const abort = () => void native.cancelTextGeneration?.(id);
2820
+ options.signal.addEventListener("abort", abort, { once: true });
2821
+ const completion = native.streamLocalText?.(prepared.request).catch((error) => {
2822
+ failure = error;
2823
+ return [];
2824
+ }).finally(() => {
2825
+ settled = true;
2826
+ wake?.();
2827
+ wake = void 0;
2828
+ });
2829
+ try {
2830
+ if (!completion) throw new AIError("unsupported_runtime", "Local text streaming is unavailable in this runtime");
2831
+ while (!settled || updates.length > 0) if (updates.length > 0) yield prepared.decode(updates.shift());
2832
+ else await new Promise((resolve) => {
2833
+ wake = resolve;
2834
+ });
2835
+ await completion;
2836
+ if (failure) throw mapNativeError(failure);
2837
+ } finally {
2838
+ if (!settled) await native.cancelTextGeneration?.(id);
2839
+ options.signal.removeEventListener("abort", abort);
2840
+ updateSubscription?.remove();
2841
+ }
2846
2842
  }
2847
- const imageDimensionMultiple = 16;
2848
- const minimumImageDimension = 64;
2849
- const defaultImageLongSide = 1152;
2850
- const aspectRatioValues = {
2851
- "1:1": [1, 1],
2852
- "16:9": [16, 9],
2853
- "9:16": [9, 16],
2854
- "4:3": [4, 3],
2855
- "3:2": [3, 2],
2856
- "2:3": [2, 3],
2857
- "21:9": [21, 9]
2843
+
2844
+ //#endregion
2845
+ //#region src/ai/chat.tsx
2846
+ const chatShape = {
2847
+ title: string({ default: "New Chat" }),
2848
+ status: string({ default: "ready" })
2858
2849
  };
2859
- function normalizedDimension(value) {
2860
- return Math.max(minimumImageDimension, Math.floor(value / imageDimensionMultiple) * imageDimensionMultiple);
2850
+ const errorShape = {
2851
+ name: string(),
2852
+ message: string(),
2853
+ code: string(),
2854
+ stage: string()
2855
+ };
2856
+ const messageShape = {
2857
+ chatId: string(),
2858
+ role: string(),
2859
+ status: string(),
2860
+ content: string({ default: "" }),
2861
+ attempt: number({ default: 1 }),
2862
+ sequence: number(),
2863
+ error: object(errorShape),
2864
+ startedAt: string(),
2865
+ completedAt: string()
2866
+ };
2867
+ const chats = atomCollection("__bleam_ai_chats", chatShape);
2868
+ const chatMessages = atomCollection("__bleam_ai_chat_messages", messageShape);
2869
+ var CollectionChatRepository = class {
2870
+ async create(input) {
2871
+ const insert = mutateAtom(chats, (mutation) => mutation.insert());
2872
+ const id = await internalStore.set(internalJotaiWritableAtom(insert), {
2873
+ title: input.title ?? "New Chat",
2874
+ status: "ready"
2875
+ });
2876
+ return this.requireChat(id);
2877
+ }
2878
+ async get(id) {
2879
+ const row = queryAtom(chats, (query) => query.row(id));
2880
+ return chatFromRow(await internalStore.get(internalJotaiAtom(row)));
2881
+ }
2882
+ async list() {
2883
+ const ids = queryAtom(chats, (query) => query.sortBy("updatedAt", "desc").ids());
2884
+ const values = await internalStore.get(internalJotaiAtom(ids));
2885
+ return Promise.all(values.map((id) => this.requireChat(id)));
2886
+ }
2887
+ async messages(chatId) {
2888
+ const ids = queryAtom(chatMessages, (query) => query.where({ chatId }).sortBy("sequence").ids());
2889
+ const values = await internalStore.get(internalJotaiAtom(ids));
2890
+ return (await Promise.all(values.map((id) => this.messageRow(id)))).flatMap((row) => row ? [messageFromRow(row)] : []);
2891
+ }
2892
+ async acceptSend(chatId, content) {
2893
+ const transaction = transactionAtom(async (tx) => {
2894
+ const chat$1 = await tx.get(chats, chatId);
2895
+ if (!chat$1) throw new Error(`Chat not found: ${chatId}`);
2896
+ if (isActiveStatus(chat$1.data.status)) throw new Error("This chat already has an active generation");
2897
+ const previousIds = await tx.query(chatMessages, (query) => query.where({ chatId }).sortBy("sequence", "desc").take(1).ids());
2898
+ const sequence = ((previousIds[0] ? await tx.get(chatMessages, previousIds[0]) : null)?.data.sequence ?? 0) + 1;
2899
+ const userId = await tx.insert(chatMessages, {
2900
+ chatId,
2901
+ role: "user",
2902
+ status: "completed",
2903
+ content,
2904
+ attempt: 1,
2905
+ sequence,
2906
+ completedAt: timestamp()
2907
+ });
2908
+ const assistantId = await tx.insert(chatMessages, {
2909
+ chatId,
2910
+ role: "assistant",
2911
+ status: "queued",
2912
+ content: "",
2913
+ attempt: 1,
2914
+ sequence: sequence + 1
2915
+ });
2916
+ return acceptedFromTransaction(tx, await tx.update(chats, chatId, { status: "queued" }), assistantId, userId);
2917
+ });
2918
+ return internalStore.set(internalJotaiWritableAtom(transaction));
2919
+ }
2920
+ async start(chatId, messageId) {
2921
+ return this.transition(chatId, messageId, async (tx, _chat, message) => {
2922
+ if (message.data.status !== "queued") throw new Error("Only queued messages can start");
2923
+ const startedAt = timestamp();
2924
+ const assistant = await tx.update(chatMessages, messageId, {
2925
+ status: "generating",
2926
+ startedAt
2927
+ });
2928
+ return acceptedFromTransaction(tx, await tx.update(chats, chatId, { status: "generating" }), assistant.id);
2929
+ });
2930
+ }
2931
+ async updateContent(message) {
2932
+ const update = mutateAtom(chatMessages, (mutation) => mutation.update(message.id));
2933
+ return messageFromRow(await internalStore.set(internalJotaiWritableAtom(update), { content: message.content }));
2934
+ }
2935
+ async markCanceling(chatId, messageId) {
2936
+ return this.transition(chatId, messageId, async (tx, _chat, message) => {
2937
+ if (!isActiveStatus(message.data.status ?? "")) throw new Error("Message is not active");
2938
+ const assistant = await tx.update(chatMessages, messageId, { status: "canceling" });
2939
+ return acceptedFromTransaction(tx, await tx.update(chats, chatId, { status: "canceling" }), assistant.id);
2940
+ });
2941
+ }
2942
+ async finish(chatId, messageId, status, content, error) {
2943
+ return this.transition(chatId, messageId, async (tx, _chat) => {
2944
+ const completedAt = timestamp();
2945
+ const assistant = await tx.update(chatMessages, messageId, {
2946
+ status,
2947
+ content,
2948
+ error,
2949
+ completedAt
2950
+ });
2951
+ return acceptedFromTransaction(tx, await tx.update(chats, chatId, { status: status === "completed" ? "ready" : status }), assistant.id);
2952
+ });
2953
+ }
2954
+ async retry(chatId, messageId) {
2955
+ return this.transition(chatId, messageId, async (tx, _chat, message) => {
2956
+ const ids = await tx.query(chatMessages, (query) => query.where({ chatId }).sortBy("sequence", "desc").ids());
2957
+ const rows = await Promise.all(ids.map((id) => tx.get(chatMessages, id)));
2958
+ if (rows.find((row) => row?.data.role === "assistant")?.id !== messageId) throw new Error("Only the latest assistant message can be retried");
2959
+ if (message.data.status !== "failed" && message.data.status !== "canceled") throw new Error("Only failed or canceled messages can be retried");
2960
+ const assistant = await tx.update(chatMessages, messageId, {
2961
+ status: "queued",
2962
+ content: "",
2963
+ attempt: message.data.attempt + 1,
2964
+ error: void 0,
2965
+ startedAt: void 0,
2966
+ completedAt: void 0
2967
+ });
2968
+ const nextChat = await tx.update(chats, chatId, { status: "queued" });
2969
+ const user = rows.find((row) => row?.data.role === "user" && (row.data.sequence ?? 0) < (assistant.data.sequence ?? 0));
2970
+ return acceptedFromTransaction(tx, nextChat, assistant.id, user?.id);
2971
+ });
2972
+ }
2973
+ async setTitle(id, title) {
2974
+ const update = mutateAtom(chats, (mutation) => mutation.update(id));
2975
+ return chatFromRow(await internalStore.set(internalJotaiWritableAtom(update), { title }));
2976
+ }
2977
+ async remove(id) {
2978
+ const transaction = transactionAtom(async (tx) => {
2979
+ const chat$1 = await tx.get(chats, id);
2980
+ if (!chat$1) return false;
2981
+ if (isActiveStatus(chat$1.data.status)) throw new Error("Active chats cannot be removed");
2982
+ const ids = await tx.query(chatMessages, (query) => query.where({ chatId: id }).ids());
2983
+ for (const messageId of ids) await tx.remove(chatMessages, messageId);
2984
+ return tx.remove(chats, id);
2985
+ });
2986
+ return internalStore.set(internalJotaiWritableAtom(transaction));
2987
+ }
2988
+ async recoverActive() {
2989
+ const transaction = transactionAtom(async (tx) => {
2990
+ const chatIds = await tx.query(chats, (query) => query.ids());
2991
+ for (const chatId of chatIds) {
2992
+ const chat$1 = await tx.get(chats, chatId);
2993
+ if (!chat$1) continue;
2994
+ const messageIds = await tx.query(chatMessages, (query) => query.where({ chatId }).ids());
2995
+ let recoveredMessage = false;
2996
+ for (const messageId of messageIds) {
2997
+ const message = await tx.get(chatMessages, messageId);
2998
+ if (message?.data.role === "assistant" && isActiveStatus(message.data.status ?? "")) {
2999
+ await tx.update(chatMessages, messageId, {
3000
+ status: "canceled",
3001
+ error: recoveryError(),
3002
+ completedAt: timestamp()
3003
+ });
3004
+ recoveredMessage = true;
3005
+ }
3006
+ }
3007
+ if (recoveredMessage || isActiveStatus(chat$1.data.status)) await tx.update(chats, chatId, { status: "canceled" });
3008
+ }
3009
+ });
3010
+ await internalStore.set(internalJotaiWritableAtom(transaction));
3011
+ }
3012
+ async requireChat(id) {
3013
+ const chat$1 = await this.get(id);
3014
+ if (!chat$1) throw new Error(`Chat not found: ${id}`);
3015
+ return chat$1;
3016
+ }
3017
+ async messageRow(id) {
3018
+ const row = queryAtom(chatMessages, (query) => query.row(id));
3019
+ return internalStore.get(internalJotaiAtom(row));
3020
+ }
3021
+ async transition(chatId, messageId, action) {
3022
+ const transaction = transactionAtom(async (tx) => {
3023
+ const chat$1 = await tx.get(chats, chatId);
3024
+ const message = await tx.get(chatMessages, messageId);
3025
+ if (!chat$1) throw new Error(`Chat not found: ${chatId}`);
3026
+ if (!message || message.data.chatId !== chatId) throw new Error(`Message not found: ${messageId}`);
3027
+ return action(tx, chat$1, message);
3028
+ });
3029
+ return internalStore.set(internalJotaiWritableAtom(transaction));
3030
+ }
3031
+ };
3032
+ const managerKey = Symbol.for("bleam.ai.chatManager.v1");
3033
+ function managedChats() {
3034
+ const scope = globalThis;
3035
+ scope[managerKey] ??= new ChatManager(new CollectionChatRepository(), { stream(options) {
3036
+ return streamChat(options);
3037
+ } });
3038
+ return scope[managerKey];
3039
+ }
3040
+ const chat = {
3041
+ create(input = {}) {
3042
+ return managedChats().create(input);
3043
+ },
3044
+ get(id) {
3045
+ return managedChats().get(id);
3046
+ },
3047
+ list() {
3048
+ return managedChats().list();
3049
+ },
3050
+ send(id, content, options) {
3051
+ return managedChats().send(id, content, options);
3052
+ },
3053
+ cancel(id) {
3054
+ return managedChats().cancel(id);
3055
+ },
3056
+ retry(id, messageId, options) {
3057
+ return managedChats().retry(id, messageId, options);
3058
+ },
3059
+ setTitle(id, title) {
3060
+ return managedChats().setTitle(id, title);
3061
+ },
3062
+ remove(id) {
3063
+ return managedChats().remove(id);
3064
+ }
3065
+ };
3066
+ function useChat(id, options = {}) {
3067
+ const manager = managedChats();
3068
+ use(manager.ready);
3069
+ const snapshot = useSyncExternalStore((listener) => manager.subscribeChat(id, listener), () => manager.getChatSnapshot(id));
3070
+ const generationOptions = optionsWithoutCallbacks(options);
3071
+ const callbacks = {
3072
+ onFinish: options.onFinish,
3073
+ onError: options.onError
3074
+ };
3075
+ const status = snapshot.chat?.status ?? "not-found";
3076
+ const active = status === "queued" || status === "generating" || status === "canceling";
3077
+ const error = snapshot.messages.findLast((message) => message.role === "assistant")?.error;
3078
+ return {
3079
+ chat: snapshot.chat,
3080
+ messages: snapshot.messages,
3081
+ status,
3082
+ error: error ?? null,
3083
+ isGenerating: active,
3084
+ canSend: snapshot.chat !== null && !active,
3085
+ canCancel: status === "queued" || status === "generating",
3086
+ send: (content, invocation) => manager.send(id, content, mergeOptions(generationOptions, invocation), callbacks),
3087
+ cancel: () => manager.cancel(id),
3088
+ retry: (messageId, invocation) => manager.retry(id, messageId, mergeOptions(generationOptions, invocation), callbacks),
3089
+ setTitle: (title) => manager.setTitle(id, title),
3090
+ remove: () => manager.remove(id)
3091
+ };
2861
3092
  }
2862
- function normalizeImageSize(size, maxLongSide = defaultImageLongSide) {
2863
- if (!Number.isFinite(size.width) || size.width <= 0) throw new AIError("invalid_model", "size.width must be positive");
2864
- if (!Number.isFinite(size.height) || size.height <= 0) throw new AIError("invalid_model", "size.height must be positive");
2865
- if (maxLongSide !== false && (!Number.isInteger(maxLongSide) || maxLongSide < minimumImageDimension)) throw new AIError("invalid_model", `maxLongSide must be false or an integer of at least ${minimumImageDimension}`);
2866
- const scale = maxLongSide === false ? 1 : Math.min(1, maxLongSide / Math.max(size.width, size.height));
3093
+ function useChatList() {
3094
+ const manager = managedChats();
3095
+ use(manager.ready);
3096
+ return useSyncExternalStore((listener) => manager.subscribeList(listener), () => manager.getListSnapshot());
3097
+ }
3098
+ async function acceptedFromTransaction(tx, chatRow, assistantId, userId) {
3099
+ const ids = await tx.query(chatMessages, (query) => query.where({ chatId: chatRow.id }).sortBy("sequence").ids());
3100
+ const messages = (await Promise.all(ids.map((id) => tx.get(chatMessages, id)))).flatMap((row) => row ? [messageFromRow(row)] : []);
3101
+ const assistantMessage = messages.find((message) => message.id === assistantId);
3102
+ if (assistantMessage?.role !== "assistant") throw new Error(`Assistant message not found: ${assistantId}`);
3103
+ const userMessage = userId ? messages.find((message) => message.id === userId) : void 0;
2867
3104
  return {
2868
- width: normalizedDimension(size.width * scale),
2869
- height: normalizedDimension(size.height * scale)
3105
+ chatId: chatRow.id,
3106
+ userMessageId: userMessage?.id ?? "",
3107
+ assistantMessageId: assistantId,
3108
+ chat: chatFromRow(chatRow),
3109
+ userMessage,
3110
+ assistantMessage,
3111
+ messages
2870
3112
  };
2871
3113
  }
2872
- function imageSizeForPreset(aspectRatio, maxLongSide = defaultImageLongSide) {
2873
- const ratio = aspectRatioValues[aspectRatio];
2874
- if (!ratio) throw new AIError("invalid_model", `Unsupported image aspect ratio: ${aspectRatio}`);
2875
- assertPositiveInteger(maxLongSide, "maxLongSide");
2876
- const [widthRatio, heightRatio] = ratio;
2877
- return normalizeImageSize(widthRatio >= heightRatio ? {
2878
- width: maxLongSide,
2879
- height: maxLongSide * heightRatio / widthRatio
2880
- } : {
2881
- width: maxLongSide * widthRatio / heightRatio,
2882
- height: maxLongSide
2883
- }, maxLongSide);
3114
+ function chatFromRow(row) {
3115
+ if (!row) return null;
3116
+ return {
3117
+ id: row.id,
3118
+ title: row.data.title,
3119
+ status: row.data.status,
3120
+ createdAt: row.createdAt,
3121
+ updatedAt: row.updatedAt
3122
+ };
2884
3123
  }
2885
- function imageLoRARoot() {
2886
- return files.directory(files.paths.models, "image-loras");
3124
+ function messageFromRow(row) {
3125
+ return {
3126
+ id: row.id,
3127
+ chatId: row.data.chatId,
3128
+ role: row.data.role,
3129
+ status: row.data.status,
3130
+ content: row.data.content,
3131
+ attempt: row.data.attempt,
3132
+ sequence: row.data.sequence,
3133
+ error: row.data.error,
3134
+ createdAt: row.createdAt,
3135
+ updatedAt: row.updatedAt,
3136
+ startedAt: row.data.startedAt,
3137
+ completedAt: row.data.completedAt
3138
+ };
2887
3139
  }
2888
- function safeCacheName(value, name) {
2889
- const trimmed = value.trim();
2890
- if (!trimmed) throw new AIError("invalid_model", `${name} must not be empty`);
2891
- return trimmed.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
3140
+ function optionsWithoutCallbacks(options) {
3141
+ const { onFinish: _onFinish, onError: _onError,...generation } = options;
3142
+ return generation;
2892
3143
  }
2893
- function sourceFileName(lora) {
2894
- if (lora.source.type === "local") return lora.source.path.split("/").pop() || `${lora.id}.safetensors`;
2895
- if (lora.source.type === "url") return lora.source.filename ?? lora.source.url.split("/").pop() ?? `${lora.id}.safetensors`;
2896
- return lora.source.path?.split("/").pop() || `${lora.id}.safetensors`;
3144
+ function mergeOptions(defaults, invocation) {
3145
+ return {
3146
+ ...defaults,
3147
+ ...invocation
3148
+ };
2897
3149
  }
2898
- function assertLoRAScale(scale, name = "lora.scale") {
2899
- const value = scale ?? 1;
2900
- if (!Number.isFinite(value) || value <= 0) throw new AIError("invalid_model", `${name} must be a positive number`);
2901
- return value;
3150
+ function isActiveStatus(status) {
3151
+ return status === "queued" || status === "generating" || status === "canceling";
2902
3152
  }
2903
- function assertLoRADefinition(lora) {
2904
- safeCacheName(lora.id, "lora.id");
2905
- assertLoRAScale(lora.scale ?? lora.metadata?.recommendedScale);
2906
- imageSigmaSchedule([lora.metadata?.sigmaSchedule]);
2907
- if (lora.metadata?.baseModel !== void 0) assertImageModel(lora.metadata.baseModel);
2908
- if (lora.metadata?.precision !== void 0 && ![
2909
- "float16",
2910
- "bfloat16",
2911
- "float32"
2912
- ].includes(lora.metadata.precision)) throw new AIError("invalid_model", "lora.metadata.precision is unsupported");
3153
+ function recoveryError() {
3154
+ return {
3155
+ name: "AIError",
3156
+ code: "generation_canceled",
3157
+ message: "Generation was interrupted when the app exited"
3158
+ };
2913
3159
  }
2914
- function assertLoRACompatibility(lora, model) {
2915
- if (lora.metadata?.baseModel && lora.metadata.baseModel !== model) throw new AIError("invalid_model", `LoRA ${lora.id} targets ${lora.metadata.baseModel}, not ${model}`);
3160
+ function timestamp() {
3161
+ return (/* @__PURE__ */ new Date()).toISOString();
2916
3162
  }
2917
- const commonLoRAFileNames = [
2918
- "pytorch_lora_weights.safetensors",
2919
- "adapter_model.safetensors",
2920
- "lora.safetensors",
2921
- "model.safetensors"
2922
- ];
2923
- async function resolveHuggingFaceLoRA(lora, options) {
2924
- if (lora.source.type !== "huggingface" || lora.source.path) return lora;
2925
- const revision = lora.source.revision ?? "main";
2926
- const manifestFile = imageLoRARoot().directory(safeCacheName(lora.id, "lora.id")).file("manifest.json");
2927
- if ((await manifestFile.stat()).type === "file") {
2928
- const manifest = await manifestFile.json();
2929
- if (isRecord(manifest) && isRecord(manifest.source) && manifest.source.type === "huggingface" && manifest.source.repo === lora.source.repo && (manifest.source.revision ?? "main") === revision && typeof manifest.source.path === "string") return {
2930
- ...lora,
2931
- source: {
2932
- ...lora.source,
2933
- revision,
2934
- path: manifest.source.path,
2935
- bytes: lora.source.bytes ?? (typeof manifest.source.bytes === "number" ? manifest.source.bytes : void 0)
2936
- }
2937
- };
2938
- }
2939
- const encodedRepo = lora.source.repo.split("/").map(encodeURIComponent).join("/");
2940
- const response = await fetch(`https://huggingface.co/api/models/${encodedRepo}/revision/${encodeURIComponent(revision)}`, {
2941
- headers: options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : void 0,
2942
- signal: options.signal
2943
- });
2944
- if (!response.ok) throw new AIError("invalid_model", `Unable to inspect Hugging Face LoRA ${lora.source.repo}: ${response.status}`);
2945
- const value = await response.json();
2946
- const siblings = isRecord(value) && Array.isArray(value.siblings) ? value.siblings.flatMap((item) => {
2947
- if (!isRecord(item) || typeof item.rfilename !== "string") return [];
2948
- return [{
2949
- path: item.rfilename,
2950
- bytes: typeof item.size === "number" ? item.size : void 0
2951
- }];
2952
- }) : [];
2953
- const common = commonLoRAFileNames.map((name) => siblings.find((file) => file.path === name)).find(Boolean);
2954
- const safetensors = siblings.filter((file) => file.path.endsWith(".safetensors"));
2955
- const selected = common ?? (safetensors.length === 1 ? safetensors[0] : void 0);
2956
- if (!selected) {
2957
- const candidates = safetensors.map((file) => file.path).join(", ");
2958
- throw new AIError("invalid_model", candidates ? `Multiple LoRA weights found for ${lora.id}; set source.path to one of: ${candidates}` : `No .safetensors LoRA weight found for ${lora.id}`);
3163
+
3164
+ //#endregion
3165
+ //#region src/ai/image-batch.ts
3166
+ function batchImageSeeds(count, seed) {
3167
+ if (!Number.isInteger(count) || count < 1 || count > 64) throw new AIError("invalid_message", "Batch count must be an integer from 1 to 64");
3168
+ const first = seed ?? Math.floor(Math.random() * 4294967296);
3169
+ return Array.from({ length: count }, (_, index) => first + index >>> 0);
3170
+ }
3171
+
3172
+ //#endregion
3173
+ //#region src/ai/image-jobs.ts
3174
+ const jobShape = {
3175
+ status: string({ default: "paused" }),
3176
+ request: string({ default: "{}" }),
3177
+ progress: string({ default: "" }),
3178
+ result: string({ default: "" }),
3179
+ error: string({ default: "" }),
3180
+ attempt: number({ default: 1 }),
3181
+ startedAt: string({ default: "" }),
3182
+ completedAt: string({ default: "" })
3183
+ };
3184
+ var CollectionImageJobRepository = class {
3185
+ records = atomCollection("__bleam_ai_jobs", jobShape);
3186
+ insertRecord = mutateAtom(this.records, (mutation) => mutation.insert());
3187
+ async list() {
3188
+ const ids = await internalStore.get(internalJotaiAtom(this.records));
3189
+ return (await Promise.all(ids.map((id) => this.getRow(id)))).flatMap((row) => row ? [jobFromRow(row)] : []);
3190
+ }
3191
+ async insert(job) {
3192
+ const id = await internalStore.set(internalJotaiWritableAtom(this.insertRecord), dataFromJob(job));
3193
+ const row = await this.getRow(id);
3194
+ if (!row) throw new Error(`Could not load inserted image job ${id}`);
3195
+ return jobFromRow(row);
3196
+ }
3197
+ async update(job) {
3198
+ const updateRecord = mutateAtom(this.records, (mutation) => mutation.update(job.id));
3199
+ return jobFromRow(await internalStore.set(internalJotaiWritableAtom(updateRecord), dataFromJob(job)));
3200
+ }
3201
+ async remove(id) {
3202
+ const removeRecord = mutateAtom(this.records, (mutation) => mutation.remove(id));
3203
+ await internalStore.set(internalJotaiWritableAtom(removeRecord));
3204
+ }
3205
+ async getRow(id) {
3206
+ const row = queryAtom(this.records, (query) => query.row(id));
3207
+ return internalStore.get(internalJotaiAtom(row));
2959
3208
  }
2960
- return {
2961
- ...lora,
2962
- source: {
2963
- ...lora.source,
2964
- revision,
2965
- path: selected.path,
2966
- bytes: lora.source.bytes ?? selected.bytes
3209
+ };
3210
+ var ImageJobManager = class {
3211
+ records = /* @__PURE__ */ new Map();
3212
+ jobListeners = /* @__PURE__ */ new Map();
3213
+ listListeners = /* @__PURE__ */ new Set();
3214
+ listSnapshot = [];
3215
+ operation = Promise.resolve();
3216
+ pumping = false;
3217
+ runningId;
3218
+ controller;
3219
+ ready;
3220
+ constructor(repository, executor, jobFiles = nativeImageJobFiles) {
3221
+ this.repository = repository;
3222
+ this.executor = executor;
3223
+ this.jobFiles = jobFiles;
3224
+ this.ready = this.initialize();
3225
+ }
3226
+ setExecutor(executor) {
3227
+ this.executor = executor;
3228
+ }
3229
+ async queue(options) {
3230
+ await this.ready;
3231
+ const request = normalizeRequest(options);
3232
+ const provisional = await this.repository.insert({
3233
+ kind: "image",
3234
+ status: "paused",
3235
+ request,
3236
+ attempt: 0
3237
+ });
3238
+ try {
3239
+ const preparedRequest = await this.jobFiles.prepare(provisional.id, request);
3240
+ const queued = await this.repository.update({
3241
+ ...provisional,
3242
+ status: "queued",
3243
+ request: preparedRequest,
3244
+ attempt: 1
3245
+ });
3246
+ this.set(queued);
3247
+ this.pump();
3248
+ return queued;
3249
+ } catch (error) {
3250
+ await this.repository.remove(provisional.id);
3251
+ await this.jobFiles.remove(provisional).catch(() => void 0);
3252
+ throw error;
2967
3253
  }
2968
- };
2969
- }
2970
- function loraUrl(lora) {
2971
- if (lora.source.type === "url") return lora.source.url;
2972
- if (lora.source.type === "huggingface") {
2973
- if (!lora.source.path) return void 0;
2974
- return hfResolveUrl(lora.source.repo, lora.source.revision ?? "main", lora.source.path);
2975
3254
  }
2976
- }
2977
- function loraExpectedBytes(lora) {
2978
- return lora.source.type === "local" ? void 0 : lora.source.bytes;
2979
- }
2980
- function hasSafetensorsHeader(size) {
2981
- return size !== void 0 && size > 8;
2982
- }
2983
- function loraHeaders(lora, accessToken) {
2984
- return lora.source.type === "huggingface" && accessToken ? { Authorization: `Bearer ${accessToken}` } : void 0;
2985
- }
2986
- function cachedLoRAFile(lora) {
2987
- const id = safeCacheName(lora.id, "lora.id");
2988
- return imageLoRARoot().directory(id).file(safeCacheName(sourceFileName(lora), "lora filename"));
2989
- }
2990
- async function ensureModelFile(input) {
2991
- const destination = files.file(input.path, input.file.destination);
2992
- const stat = await destination.stat();
2993
- if (stat.type === "file" && stat.size === input.file.bytes) {
2994
- input.onProgress?.({
2995
- model: input.model,
2996
- file: input.file.destination,
2997
- index: input.index,
2998
- total: input.total,
2999
- bytesWritten: input.file.bytes,
3000
- totalBytes: input.file.bytes,
3001
- fraction: 1
3255
+ async get(id) {
3256
+ await this.ready;
3257
+ return this.records.get(id);
3258
+ }
3259
+ async list() {
3260
+ await this.ready;
3261
+ return this.listSnapshot;
3262
+ }
3263
+ async cancel(id) {
3264
+ await this.ready;
3265
+ return this.mutate(async () => {
3266
+ const job = this.records.get(id);
3267
+ if (!job) return false;
3268
+ if (job.status === "queued" || job.status === "paused") {
3269
+ await this.replace(job, {
3270
+ status: "canceled",
3271
+ error: canceledError(),
3272
+ completedAt: now()
3273
+ });
3274
+ return true;
3275
+ }
3276
+ if (job.status !== "running") return false;
3277
+ await this.replace(job, { status: "canceling" });
3278
+ if (this.runningId === id) this.controller?.abort();
3279
+ return true;
3002
3280
  });
3003
- return;
3004
3281
  }
3005
- await destination.download(hfResolveUrl(input.file.repo, input.file.revision, input.file.source), {
3006
- headers: input.headers,
3007
- expectedBytes: input.file.bytes,
3008
- atomic: true,
3009
- resume: true,
3010
- onProgress(progress) {
3011
- input.onProgress?.({
3012
- model: input.model,
3013
- file: input.file.destination,
3014
- index: input.index,
3015
- total: input.total,
3016
- ...progress
3282
+ async retry(id) {
3283
+ await this.ready;
3284
+ const resumed = await this.mutate(async () => {
3285
+ const job = this.records.get(id);
3286
+ if (!job || job.status !== "failed" && job.status !== "canceled") return false;
3287
+ await this.replace(job, {
3288
+ status: "queued",
3289
+ attempt: job.attempt + 1,
3290
+ progress: void 0,
3291
+ result: void 0,
3292
+ error: void 0,
3293
+ startedAt: void 0,
3294
+ completedAt: void 0
3295
+ });
3296
+ return true;
3297
+ });
3298
+ if (resumed) this.pump();
3299
+ return resumed;
3300
+ }
3301
+ async resume(id) {
3302
+ await this.ready;
3303
+ const resumed = await this.mutate(async () => {
3304
+ const job = this.records.get(id);
3305
+ if (job?.status !== "paused") return false;
3306
+ await this.replace(job, { status: "queued" });
3307
+ return true;
3308
+ });
3309
+ if (resumed) this.pump();
3310
+ return resumed;
3311
+ }
3312
+ async remove(id) {
3313
+ await this.ready;
3314
+ return this.mutate(async () => {
3315
+ const job = this.records.get(id);
3316
+ if (!job) return false;
3317
+ if (job.status === "queued" || job.status === "running" || job.status === "canceling") throw new AIError("concurrent_request", "Cancel the image job before removing it");
3318
+ await this.jobFiles.remove(job);
3319
+ await this.repository.remove(id);
3320
+ this.records.delete(id);
3321
+ this.refreshList();
3322
+ this.emit(id);
3323
+ return true;
3324
+ });
3325
+ }
3326
+ getJobSnapshot(id) {
3327
+ return this.records.get(id);
3328
+ }
3329
+ getListSnapshot() {
3330
+ return this.listSnapshot;
3331
+ }
3332
+ subscribeJob(id, listener) {
3333
+ const listeners = this.jobListeners.get(id) ?? /* @__PURE__ */ new Set();
3334
+ listeners.add(listener);
3335
+ this.jobListeners.set(id, listeners);
3336
+ return () => {
3337
+ listeners.delete(listener);
3338
+ if (listeners.size === 0) this.jobListeners.delete(id);
3339
+ };
3340
+ }
3341
+ subscribeList(listener) {
3342
+ this.listListeners.add(listener);
3343
+ return () => this.listListeners.delete(listener);
3344
+ }
3345
+ async initialize() {
3346
+ const jobs$1 = await this.repository.list();
3347
+ for (const job of jobs$1) {
3348
+ if (job.status === "paused" && job.attempt === 0) {
3349
+ await this.repository.remove(job.id);
3350
+ await this.jobFiles.remove(job).catch(() => void 0);
3351
+ continue;
3352
+ }
3353
+ let recovered = job;
3354
+ if (job.status === "running" || job.status === "canceling") recovered = await this.repository.update({
3355
+ ...job,
3356
+ status: "canceled",
3357
+ error: canceledError("Generation was interrupted when the app exited"),
3358
+ completedAt: now()
3017
3359
  });
3360
+ else if (job.status === "queued") recovered = await this.repository.update({
3361
+ ...job,
3362
+ status: "paused"
3363
+ });
3364
+ this.records.set(recovered.id, recovered);
3018
3365
  }
3019
- }).result;
3020
- }
3021
- async function writePreparedManifest(path, manifest) {
3022
- await files.file(path, "manifest.json").write(JSON.stringify(manifest, null, 2));
3023
- }
3024
- async function imageModelState(model, path) {
3025
- const definition = imageModelDefinition(model);
3026
- let bytesPresent = 0;
3027
- const missingFiles = [];
3028
- const invalidFiles = [];
3029
- for (const file of definition.files) {
3030
- const stat = await files.file(path, file.destination).stat();
3031
- if (stat.type !== "file") {
3032
- missingFiles.push(file.destination);
3033
- continue;
3366
+ this.refreshList();
3367
+ }
3368
+ mutate(action) {
3369
+ const result = this.operation.then(action, action);
3370
+ this.operation = result.then(() => void 0, () => void 0);
3371
+ return result;
3372
+ }
3373
+ pump() {
3374
+ if (this.pumping) return;
3375
+ this.pumping = true;
3376
+ this.runLoop().finally(() => {
3377
+ this.pumping = false;
3378
+ if (this.nextQueued()) this.pump();
3379
+ });
3380
+ }
3381
+ async runLoop() {
3382
+ while (true) {
3383
+ const job = await this.mutate(async () => {
3384
+ const next = this.nextQueued();
3385
+ if (!next) return void 0;
3386
+ this.runningId = next.id;
3387
+ this.controller = new AbortController();
3388
+ return this.replace(next, {
3389
+ status: "running",
3390
+ startedAt: now(),
3391
+ completedAt: void 0,
3392
+ error: void 0,
3393
+ progress: void 0
3394
+ });
3395
+ });
3396
+ if (!job) return;
3397
+ const controller = this.controller;
3398
+ try {
3399
+ const result = await this.executor({
3400
+ ...job.request,
3401
+ signal: controller.signal,
3402
+ onProgress: (progress) => {
3403
+ this.mutate(async () => {
3404
+ const current = this.records.get(job.id);
3405
+ if (current?.status === "running") await this.replace(current, { progress });
3406
+ });
3407
+ }
3408
+ });
3409
+ await this.mutate(async () => {
3410
+ const current = this.records.get(job.id);
3411
+ if (!current) return;
3412
+ if (controller.signal.aborted || current.status === "canceling") {
3413
+ await this.replace(current, {
3414
+ status: "canceled",
3415
+ error: canceledError(),
3416
+ completedAt: now()
3417
+ });
3418
+ return;
3419
+ }
3420
+ await this.replace(current, {
3421
+ status: "completed",
3422
+ progress: {
3423
+ currentStep: 1,
3424
+ totalSteps: 1,
3425
+ fraction: 1
3426
+ },
3427
+ result,
3428
+ completedAt: now()
3429
+ });
3430
+ });
3431
+ } catch (error) {
3432
+ await this.mutate(async () => {
3433
+ const current = this.records.get(job.id);
3434
+ if (!current) return;
3435
+ const canceled = controller.signal.aborted || current.status === "canceling";
3436
+ await this.replace(current, {
3437
+ status: canceled ? "canceled" : "failed",
3438
+ error: canceled ? canceledError() : serializedError(error),
3439
+ completedAt: now()
3440
+ });
3441
+ });
3442
+ } finally {
3443
+ this.runningId = void 0;
3444
+ this.controller = void 0;
3445
+ }
3034
3446
  }
3035
- bytesPresent += Math.min(stat.size ?? 0, file.bytes);
3036
- if (stat.size !== file.bytes) invalidFiles.push(file.destination);
3037
3447
  }
3038
- const manifestStat = await files.file(path, "manifest.json").stat();
3039
- if (manifestStat.type !== "file") missingFiles.push("manifest.json");
3040
- const installed = missingFiles.length === 0;
3448
+ nextQueued() {
3449
+ return [...this.records.values()].filter((job) => job.status === "queued").sort((left, right) => left.createdAt === right.createdAt ? left.id.localeCompare(right.id) : left.createdAt.localeCompare(right.createdAt))[0];
3450
+ }
3451
+ async replace(job, update) {
3452
+ const persisted = await this.repository.update({
3453
+ ...job,
3454
+ ...update
3455
+ });
3456
+ this.set(persisted);
3457
+ return persisted;
3458
+ }
3459
+ set(job) {
3460
+ this.records.set(job.id, job);
3461
+ this.refreshList();
3462
+ this.emit(job.id);
3463
+ }
3464
+ refreshList() {
3465
+ this.listSnapshot = [...this.records.values()].sort((left, right) => left.createdAt === right.createdAt ? right.id.localeCompare(left.id) : right.createdAt.localeCompare(left.createdAt)).map(summaryFromJob);
3466
+ for (const listener of this.listListeners) listener();
3467
+ }
3468
+ emit(id) {
3469
+ for (const listener of this.jobListeners.get(id) ?? []) listener();
3470
+ }
3471
+ };
3472
+ function useManagedJob(manager, id) {
3473
+ use(manager.ready);
3474
+ return useSyncExternalStore((listener) => manager.subscribeJob(id, listener), () => manager.getJobSnapshot(id));
3475
+ }
3476
+ function useManagedJobList(manager) {
3477
+ use(manager.ready);
3478
+ return useSyncExternalStore((listener) => manager.subscribeList(listener), () => manager.getListSnapshot());
3479
+ }
3480
+ const nativeImageJobFiles = {
3481
+ async prepare(id, request) {
3482
+ const inputs = jobRoot(id).directory("Inputs");
3483
+ await inputs.create();
3484
+ return {
3485
+ ...request,
3486
+ image: request.image ? await copyInput(request.image, inputs.path, "Image") : void 0,
3487
+ mask: request.mask ? await copyInput(request.mask, inputs.path, "Mask") : void 0,
3488
+ references: request.references ? await Promise.all(request.references.map((reference, index) => copyInput(reference, inputs.path, `Reference-${index + 1}`))) : void 0,
3489
+ loras: request.loras ? await Promise.all(request.loras.map(async (lora, index) => lora.source.type === "local" ? {
3490
+ ...lora,
3491
+ source: {
3492
+ ...lora.source,
3493
+ path: await copyInput(lora.source.path, inputs.path, `LoRA-${index + 1}`, ".safetensors")
3494
+ }
3495
+ } : lora)) : void 0
3496
+ };
3497
+ },
3498
+ async remove(job) {
3499
+ await jobRoot(job.id).delete().catch(() => void 0);
3500
+ if (job.result?.uri) await files.file(pathFromUri(job.result.uri)).delete().catch(() => void 0);
3501
+ }
3502
+ };
3503
+ function dataFromJob(job) {
3041
3504
  return {
3042
- model,
3043
- path,
3044
- paths: fluxImageModelPaths(path, definition.manifest),
3045
- installed,
3046
- verified: installed && invalidFiles.length === 0 && manifestStat.type === "file",
3047
- bytesPresent,
3048
- totalBytes: definition.totalBytes,
3049
- missingFiles,
3050
- invalidFiles
3505
+ status: job.status,
3506
+ request: JSON.stringify(job.request),
3507
+ progress: encode(job.progress),
3508
+ result: encode(job.result),
3509
+ error: encode(job.error),
3510
+ attempt: job.attempt,
3511
+ startedAt: job.startedAt ?? "",
3512
+ completedAt: job.completedAt ?? ""
3051
3513
  };
3052
3514
  }
3053
- function tokenArray(value, name) {
3054
- const candidate = isRecord(value) && "data" in value ? value.data : value;
3055
- const values = Array.isArray(candidate) ? candidate : ArrayBuffer.isView(candidate) ? Array.from(candidate) : void 0;
3056
- if (!values) throw new AIError("invalid_message", `Tokenizer did not return ${name}`);
3057
- return values.map((token) => {
3058
- const number = typeof token === "bigint" ? Number(token) : token;
3059
- if (!Number.isInteger(number) || number < 0) throw new AIError("invalid_message", `${name} must contain token ids`);
3060
- return number;
3515
+ function jobFromRow(row) {
3516
+ return {
3517
+ id: row.id,
3518
+ kind: "image",
3519
+ status: row.data.status,
3520
+ request: decode(row.data.request),
3521
+ progress: decode(row.data.progress),
3522
+ result: decode(row.data.result),
3523
+ error: decode(row.data.error),
3524
+ attempt: row.data.attempt,
3525
+ createdAt: row.createdAt,
3526
+ updatedAt: row.updatedAt,
3527
+ startedAt: row.data.startedAt || void 0,
3528
+ completedAt: row.data.completedAt || void 0
3529
+ };
3530
+ }
3531
+ function encode(value) {
3532
+ return value === void 0 ? "" : JSON.stringify(value);
3533
+ }
3534
+ function decode(value) {
3535
+ return value ? JSON.parse(value) : void 0;
3536
+ }
3537
+ function normalizeRequest(options) {
3538
+ const runtimeOptions = options;
3539
+ for (const key of [
3540
+ "accessToken",
3541
+ "onModelProgress",
3542
+ "onProgress",
3543
+ "signal",
3544
+ "tokenizer"
3545
+ ]) if (runtimeOptions[key] !== void 0) throw new AIError("invalid_message", `${key} is not supported for persistent image jobs`);
3546
+ if (!options.prompt.trim()) throw new AIError("invalid_message", "Expected prompt");
3547
+ assertSerializable(options);
3548
+ return {
3549
+ ...options,
3550
+ model: typeof options.model === "string" ? options.model : options.model?.id,
3551
+ seed: options.seed ?? Math.floor(Math.random() * 4294967296)
3552
+ };
3553
+ }
3554
+ function assertSerializable(value, path = "options") {
3555
+ if (typeof value === "number" && !Number.isFinite(value)) throw new AIError("invalid_message", `${path} must be finite`);
3556
+ if (typeof value === "function" || typeof value === "symbol" || typeof value === "bigint") throw new AIError("invalid_message", `${path} must be serializable`);
3557
+ if (Array.isArray(value)) value.forEach((next, index) => {
3558
+ assertSerializable(next, `${path}[${index}]`);
3061
3559
  });
3560
+ else if (value && typeof value === "object") for (const [key, next] of Object.entries(value)) assertSerializable(next, `${path}.${key}`);
3062
3561
  }
3063
- async function createFluxTokenizer(path, manifest) {
3064
- const paths = fluxImageModelPaths(path, manifest);
3065
- const tokenizer = new Tokenizer_default(await files.file(paths.textEncoderPath, "tokenizer.json").json(), await files.file(paths.textEncoderPath, "tokenizer_config.json").json());
3066
- const padTokenId = 151643;
3067
- return ({ prompt, maxLength }) => {
3068
- const inputIds = tokenArray(tokenizer.encode(formatQwen3KleinPrompt(prompt)).ids, "inputIds").slice(0, maxLength);
3069
- const attentionMask = inputIds.map(() => 1);
3070
- while (inputIds.length < maxLength) {
3071
- inputIds.push(padTokenId);
3072
- attentionMask.push(0);
3073
- }
3074
- return {
3075
- inputIds,
3076
- attentionMask
3077
- };
3562
+ function serializedError(error) {
3563
+ const value = error instanceof Error ? error : new Error(String(error));
3564
+ const record = value;
3565
+ return {
3566
+ name: value.name,
3567
+ message: value.message,
3568
+ code: typeof record.code === "string" ? record.code : void 0,
3569
+ stage: typeof record.stage === "string" ? record.stage : void 0
3078
3570
  };
3079
3571
  }
3080
- function formatQwen3KleinPrompt(prompt) {
3081
- return [
3082
- "<|im_start|>user",
3083
- `${prompt.replaceAll("[IMG]", "")}<|im_end|>`,
3084
- "<|im_start|>assistant",
3085
- "<think>",
3086
- "",
3087
- "</think>",
3088
- ""
3089
- ].join("\n");
3572
+ function canceledError(message = "Image generation canceled") {
3573
+ return {
3574
+ name: "AIError",
3575
+ code: "generation_canceled",
3576
+ message
3577
+ };
3090
3578
  }
3091
- function assertPositiveInteger(value, name) {
3092
- if (!Number.isInteger(value) || value <= 0) throw new AIError("invalid_model", `${name} must be a positive integer`);
3579
+ function summaryFromJob(job) {
3580
+ return {
3581
+ id: job.id,
3582
+ kind: job.kind,
3583
+ status: job.status,
3584
+ prompt: job.request.prompt,
3585
+ progress: job.progress,
3586
+ attempt: job.attempt,
3587
+ createdAt: job.createdAt,
3588
+ updatedAt: job.updatedAt,
3589
+ startedAt: job.startedAt,
3590
+ completedAt: job.completedAt
3591
+ };
3093
3592
  }
3094
- function assertUnitInterval(value, name) {
3095
- if (!Number.isFinite(value) || value <= 0 || value > 1) throw new AIError("invalid_model", `${name} must be greater than 0 and at most 1`);
3593
+ function jobRoot(id) {
3594
+ return files.directory(files.paths.shared, "ImageJobs", currentAppStorageKey(), id);
3096
3595
  }
3097
- function filePathFromUri(value, name) {
3098
- const path = value.trim();
3099
- if (!path) throw new AIError("invalid_message", `${name} must not be empty`);
3100
- if (!path.startsWith("file://")) return path;
3596
+ async function copyInput(source, directory, name, fallbackExtension = ".png") {
3597
+ const path = pathFromUri(source);
3598
+ const destination = `${directory}/${name}${path.match(/\.[A-Za-z0-9]+$/)?.[0] ?? fallbackExtension}`;
3599
+ await nativeCopy(path, destination);
3600
+ return destination;
3601
+ }
3602
+ function pathFromUri(value) {
3603
+ if (!value.startsWith("file://")) return value;
3101
3604
  try {
3102
- return decodeURIComponent(new URL(path).pathname);
3103
- } catch (error) {
3104
- throw new AIError("invalid_message", `Invalid ${name} file URI`, error);
3605
+ return decodeURIComponent(new URL(value).pathname);
3606
+ } catch {
3607
+ return value.slice(7);
3105
3608
  }
3106
3609
  }
3107
- function assertTokenArray(value, name) {
3108
- if (value.length === 0) throw new AIError("invalid_message", `${name} must not be empty`);
3109
- for (const token of value) if (!Number.isInteger(token) || token < 0) throw new AIError("invalid_message", `${name} must contain token ids`);
3610
+ function now() {
3611
+ return (/* @__PURE__ */ new Date()).toISOString();
3110
3612
  }
3111
- function imageResult(value, model, fallbackMetadata) {
3112
- if (!isRecord(value) || typeof value.uri !== "string" || typeof value.width !== "number" || typeof value.height !== "number" || value.model !== model) throw new AIError("image_generation_failed", "Expected generated image URI");
3113
- const result = value;
3114
- const metadata = isRecord(result.metadata) ? result.metadata : {};
3115
- return {
3116
- uri: value.uri,
3117
- width: value.width,
3118
- height: value.height,
3119
- model,
3120
- metadata: {
3121
- ...fallbackMetadata,
3122
- model: metadata.model === model ? model : fallbackMetadata.model,
3123
- width: typeof metadata.width === "number" ? metadata.width : value.width,
3124
- height: typeof metadata.height === "number" ? metadata.height : value.height,
3125
- steps: typeof metadata.steps === "number" ? metadata.steps : fallbackMetadata.steps,
3126
- guidance: typeof metadata.guidance === "number" ? metadata.guidance : fallbackMetadata.guidance,
3127
- strength: typeof metadata.strength === "number" ? metadata.strength : fallbackMetadata.strength,
3128
- seed: typeof metadata.seed === "number" ? metadata.seed : fallbackMetadata.seed,
3129
- elapsedMs: typeof metadata.elapsedMs === "number" ? metadata.elapsedMs : fallbackMetadata.elapsedMs,
3130
- appliedLoRAs: Array.isArray(metadata.appliedLoRAs) ? metadata.appliedLoRAs.flatMap((item) => {
3131
- if (!isRecord(item) || typeof item.path !== "string") return [];
3132
- return [{
3133
- id: typeof item.id === "string" ? item.id : void 0,
3134
- path: item.path,
3135
- scale: typeof item.scale === "number" ? item.scale : 1
3136
- }];
3137
- }) : fallbackMetadata.appliedLoRAs
3613
+
3614
+ //#endregion
3615
+ //#region src/ai/image-models.ts
3616
+ const flux2Klein4B8BitAbliterated = {
3617
+ formatVersion: 1,
3618
+ model: "flux2-klein-4b-8bit-abliterated",
3619
+ directory: "flux2-klein-4b-8bit-abliterated",
3620
+ metadata: {
3621
+ displayName: "Flux.2 Klein 4B Abliterated",
3622
+ family: "flux2-klein",
3623
+ precision: "8-bit",
3624
+ estimatedMemoryGB: 12,
3625
+ quality: "high",
3626
+ speed: "fast",
3627
+ capabilities: [
3628
+ "text-to-image",
3629
+ "image-to-image",
3630
+ "inpainting",
3631
+ "outpainting",
3632
+ "references",
3633
+ "lora"
3634
+ ]
3635
+ },
3636
+ components: {
3637
+ textEncoder: {
3638
+ repo: "mlx-community/Josiefied-Qwen3-4B-abliterated-v1-8bit",
3639
+ revision: "main",
3640
+ path: "text-encoder",
3641
+ files: [
3642
+ "config.json",
3643
+ "tokenizer.json",
3644
+ "tokenizer_config.json",
3645
+ "*.safetensors",
3646
+ "*.safetensors.index.json"
3647
+ ]
3648
+ },
3649
+ transformer: {
3650
+ repo: "moxin-org/FLUX.2-klein-4B-8bit-mlx",
3651
+ revision: "main",
3652
+ path: "transformer",
3653
+ files: ["config.json", "quantized_8bit.safetensors"]
3654
+ },
3655
+ vae: {
3656
+ repo: "black-forest-labs/FLUX.2-klein-4B",
3657
+ revision: "main",
3658
+ path: "vae",
3659
+ files: [
3660
+ "config.json",
3661
+ "diffusion_pytorch_model.safetensors",
3662
+ "diffusion_pytorch_model.safetensors.index.json",
3663
+ "diffusion_pytorch_model-*.safetensors"
3664
+ ]
3138
3665
  }
3139
- };
3666
+ }
3667
+ };
3668
+ const ternaryBonsaiImage4B = {
3669
+ formatVersion: 1,
3670
+ model: "ternary-bonsai-image-4b",
3671
+ directory: "ternary-bonsai-image-4b",
3672
+ metadata: {
3673
+ displayName: "Ternary Bonsai Image 4B",
3674
+ family: "bonsai-image",
3675
+ precision: "2-bit",
3676
+ estimatedMemoryGB: 8,
3677
+ quality: "high",
3678
+ speed: "fast",
3679
+ capabilities: ["text-to-image"]
3680
+ },
3681
+ components: {
3682
+ textEncoder: {
3683
+ repo: "prism-ml/bonsai-image-ternary-4B-mlx-2bit",
3684
+ revision: "2c24c81b934a658ba5590cf39088ba929985b4a8",
3685
+ path: "text-encoder",
3686
+ files: [
3687
+ "text_encoder-mlx-4bit/config.json",
3688
+ "text_encoder-mlx-4bit/tokenizer.json",
3689
+ "text_encoder-mlx-4bit/tokenizer_config.json",
3690
+ "text_encoder-mlx-4bit/model.safetensors",
3691
+ "text_encoder-mlx-4bit/model.safetensors.index.json"
3692
+ ]
3693
+ },
3694
+ transformer: {
3695
+ repo: "prism-ml/bonsai-image-ternary-4B-mlx-2bit",
3696
+ revision: "2c24c81b934a658ba5590cf39088ba929985b4a8",
3697
+ path: "transformer",
3698
+ files: [
3699
+ "transformer-packed-mflux/config.json",
3700
+ "transformer-packed-mflux/diffusion_pytorch_model.safetensors",
3701
+ "transformer-packed-mflux/quantization_config.json"
3702
+ ]
3703
+ },
3704
+ vae: {
3705
+ repo: "prism-ml/bonsai-image-ternary-4B-mlx-2bit",
3706
+ revision: "2c24c81b934a658ba5590cf39088ba929985b4a8",
3707
+ path: "vae",
3708
+ files: ["vae/config.json", "vae/diffusion_pytorch_model.safetensors"]
3709
+ }
3710
+ }
3711
+ };
3712
+ const imageModelManifests = [flux2Klein4B8BitAbliterated, ternaryBonsaiImage4B];
3713
+ function imageModelManifest(model) {
3714
+ return imageModelManifests.find((manifest) => manifest.model === model);
3140
3715
  }
3141
- async function withImageStage(stage, operation) {
3142
- try {
3143
- return await operation();
3144
- } catch (error) {
3145
- if (error instanceof ImageGenerationError) throw error;
3146
- if (error instanceof AIError && error.code === "generation_canceled") throw error;
3147
- throw new ImageGenerationError(stage, error instanceof Error ? error.message : String(error), error);
3716
+ const flux2KleinModelFiles = [
3717
+ {
3718
+ repo: flux2Klein4B8BitAbliterated.components.textEncoder.repo,
3719
+ revision: flux2Klein4B8BitAbliterated.components.textEncoder.revision,
3720
+ source: "config.json",
3721
+ destination: "text-encoder/config.json",
3722
+ bytes: 937
3723
+ },
3724
+ {
3725
+ repo: flux2Klein4B8BitAbliterated.components.textEncoder.repo,
3726
+ revision: flux2Klein4B8BitAbliterated.components.textEncoder.revision,
3727
+ source: "tokenizer.json",
3728
+ destination: "text-encoder/tokenizer.json",
3729
+ bytes: 11422654
3730
+ },
3731
+ {
3732
+ repo: flux2Klein4B8BitAbliterated.components.textEncoder.repo,
3733
+ revision: flux2Klein4B8BitAbliterated.components.textEncoder.revision,
3734
+ source: "tokenizer_config.json",
3735
+ destination: "text-encoder/tokenizer_config.json",
3736
+ bytes: 9706
3737
+ },
3738
+ {
3739
+ repo: flux2Klein4B8BitAbliterated.components.textEncoder.repo,
3740
+ revision: flux2Klein4B8BitAbliterated.components.textEncoder.revision,
3741
+ source: "model.safetensors",
3742
+ destination: "text-encoder/model.safetensors",
3743
+ bytes: 4274158989
3744
+ },
3745
+ {
3746
+ repo: flux2Klein4B8BitAbliterated.components.textEncoder.repo,
3747
+ revision: flux2Klein4B8BitAbliterated.components.textEncoder.revision,
3748
+ source: "model.safetensors.index.json",
3749
+ destination: "text-encoder/model.safetensors.index.json",
3750
+ bytes: 63924
3751
+ },
3752
+ {
3753
+ repo: flux2Klein4B8BitAbliterated.components.transformer.repo,
3754
+ revision: flux2Klein4B8BitAbliterated.components.transformer.revision,
3755
+ source: "transformer/config.json",
3756
+ destination: "transformer/config.json",
3757
+ bytes: 541
3758
+ },
3759
+ {
3760
+ repo: flux2Klein4B8BitAbliterated.components.transformer.repo,
3761
+ revision: flux2Klein4B8BitAbliterated.components.transformer.revision,
3762
+ source: "transformer/quantized_8bit.safetensors",
3763
+ destination: "transformer/quantized_8bit.safetensors",
3764
+ bytes: 4360050983
3765
+ },
3766
+ {
3767
+ repo: flux2Klein4B8BitAbliterated.components.vae.repo,
3768
+ revision: flux2Klein4B8BitAbliterated.components.vae.revision,
3769
+ source: "vae/config.json",
3770
+ destination: "vae/config.json",
3771
+ bytes: 821
3772
+ },
3773
+ {
3774
+ repo: flux2Klein4B8BitAbliterated.components.vae.repo,
3775
+ revision: flux2Klein4B8BitAbliterated.components.vae.revision,
3776
+ source: "vae/diffusion_pytorch_model.safetensors",
3777
+ destination: "vae/diffusion_pytorch_model.safetensors",
3778
+ bytes: 168120878
3148
3779
  }
3780
+ ];
3781
+ const flux2KleinTotalBytes = flux2KleinModelFiles.reduce((total, file) => total + file.bytes, 0);
3782
+ const bonsaiRepo = ternaryBonsaiImage4B.components.textEncoder.repo;
3783
+ const bonsaiRevision = ternaryBonsaiImage4B.components.textEncoder.revision;
3784
+ const ternaryBonsaiImageModelFiles = [
3785
+ {
3786
+ repo: bonsaiRepo,
3787
+ revision: bonsaiRevision,
3788
+ source: "text_encoder-mlx-4bit/config.json",
3789
+ destination: "text-encoder/config.json",
3790
+ bytes: 937
3791
+ },
3792
+ {
3793
+ repo: bonsaiRepo,
3794
+ revision: bonsaiRevision,
3795
+ source: "text_encoder-mlx-4bit/tokenizer.json",
3796
+ destination: "text-encoder/tokenizer.json",
3797
+ bytes: 11422654
3798
+ },
3799
+ {
3800
+ repo: bonsaiRepo,
3801
+ revision: bonsaiRevision,
3802
+ source: "text_encoder-mlx-4bit/tokenizer_config.json",
3803
+ destination: "text-encoder/tokenizer_config.json",
3804
+ bytes: 9706
3805
+ },
3806
+ {
3807
+ repo: bonsaiRepo,
3808
+ revision: bonsaiRevision,
3809
+ source: "text_encoder-mlx-4bit/model.safetensors",
3810
+ destination: "text-encoder/model.safetensors",
3811
+ bytes: 2263022529
3812
+ },
3813
+ {
3814
+ repo: bonsaiRepo,
3815
+ revision: bonsaiRevision,
3816
+ source: "text_encoder-mlx-4bit/model.safetensors.index.json",
3817
+ destination: "text-encoder/model.safetensors.index.json",
3818
+ bytes: 63924
3819
+ },
3820
+ {
3821
+ repo: bonsaiRepo,
3822
+ revision: bonsaiRevision,
3823
+ source: "transformer-packed-mflux/config.json",
3824
+ destination: "transformer/config.json",
3825
+ bytes: 619
3826
+ },
3827
+ {
3828
+ repo: bonsaiRepo,
3829
+ revision: bonsaiRevision,
3830
+ source: "transformer-packed-mflux/diffusion_pytorch_model.safetensors",
3831
+ destination: "transformer/diffusion_pytorch_model.safetensors",
3832
+ bytes: 1425271472
3833
+ },
3834
+ {
3835
+ repo: bonsaiRepo,
3836
+ revision: bonsaiRevision,
3837
+ source: "transformer-packed-mflux/quantization_config.json",
3838
+ destination: "transformer/quantization_config.json",
3839
+ bytes: 5054
3840
+ },
3841
+ {
3842
+ repo: bonsaiRepo,
3843
+ revision: bonsaiRevision,
3844
+ source: "vae/config.json",
3845
+ destination: "vae/config.json",
3846
+ bytes: 821
3847
+ },
3848
+ {
3849
+ repo: bonsaiRepo,
3850
+ revision: bonsaiRevision,
3851
+ source: "vae/diffusion_pytorch_model.safetensors",
3852
+ destination: "vae/diffusion_pytorch_model.safetensors",
3853
+ bytes: 168120878
3854
+ }
3855
+ ];
3856
+ const ternaryBonsaiImageTotalBytes = ternaryBonsaiImageModelFiles.reduce((total, file) => total + file.bytes, 0);
3857
+ function joinModelPath(root, component) {
3858
+ return `${root.replace(/\/+$/, "")}/${component.replace(/^\/+/, "")}`;
3149
3859
  }
3150
- function imagegenProgress(value) {
3151
- const currentStep = value.currentStep;
3152
- const totalSteps = value.totalSteps;
3153
- if (typeof currentStep !== "number" || !Number.isFinite(currentStep) || typeof totalSteps !== "number" || !Number.isFinite(totalSteps) || totalSteps <= 0) return;
3860
+ function fluxImageModelPaths(path, manifest = flux2Klein4B8BitAbliterated) {
3154
3861
  return {
3155
- currentStep,
3156
- totalSteps,
3157
- fraction: Math.max(0, Math.min(1, currentStep / totalSteps))
3862
+ path,
3863
+ textEncoderPath: joinModelPath(path, manifest.components.textEncoder.path),
3864
+ transformerPath: joinModelPath(path, manifest.components.transformer.path),
3865
+ vaePath: joinModelPath(path, manifest.components.vae.path)
3158
3866
  };
3159
3867
  }
3160
- function throwIfAborted(signal) {
3161
- if (signal?.aborted) throw new AIError("generation_canceled", "Image generation canceled");
3162
- }
3163
- function nativeErrorStage(error) {
3164
- const stage = (error instanceof Error ? error.message : String(error)).match(/^\[(download|tokenize|encode|denoise|decode|write)]\s/)?.[1] ?? (isRecord(error) && typeof error.stage === "string" ? error.stage : isRecord(error) && isRecord(error.userInfo) && typeof error.userInfo.stage === "string" ? error.userInfo.stage : void 0);
3165
- return stage === "download" || stage === "tokenize" || stage === "encode" || stage === "denoise" || stage === "decode" || stage === "write" ? stage : void 0;
3868
+
3869
+ //#endregion
3870
+ //#region src/ai/image-schedule.ts
3871
+ function imageSigmaSchedule(schedules) {
3872
+ const configured = schedules.filter((schedule) => schedule !== void 0);
3873
+ if (configured.length === 0) return void 0;
3874
+ const first = configured[0];
3875
+ if (first.length === 0 || first.some((sigma, index) => !Number.isFinite(sigma) || sigma <= 0 || sigma > 1 || index > 0 && sigma >= first[index - 1])) throw new AIError("invalid_model", "LoRA sigmaSchedule must contain descending values greater than 0 and at most 1");
3876
+ if (configured.some((schedule) => schedule.length !== first.length || schedule.some((sigma, index) => sigma !== first[index]))) throw new AIError("invalid_model", "Selected LoRAs require conflicting sigma schedules");
3877
+ return [...first];
3166
3878
  }
3167
- function nativeErrorMessage(error) {
3168
- return (error instanceof Error ? error.message : String(error)).replace(/^\[(download|tokenize|encode|denoise|decode|write)]\s*/, "");
3879
+
3880
+ //#endregion
3881
+ //#region src/ai/image-upscale.ts
3882
+ function normalizeUpscaleScale(value) {
3883
+ const scale = value ?? 2;
3884
+ if (!Number.isFinite(scale) || scale <= 1 || scale > 4) throw new AIError("invalid_model", "Upscale scale must be greater than 1 and at most 4");
3885
+ return scale;
3169
3886
  }
3170
- async function prepareImageModel(options = {}) {
3171
- const definition = imageModelDefinition(options.model ?? flux2Klein4B8BitAbliterated.model);
3172
- return prepareImageModelAtPath(definition, options, options.directory ? files.directory(options.directory, definition.manifest.directory).path : modelCacheRoot(definition.manifest).path);
3887
+
3888
+ //#endregion
3889
+ //#region src/ai/image.ts
3890
+ function imageModelId(model) {
3891
+ return typeof model === "string" ? model : model.id;
3173
3892
  }
3174
- async function prepareImageModelAtPath(definition, options, path) {
3175
- const model = definition.manifest.model;
3176
- const root = files.directory(path);
3177
- await root.create({ recursive: true });
3178
- const headers = options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : void 0;
3179
- const total = definition.files.length;
3180
- const bytesByFile = /* @__PURE__ */ new Map();
3181
- const emitProgress = (progress) => {
3182
- const file = definition.files.find((candidate) => candidate.destination === progress.file);
3183
- const bytesWritten = file ? Math.min(progress.bytesWritten, file.bytes) : progress.bytesWritten;
3184
- bytesByFile.set(progress.file, bytesWritten);
3185
- const modelBytesWritten = Array.from(bytesByFile.values()).reduce((sum, bytes) => sum + bytes, 0);
3186
- options.onProgress?.({
3187
- ...progress,
3188
- bytesWritten,
3189
- modelBytesWritten,
3190
- totalModelBytes: definition.totalBytes,
3191
- modelFraction: modelBytesWritten / definition.totalBytes
3192
- });
3893
+ function imageModelDefinition(model) {
3894
+ const id = imageModelId(model);
3895
+ if (id === flux2Klein4B8BitAbliterated.model) return {
3896
+ manifest: flux2Klein4B8BitAbliterated,
3897
+ files: flux2KleinModelFiles,
3898
+ totalBytes: flux2KleinTotalBytes
3193
3899
  };
3194
- const missingFiles = [];
3195
- for (const [index, file] of definition.files.entries()) {
3196
- const stat = await files.file(root.path, file.destination).stat();
3197
- if (stat.type === "file" && stat.size === file.bytes) emitProgress({
3198
- model,
3199
- file: file.destination,
3200
- index: index + 1,
3201
- total,
3202
- bytesWritten: file.bytes,
3203
- totalBytes: file.bytes,
3204
- fraction: 1
3205
- });
3206
- else missingFiles.push({
3207
- file,
3208
- index: index + 1
3209
- });
3210
- }
3211
- await runConcurrent(missingFiles, downloadConcurrency(options.concurrency), async ({ file, index }) => {
3212
- await ensureModelFile({
3213
- model,
3214
- path: root.path,
3215
- file,
3216
- headers,
3217
- index,
3218
- total,
3219
- onProgress: emitProgress
3220
- });
3221
- });
3222
- await writePreparedManifest(root.path, definition.manifest);
3223
- return {
3224
- model,
3225
- ...fluxImageModelPaths(root.path, definition.manifest),
3226
- tokenizer: await createFluxTokenizer(root.path, definition.manifest)
3900
+ if (id === ternaryBonsaiImage4B.model) return {
3901
+ manifest: ternaryBonsaiImage4B,
3902
+ files: ternaryBonsaiImageModelFiles,
3903
+ totalBytes: ternaryBonsaiImageTotalBytes
3227
3904
  };
3905
+ throw new AIError("invalid_model", `Unsupported image model: ${id}`);
3228
3906
  }
3229
- async function verifyImageModel(options = {}) {
3230
- const definition = imageModelDefinition(options.model ?? flux2Klein4B8BitAbliterated.model);
3231
- return imageModelState(definition.manifest.model, modelPathFromOptions(definition, options.path));
3232
- }
3233
- async function listImageModels(options = {}) {
3234
- return [...await Promise.all([flux2Klein4B8BitAbliterated.model, ternaryBonsaiImage4B.model].map((model) => {
3235
- const definition = imageModelDefinition(model);
3236
- return imageModelState(model, options.directory ? files.directory(options.directory, definition.manifest.directory).path : modelPathFromOptions(definition, void 0));
3237
- }))];
3907
+ function modelCacheRoot(manifest) {
3908
+ return files.directory(files.paths.models, manifest.directory);
3238
3909
  }
3239
- async function deleteImageModel(options = {}) {
3240
- const definition = imageModelDefinition(options.model ?? flux2Klein4B8BitAbliterated.model);
3241
- await files.directory(modelPathFromOptions(definition, options.path)).delete({ recursive: true });
3910
+ function assertImageModel(model) {
3911
+ imageModelDefinition(model);
3242
3912
  }
3243
- async function imageMemoryTelemetry() {
3244
- const value = await bridge().imageMemoryTelemetry?.();
3245
- if (!value) throw new AIError("image_generation_failed", "Image service is unavailable");
3246
- return value;
3913
+ function modelPathFromOptions(definition, path) {
3914
+ return path ?? modelCacheRoot(definition.manifest).path;
3247
3915
  }
3248
- async function unloadImageModel() {
3249
- return await bridge().unloadImageModel?.() ?? false;
3916
+ function downloadConcurrency(value) {
3917
+ if (value === void 0) return 2;
3918
+ if (!Number.isInteger(value)) throw new AIError("invalid_model", "concurrency must be an integer");
3919
+ return Math.min(4, Math.max(1, value));
3250
3920
  }
3251
- async function upscaleImage(options) {
3252
- throwIfAborted(options.signal);
3253
- const scale = normalizeUpscaleScale(options.scale);
3254
- const value = await bridge().upscaleImage?.({
3255
- imagePath: filePathFromUri(options.image, "image"),
3256
- scale
3921
+ async function runConcurrent(items, concurrency, worker) {
3922
+ let nextIndex = 0;
3923
+ const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
3924
+ while (nextIndex < items.length) {
3925
+ const item = items[nextIndex];
3926
+ nextIndex += 1;
3927
+ await worker(item);
3928
+ }
3257
3929
  });
3258
- throwIfAborted(options.signal);
3259
- if (!value || typeof value.uri !== "string" || !Number.isInteger(value.width) || !Number.isInteger(value.height) || value.scale !== scale) throw new AIError("image_generation_failed", "Native image upscaling returned an invalid result");
3260
- return value;
3930
+ await Promise.all(workers);
3261
3931
  }
3262
- async function prepareImageLoRA(lora, options = {}) {
3263
- assertLoRADefinition(lora);
3264
- const resolvedDefinition = await resolveHuggingFaceLoRA(lora, options);
3265
- const id = safeCacheName(lora.id, "lora.id");
3266
- const scale = assertLoRAScale(lora.scale ?? lora.metadata?.recommendedScale);
3267
- if (resolvedDefinition.source.type === "local") {
3268
- const path = filePathFromUri(resolvedDefinition.source.path, `lora ${id}`);
3269
- const stat$1 = await files.file(path).stat();
3270
- if (stat$1.type !== "file") throw new AIError("invalid_model", `Missing LoRA file: ${path}`);
3271
- if (!hasSafetensorsHeader(stat$1.size)) throw new AIError("invalid_model", `Invalid LoRA safetensors file: ${path}`);
3272
- return {
3273
- id: lora.id,
3274
- description: lora.description,
3275
- path,
3276
- uri: stat$1.uri,
3277
- scale,
3278
- source: resolvedDefinition.source,
3279
- metadata: lora.metadata
3280
- };
3281
- }
3282
- const url = loraUrl(resolvedDefinition);
3283
- if (!url) throw new AIError("invalid_model", `Unsupported LoRA source: ${lora.id}`);
3284
- const root = imageLoRARoot().directory(id);
3285
- await root.create({ recursive: true });
3286
- const destination = root.file(safeCacheName(sourceFileName(resolvedDefinition), "lora filename"));
3287
- const expectedBytes = loraExpectedBytes(resolvedDefinition);
3288
- const stat = await destination.stat();
3289
- if (stat.type !== "file" || !hasSafetensorsHeader(stat.size) || expectedBytes !== void 0 && stat.size !== expectedBytes) await destination.download(url, {
3290
- headers: loraHeaders(resolvedDefinition, options.accessToken),
3291
- expectedBytes,
3292
- atomic: true,
3293
- resume: true,
3294
- signal: options.signal,
3295
- onProgress(progress) {
3296
- options.onProgress?.({
3297
- lora: lora.id,
3298
- file: destination.path,
3299
- bytesWritten: progress.bytesWritten,
3300
- totalBytes: progress.totalBytes,
3301
- fraction: progress.fraction
3302
- });
3303
- }
3304
- }).result;
3305
- await root.file("manifest.json").write(JSON.stringify({
3306
- formatVersion: 1,
3307
- id: lora.id,
3308
- file: destination.path.split("/").pop(),
3309
- source: resolvedDefinition.source,
3310
- metadata: lora.metadata
3311
- }, null, 2));
3312
- const preparedStat = await destination.stat();
3313
- if (preparedStat.type !== "file" || !hasSafetensorsHeader(preparedStat.size)) throw new AIError("invalid_model", `Invalid LoRA safetensors file: ${destination.path}`);
3314
- return {
3315
- id: lora.id,
3316
- description: lora.description,
3317
- path: destination.path,
3318
- uri: preparedStat.uri,
3319
- scale,
3320
- source: resolvedDefinition.source,
3321
- metadata: lora.metadata
3322
- };
3932
+ function hfResolveUrl(repo, revision, path) {
3933
+ const encodedRepo = repo.split("/").map(encodeURIComponent).join("/");
3934
+ const encodedPath = path.split("/").map(encodeURIComponent).join("/");
3935
+ return `https://huggingface.co/${encodedRepo}/resolve/${encodeURIComponent(revision)}/${encodedPath}`;
3323
3936
  }
3324
- async function verifyImageLoRA(lora) {
3325
- assertLoRADefinition(lora);
3326
- const scale = assertLoRAScale(lora.scale ?? lora.metadata?.recommendedScale);
3327
- let resolvedDefinition = lora;
3328
- if (lora.source.type === "huggingface" && !lora.source.path) {
3329
- const manifestFile = imageLoRARoot().directory(safeCacheName(lora.id, "lora.id")).file("manifest.json");
3330
- if ((await manifestFile.stat()).type === "file") {
3331
- const manifest = await manifestFile.json();
3332
- if (isRecord(manifest) && isRecord(manifest.source) && manifest.source.type === "huggingface" && manifest.source.repo === lora.source.repo && (manifest.source.revision ?? "main") === (lora.source.revision ?? "main") && typeof manifest.source.path === "string") resolvedDefinition = {
3333
- ...lora,
3334
- source: {
3335
- ...lora.source,
3336
- path: manifest.source.path,
3337
- revision: typeof manifest.source.revision === "string" ? manifest.source.revision : lora.source.revision,
3338
- bytes: typeof manifest.source.bytes === "number" ? manifest.source.bytes : lora.source.bytes
3339
- }
3340
- };
3341
- }
3342
- }
3343
- const file = resolvedDefinition.source.type === "local" ? files.file(filePathFromUri(resolvedDefinition.source.path, `lora ${lora.id}`)) : cachedLoRAFile(resolvedDefinition);
3344
- const stat = await file.stat();
3345
- const expectedBytes = loraExpectedBytes(resolvedDefinition);
3346
- const installed = stat.type === "file";
3347
- const verified = installed && hasSafetensorsHeader(stat.size) && (expectedBytes === void 0 || stat.size === expectedBytes);
3937
+ const imageDimensionMultiple = 16;
3938
+ const minimumImageDimension = 64;
3939
+ const defaultImageLongSide = 1152;
3940
+ const aspectRatioValues = {
3941
+ "1:1": [1, 1],
3942
+ "16:9": [16, 9],
3943
+ "9:16": [9, 16],
3944
+ "4:3": [4, 3],
3945
+ "3:2": [3, 2],
3946
+ "2:3": [2, 3],
3947
+ "21:9": [21, 9]
3948
+ };
3949
+ function normalizedDimension(value) {
3950
+ return Math.max(minimumImageDimension, Math.floor(value / imageDimensionMultiple) * imageDimensionMultiple);
3951
+ }
3952
+ function normalizeImageSize(size, maxLongSide = defaultImageLongSide) {
3953
+ if (!Number.isFinite(size.width) || size.width <= 0) throw new AIError("invalid_model", "size.width must be positive");
3954
+ if (!Number.isFinite(size.height) || size.height <= 0) throw new AIError("invalid_model", "size.height must be positive");
3955
+ if (maxLongSide !== false && (!Number.isInteger(maxLongSide) || maxLongSide < minimumImageDimension)) throw new AIError("invalid_model", `maxLongSide must be false or an integer of at least ${minimumImageDimension}`);
3956
+ const scale = maxLongSide === false ? 1 : Math.min(1, maxLongSide / Math.max(size.width, size.height));
3348
3957
  return {
3349
- id: lora.id,
3350
- description: lora.description,
3351
- path: file.path,
3352
- uri: stat.uri,
3353
- scale,
3354
- source: resolvedDefinition.source,
3355
- metadata: lora.metadata,
3356
- installed,
3357
- verified,
3358
- size: stat.size
3958
+ width: normalizedDimension(size.width * scale),
3959
+ height: normalizedDimension(size.height * scale)
3359
3960
  };
3360
3961
  }
3361
- async function listImageLoRAs(loras) {
3362
- return Promise.all(loras.map((lora) => verifyImageLoRA(lora)));
3962
+ function imageSizeForPreset(aspectRatio, maxLongSide = defaultImageLongSide) {
3963
+ const ratio = aspectRatioValues[aspectRatio];
3964
+ if (!ratio) throw new AIError("invalid_model", `Unsupported image aspect ratio: ${aspectRatio}`);
3965
+ assertPositiveInteger(maxLongSide, "maxLongSide");
3966
+ const [widthRatio, heightRatio] = ratio;
3967
+ return normalizeImageSize(widthRatio >= heightRatio ? {
3968
+ width: maxLongSide,
3969
+ height: maxLongSide * heightRatio / widthRatio
3970
+ } : {
3971
+ width: maxLongSide * widthRatio / heightRatio,
3972
+ height: maxLongSide
3973
+ }, maxLongSide);
3974
+ }
3975
+ function imageLoRARoot() {
3976
+ return files.directory(files.paths.models, "image-loras");
3363
3977
  }
3364
- async function deleteImageLoRA(lora) {
3365
- const id = safeCacheName(typeof lora === "string" ? lora : lora.id, "lora.id");
3366
- await imageLoRARoot().directory(id).delete({ recursive: true });
3978
+ function safeCacheName(value, name) {
3979
+ const trimmed = value.trim();
3980
+ if (!trimmed) throw new AIError("invalid_model", `${name} must not be empty`);
3981
+ return trimmed.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
3367
3982
  }
3368
- async function prepareSelectedImageLoRAs(loras, model, options = {}) {
3369
- const prepared = [];
3370
- for (const lora of loras) {
3371
- assertLoRADefinition(lora);
3372
- assertLoRACompatibility(lora, model);
3373
- prepared.push(await prepareImageLoRA(lora, options));
3374
- }
3375
- return prepared;
3983
+ function sourceFileName(lora) {
3984
+ if (lora.source.type === "local") return lora.source.path.split("/").pop() || `${lora.id}.safetensors`;
3985
+ if (lora.source.type === "url") return lora.source.filename ?? lora.source.url.split("/").pop() ?? `${lora.id}.safetensors`;
3986
+ return lora.source.path?.split("/").pop() || `${lora.id}.safetensors`;
3376
3987
  }
3377
- async function generateImage(options) {
3378
- throwIfAborted(options.signal);
3379
- const definition = imageModelDefinition(options.model ?? flux2Klein4B8BitAbliterated.model);
3380
- const model = definition.manifest.model;
3381
- const prompt = options.prompt.trim();
3382
- if (!prompt) throw new AIError("invalid_message", "Expected prompt");
3383
- const presetSize = options.aspectRatio ? imageSizeForPreset(options.aspectRatio) : void 0;
3384
- const requestedSize = normalizeImageSize({
3385
- width: options.width ?? presetSize?.width ?? 1024,
3386
- height: options.height ?? presetSize?.height ?? 1024
3387
- }, false);
3388
- const width = requestedSize.width;
3389
- const height = requestedSize.height;
3390
- const outpaintSize = options.outpaint ? normalizeImageSize({
3391
- width: options.outpaint.width,
3392
- height: options.outpaint.height
3393
- }, false) : void 0;
3394
- if (options.outpaint && (outpaintSize?.width !== options.outpaint.width || outpaintSize?.height !== options.outpaint.height)) throw new AIError("invalid_model", "outpaint width and height must be multiples of 16");
3395
- const steps = options.steps ?? 4;
3396
- const guidance = options.guidance ?? 1;
3397
- const seed = options.seed ?? Math.floor(Math.random() * 4294967296);
3398
- const sourceImagePath = options.image ? filePathFromUri(options.image, "image") : void 0;
3399
- const maskImagePath = options.mask ? filePathFromUri(options.mask, "mask") : void 0;
3400
- const referenceImagePaths = (options.references ?? []).map((reference, index) => filePathFromUri(reference, `references[${index}]`));
3401
- const isImageConditioned = Boolean(sourceImagePath) || referenceImagePaths.length > 0;
3402
- const strength = options.strength ?? (isImageConditioned ? .8 : void 0);
3403
- if (maskImagePath && !sourceImagePath) throw new AIError("invalid_message", "mask requires image");
3404
- if (options.maskMode !== void 0 && options.maskMode !== "paint" && options.maskMode !== "preserve") throw new AIError("invalid_model", "maskMode must be paint or preserve");
3405
- if (options.outpaint && !sourceImagePath) throw new AIError("invalid_message", "outpaint requires image");
3406
- if (options.outpaint) {
3407
- assertPositiveInteger(options.outpaint.width, "outpaint.width");
3408
- assertPositiveInteger(options.outpaint.height, "outpaint.height");
3409
- const rect = options.outpaint.sourceRect;
3410
- if (!rect) throw new AIError("invalid_model", "outpaint.sourceRect is required");
3411
- assertPositiveInteger(rect.width, "outpaint.sourceRect.width");
3412
- assertPositiveInteger(rect.height, "outpaint.sourceRect.height");
3413
- if (!Number.isInteger(rect.x) || !Number.isInteger(rect.y)) throw new AIError("invalid_model", "outpaint.sourceRect x and y must be integers");
3414
- const canvasWidth = outpaintSize?.width ?? options.outpaint.width;
3415
- const canvasHeight = outpaintSize?.height ?? options.outpaint.height;
3416
- if (!(rect.x < canvasWidth && rect.y < canvasHeight && rect.x + rect.width > 0 && rect.y + rect.height > 0)) throw new AIError("invalid_model", "outpaint.sourceRect must intersect the canvas");
3417
- if (!options.outpaint.autoCrop && (rect.x < 0 || rect.y < 0 || rect.x + rect.width > canvasWidth || rect.y + rect.height > canvasHeight)) throw new AIError("invalid_model", "outpaint.sourceRect must fit within the outpaint canvas");
3418
- }
3419
- if (options.resizeMode !== void 0 && options.resizeMode !== "stretch" && options.resizeMode !== "fit" && options.resizeMode !== "crop") throw new AIError("invalid_model", "resizeMode must be stretch, fit, or crop");
3420
- if (options.maxInputLongSide !== void 0 && options.maxInputLongSide !== false && (!Number.isInteger(options.maxInputLongSide) || options.maxInputLongSide < 64)) throw new AIError("invalid_model", "maxInputLongSide must be false or an integer of at least 64");
3421
- assertPositiveInteger(width, "width");
3422
- assertPositiveInteger(height, "height");
3423
- assertPositiveInteger(steps, "steps");
3424
- if (seed !== void 0 && (!Number.isInteger(seed) || seed < 0)) throw new AIError("invalid_model", "seed must be a non-negative integer");
3425
- if (!Number.isFinite(guidance) || guidance <= 0) throw new AIError("invalid_model", "guidance must be a positive number");
3426
- if (referenceImagePaths.length > 3) throw new AIError("invalid_model", "references must contain at most 3 images");
3427
- if (options.referenceInfluences !== void 0) {
3428
- if (options.referenceInfluences.length !== referenceImagePaths.length) throw new AIError("invalid_model", "referenceInfluences must match references length");
3429
- for (const [index, influence] of options.referenceInfluences.entries()) if (!Number.isFinite(influence) || influence < 0) throw new AIError("invalid_model", `referenceInfluences[${index}] must be a non-negative number`);
3988
+ function assertLoRAScale(scale, name = "lora.scale") {
3989
+ const value = scale ?? 1;
3990
+ if (!Number.isFinite(value) || value <= 0) throw new AIError("invalid_model", `${name} must be a positive number`);
3991
+ return value;
3992
+ }
3993
+ function assertLoRADefinition(lora) {
3994
+ safeCacheName(lora.id, "lora.id");
3995
+ assertLoRAScale(lora.scale ?? lora.metadata?.recommendedScale);
3996
+ imageSigmaSchedule([lora.metadata?.sigmaSchedule]);
3997
+ if (lora.metadata?.baseModel !== void 0) assertImageModel(lora.metadata.baseModel);
3998
+ if (lora.metadata?.precision !== void 0 && ![
3999
+ "float16",
4000
+ "bfloat16",
4001
+ "float32"
4002
+ ].includes(lora.metadata.precision)) throw new AIError("invalid_model", "lora.metadata.precision is unsupported");
4003
+ }
4004
+ function assertLoRACompatibility(lora, model) {
4005
+ if (lora.metadata?.baseModel && lora.metadata.baseModel !== model) throw new AIError("invalid_model", `LoRA ${lora.id} targets ${lora.metadata.baseModel}, not ${model}`);
4006
+ }
4007
+ const commonLoRAFileNames = [
4008
+ "pytorch_lora_weights.safetensors",
4009
+ "adapter_model.safetensors",
4010
+ "lora.safetensors",
4011
+ "model.safetensors"
4012
+ ];
4013
+ async function resolveHuggingFaceLoRA(lora, options) {
4014
+ if (lora.source.type !== "huggingface" || lora.source.path) return lora;
4015
+ const revision = lora.source.revision ?? "main";
4016
+ const manifestFile = imageLoRARoot().directory(safeCacheName(lora.id, "lora.id")).file("manifest.json");
4017
+ if ((await manifestFile.stat()).type === "file") {
4018
+ const manifest = await manifestFile.json();
4019
+ if (isRecord(manifest) && isRecord(manifest.source) && manifest.source.type === "huggingface" && manifest.source.repo === lora.source.repo && (manifest.source.revision ?? "main") === revision && typeof manifest.source.path === "string") return {
4020
+ ...lora,
4021
+ source: {
4022
+ ...lora.source,
4023
+ revision,
4024
+ path: manifest.source.path,
4025
+ bytes: lora.source.bytes ?? (typeof manifest.source.bytes === "number" ? manifest.source.bytes : void 0)
4026
+ }
4027
+ };
3430
4028
  }
3431
- if (strength !== void 0) assertUnitInterval(strength, "strength");
3432
- const selectedLoRAs = options.loras?.length ? await withImageStage("download", () => prepareSelectedImageLoRAs(options.loras ?? [], model, {
3433
- accessToken: options.accessToken,
4029
+ const encodedRepo = lora.source.repo.split("/").map(encodeURIComponent).join("/");
4030
+ const response = await fetch(`https://huggingface.co/api/models/${encodedRepo}/revision/${encodeURIComponent(revision)}`, {
4031
+ headers: options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : void 0,
3434
4032
  signal: options.signal
3435
- })) : [];
3436
- const sigmaSchedule = imageSigmaSchedule(selectedLoRAs.map((lora) => lora.metadata?.sigmaSchedule));
3437
- if (sigmaSchedule && options.steps !== void 0 && options.steps !== sigmaSchedule.length) throw new AIError("invalid_model", `steps must equal the LoRA sigma schedule length (${sigmaSchedule.length})`);
3438
- const generationSteps = sigmaSchedule?.length ?? steps;
3439
- const prepared = options.path && options.tokenizer ? void 0 : await withImageStage("download", () => prepareImageModelAtPath(definition, {
3440
- model,
3441
- accessToken: options.accessToken,
3442
- concurrency: options.concurrency,
3443
- onProgress: options.onModelProgress
3444
- }, options.path ?? modelCacheRoot(definition.manifest).path));
3445
- throwIfAborted(options.signal);
3446
- const tokenizer = options.tokenizer ?? prepared?.tokenizer;
3447
- const modelPath = options.path ?? prepared?.path;
3448
- if (!tokenizer || !modelPath) throw new AIError("invalid_model", "Expected image model path and tokenizer");
3449
- const tokenized = await withImageStage("tokenize", () => tokenizer({
3450
- prompt,
3451
- maxLength: 512
3452
- }));
3453
- throwIfAborted(options.signal);
3454
- await withImageStage("tokenize", () => {
3455
- assertTokenArray(tokenized.inputIds, "inputIds");
3456
- assertTokenArray(tokenized.attentionMask, "attentionMask");
3457
- if (tokenized.inputIds.length !== tokenized.attentionMask.length) throw new AIError("invalid_message", "inputIds and attentionMask must have the same length");
3458
4033
  });
3459
- const paths = fluxImageModelPaths(modelPath, definition.manifest);
3460
- const request = {
3461
- model,
3462
- prompt,
3463
- sourceImagePath,
3464
- maskImagePath,
3465
- maskMode: options.maskMode,
3466
- outpaintWidth: outpaintSize?.width,
3467
- outpaintHeight: outpaintSize?.height,
3468
- outpaintSourceX: options.outpaint?.sourceRect.x,
3469
- outpaintSourceY: options.outpaint?.sourceRect.y,
3470
- outpaintSourceWidth: options.outpaint?.sourceRect.width,
3471
- outpaintSourceHeight: options.outpaint?.sourceRect.height,
3472
- outpaintAutoCrop: options.outpaint?.autoCrop,
3473
- resizeMode: options.resizeMode,
3474
- maxInputLongSide: options.maxInputLongSide === false ? 0 : options.maxInputLongSide ?? defaultImageLongSide,
3475
- referenceImagePaths,
3476
- referenceInfluences: options.referenceInfluences,
3477
- loraPaths: selectedLoRAs.map((lora) => lora.path),
3478
- loraScales: selectedLoRAs.map((lora) => lora.scale),
3479
- loraIds: selectedLoRAs.map((lora) => lora.id),
3480
- sigmaSchedule,
3481
- width,
3482
- height,
3483
- steps: generationSteps,
3484
- guidance,
3485
- strength,
3486
- seed,
3487
- inputIds: tokenized.inputIds,
3488
- attentionMask: tokenized.attentionMask,
3489
- modelRoot: paths.path,
3490
- textEncoderPath: paths.textEncoderPath,
3491
- transformerPath: paths.transformerPath,
3492
- vaePath: paths.vaePath
3493
- };
3494
- const fallbackMetadata = {
3495
- model,
3496
- width: outpaintSize?.width ?? width,
3497
- height: outpaintSize?.height ?? height,
3498
- steps: generationSteps,
3499
- guidance,
3500
- strength,
3501
- seed,
3502
- appliedLoRAs: selectedLoRAs.map((lora) => ({
3503
- id: lora.id,
3504
- path: lora.path,
3505
- scale: lora.scale
3506
- })),
3507
- sigmaSchedule
3508
- };
3509
- try {
3510
- const native = bridge();
3511
- const cancelNative = () => {
3512
- native.cancelImagegen?.();
3513
- };
3514
- const subscription = options.onProgress ? native.addListener?.("imagegenProgress", (event) => {
3515
- const progress = imagegenProgress(event);
3516
- if (progress) options.onProgress?.(progress);
3517
- }) : void 0;
3518
- try {
3519
- options.signal?.addEventListener("abort", cancelNative, { once: true });
3520
- throwIfAborted(options.signal);
3521
- const value = await native.generateImage?.(request);
3522
- throwIfAborted(options.signal);
3523
- return imageResult(value, model, fallbackMetadata);
3524
- } finally {
3525
- subscription?.remove();
3526
- options.signal?.removeEventListener("abort", cancelNative);
3527
- }
3528
- } catch (error) {
3529
- if (error instanceof ImageGenerationError) throw error;
3530
- if (error instanceof AIError) throw error;
3531
- if (options.signal?.aborted) throw new AIError("generation_canceled", "Image generation canceled", error);
3532
- const mapped = mapNativeError(error);
3533
- if (mapped.code === "generation_failed" || mapped.code === "image_generation_failed") throw new ImageGenerationError(nativeErrorStage(error) ?? "denoise", nativeErrorMessage(error), error);
3534
- throw mapped;
3535
- }
3536
- }
3537
- async function generateImages(options) {
3538
- const { count,...imageOptions } = options;
3539
- const results = [];
3540
- for (const seed of batchImageSeeds(count, options.seed)) {
3541
- throwIfAborted(options.signal);
3542
- results.push(await generateImage({
3543
- ...imageOptions,
3544
- seed
3545
- }));
4034
+ if (!response.ok) throw new AIError("invalid_model", `Unable to inspect Hugging Face LoRA ${lora.source.repo}: ${response.status}`);
4035
+ const value = await response.json();
4036
+ const siblings = isRecord(value) && Array.isArray(value.siblings) ? value.siblings.flatMap((item) => {
4037
+ if (!isRecord(item) || typeof item.rfilename !== "string") return [];
4038
+ return [{
4039
+ path: item.rfilename,
4040
+ bytes: typeof item.size === "number" ? item.size : void 0
4041
+ }];
4042
+ }) : [];
4043
+ const common = commonLoRAFileNames.map((name) => siblings.find((file) => file.path === name)).find(Boolean);
4044
+ const safetensors = siblings.filter((file) => file.path.endsWith(".safetensors"));
4045
+ const selected = common ?? (safetensors.length === 1 ? safetensors[0] : void 0);
4046
+ if (!selected) {
4047
+ const candidates = safetensors.map((file) => file.path).join(", ");
4048
+ throw new AIError("invalid_model", candidates ? `Multiple LoRA weights found for ${lora.id}; set source.path to one of: ${candidates}` : `No .safetensors LoRA weight found for ${lora.id}`);
3546
4049
  }
3547
- return results;
3548
- }
3549
- const imageGenerationQueueKey = Symbol.for("bleam.ai.imageGenerationQueue");
3550
- function imageGenerationQueue() {
3551
- const scope = globalThis;
3552
- const queue = scope[imageGenerationQueueKey] ?? new ImageGenerationQueue(generateImage);
3553
- queue.setExecutor(generateImage);
3554
- scope[imageGenerationQueueKey] = queue;
3555
- return queue;
4050
+ return {
4051
+ ...lora,
4052
+ source: {
4053
+ ...lora.source,
4054
+ revision,
4055
+ path: selected.path,
4056
+ bytes: lora.source.bytes ?? selected.bytes
4057
+ }
4058
+ };
3556
4059
  }
3557
- function scheduleImageGeneration(options) {
3558
- return imageGenerationQueue().schedule(options);
4060
+ function loraUrl(lora) {
4061
+ if (lora.source.type === "url") return lora.source.url;
4062
+ if (lora.source.type === "huggingface") {
4063
+ if (!lora.source.path) return void 0;
4064
+ return hfResolveUrl(lora.source.repo, lora.source.revision ?? "main", lora.source.path);
4065
+ }
3559
4066
  }
3560
- function getImageGenerationJob(id) {
3561
- return imageGenerationQueue().get(id);
4067
+ function loraExpectedBytes(lora) {
4068
+ return lora.source.type === "local" ? void 0 : lora.source.bytes;
3562
4069
  }
3563
- function listImageGenerationJobs() {
3564
- return imageGenerationQueue().list();
4070
+ function hasSafetensorsHeader(size) {
4071
+ return size !== void 0 && size > 8;
3565
4072
  }
3566
-
3567
- //#endregion
3568
- //#region src/ai/image-composer.tsx
3569
- const defaultImageSize = defaultImageLongSide;
3570
- const defaultStepCount = 4;
3571
- const minOutpaintScale = .35;
3572
- const maxOutpaintScale = .95;
3573
- function roundImageDimension(value) {
3574
- return normalizeImageSize({
3575
- width: value,
3576
- height: value
3577
- }, false).width;
4073
+ function loraHeaders(lora, accessToken) {
4074
+ return lora.source.type === "huggingface" && accessToken ? { Authorization: `Bearer ${accessToken}` } : void 0;
3578
4075
  }
3579
- function imageSizeForAspectRatio(size, maxSide = defaultImageSize) {
3580
- if (size.width <= 0 || size.height <= 0) return {
3581
- width: maxSide,
3582
- height: maxSide
3583
- };
3584
- const aspect = size.width / size.height;
3585
- return normalizeImageSize({
3586
- width: aspect >= 1 ? maxSide : maxSide * aspect,
3587
- height: aspect >= 1 ? maxSide / aspect : maxSide
3588
- }, maxSide);
4076
+ function cachedLoRAFile(lora) {
4077
+ const id = safeCacheName(lora.id, "lora.id");
4078
+ return imageLoRARoot().directory(id).file(safeCacheName(sourceFileName(lora), "lora filename"));
3589
4079
  }
3590
- function roundedImageSize(size) {
3591
- return normalizeImageSize(size);
4080
+ async function ensureModelFile(input) {
4081
+ const destination = files.file(input.path, input.file.destination);
4082
+ const stat = await destination.stat();
4083
+ if (stat.type === "file" && stat.size === input.file.bytes) {
4084
+ input.onProgress?.({
4085
+ model: input.model,
4086
+ file: input.file.destination,
4087
+ index: input.index,
4088
+ total: input.total,
4089
+ bytesWritten: input.file.bytes,
4090
+ totalBytes: input.file.bytes,
4091
+ fraction: 1
4092
+ });
4093
+ return;
4094
+ }
4095
+ await destination.download(hfResolveUrl(input.file.repo, input.file.revision, input.file.source), {
4096
+ headers: input.headers,
4097
+ expectedBytes: input.file.bytes,
4098
+ atomic: true,
4099
+ resume: true,
4100
+ onProgress(progress) {
4101
+ input.onProgress?.({
4102
+ model: input.model,
4103
+ file: input.file.destination,
4104
+ index: input.index,
4105
+ total: input.total,
4106
+ ...progress
4107
+ });
4108
+ }
4109
+ }).result;
3592
4110
  }
3593
- function clamp(value, min$1, max) {
3594
- return Math.min(max, Math.max(min$1, value));
4111
+ async function writePreparedManifest(path, manifest) {
4112
+ await files.file(path, "manifest.json").write(JSON.stringify(manifest, null, 2));
3595
4113
  }
3596
- function clampOutpaintRect(rect) {
3597
- const width = Math.min(defaultImageSize, Math.max(1, Math.round(rect.width)));
3598
- const height = Math.min(defaultImageSize, Math.max(1, Math.round(rect.height)));
4114
+ async function imageModelState(model, path) {
4115
+ const definition = imageModelDefinition(model);
4116
+ let bytesPresent = 0;
4117
+ const missingFiles = [];
4118
+ const invalidFiles = [];
4119
+ for (const file of definition.files) {
4120
+ const stat = await files.file(path, file.destination).stat();
4121
+ if (stat.type !== "file") {
4122
+ missingFiles.push(file.destination);
4123
+ continue;
4124
+ }
4125
+ bytesPresent += Math.min(stat.size ?? 0, file.bytes);
4126
+ if (stat.size !== file.bytes) invalidFiles.push(file.destination);
4127
+ }
4128
+ const manifestStat = await files.file(path, "manifest.json").stat();
4129
+ if (manifestStat.type !== "file") missingFiles.push("manifest.json");
4130
+ const installed = missingFiles.length === 0;
3599
4131
  return {
3600
- x: Math.round(clamp(rect.x, 0, defaultImageSize - width)),
3601
- y: Math.round(clamp(rect.y, 0, defaultImageSize - height)),
3602
- width,
3603
- height
4132
+ model,
4133
+ path,
4134
+ paths: fluxImageModelPaths(path, definition.manifest),
4135
+ installed,
4136
+ verified: installed && invalidFiles.length === 0 && manifestStat.type === "file",
4137
+ bytesPresent,
4138
+ totalBytes: definition.totalBytes,
4139
+ missingFiles,
4140
+ invalidFiles
3604
4141
  };
3605
4142
  }
3606
- function rectForSourceScale(sourceSize, scale, center) {
3607
- const aspect = sourceSize.width / sourceSize.height;
3608
- const longSide = defaultImageSize * clamp(scale, minOutpaintScale, maxOutpaintScale);
3609
- const width = aspect >= 1 ? longSide : longSide * aspect;
3610
- const height = aspect >= 1 ? longSide / aspect : longSide;
3611
- const nextCenter = center ?? {
3612
- x: defaultImageSize / 2,
3613
- y: defaultImageSize / 2
3614
- };
3615
- return clampOutpaintRect({
3616
- x: nextCenter.x - width / 2,
3617
- y: nextCenter.y - height / 2,
3618
- width,
3619
- height
4143
+ function tokenArray(value, name) {
4144
+ const candidate = isRecord(value) && "data" in value ? value.data : value;
4145
+ const values = Array.isArray(candidate) ? candidate : ArrayBuffer.isView(candidate) ? Array.from(candidate) : void 0;
4146
+ if (!values) throw new AIError("invalid_message", `Tokenizer did not return ${name}`);
4147
+ return values.map((token) => {
4148
+ const number$1 = typeof token === "bigint" ? Number(token) : token;
4149
+ if (!Number.isInteger(number$1) || number$1 < 0) throw new AIError("invalid_message", `${name} must contain token ids`);
4150
+ return number$1;
3620
4151
  });
3621
4152
  }
3622
- function initialOutpaintRect(sourceSize) {
3623
- return rectForSourceScale(sourceSize, .72);
3624
- }
3625
- function buildImageGenerationRequest(input, options = {}) {
3626
- const base = {
3627
- prompt: input.prompt,
3628
- mode: input.mode,
3629
- steps: defaultStepCount,
3630
- guidance: 1,
3631
- ...options
3632
- };
3633
- if (input.mode === "text") {
3634
- const references = (input.refs ?? []).map((image) => image.path);
3635
- return {
3636
- ...base,
3637
- references: references.length > 0 ? references : void 0,
3638
- referenceInfluences: references.length > 0 ? references.map(() => 1) : void 0,
3639
- strength: references.length > 0 ? 1 : void 0,
3640
- width: defaultImageSize,
3641
- height: defaultImageSize
3642
- };
3643
- }
3644
- if (input.mode === "subject") {
3645
- if (!input.subject) throw new Error("Subject mode requires a subject image");
3646
- const refs = input.refs ?? [];
3647
- const references = [input.subject, ...refs].map((image) => image.path);
3648
- const size = imageSizeForAspectRatio(input.subject.size);
3649
- return {
3650
- ...base,
3651
- references,
3652
- referenceInfluences: references.map(() => 1),
3653
- strength: 1,
3654
- width: size.width,
3655
- height: size.height
3656
- };
3657
- }
3658
- if (input.mode === "edit") {
3659
- if (!input.source) throw new Error("Edit requires a source image");
3660
- const references = (input.refs ?? []).map((image) => image.path);
3661
- const size = roundedImageSize(input.source.size);
4153
+ async function createFluxTokenizer(path, manifest) {
4154
+ const paths = fluxImageModelPaths(path, manifest);
4155
+ const tokenizer = new Tokenizer_default(await files.file(paths.textEncoderPath, "tokenizer.json").json(), await files.file(paths.textEncoderPath, "tokenizer_config.json").json());
4156
+ const padTokenId = 151643;
4157
+ return ({ prompt, maxLength }) => {
4158
+ const inputIds = tokenArray(tokenizer.encode(formatQwen3KleinPrompt(prompt)).ids, "inputIds").slice(0, maxLength);
4159
+ const attentionMask = inputIds.map(() => 1);
4160
+ while (inputIds.length < maxLength) {
4161
+ inputIds.push(padTokenId);
4162
+ attentionMask.push(0);
4163
+ }
3662
4164
  return {
3663
- ...base,
3664
- image: input.source.path,
3665
- references: references.length > 0 ? references : void 0,
3666
- referenceInfluences: references.length > 0 ? references.map(() => 1) : void 0,
3667
- strength: references.length > 0 ? 1 : .35,
3668
- width: size.width,
3669
- height: size.height
4165
+ inputIds,
4166
+ attentionMask
3670
4167
  };
3671
- }
3672
- if (!input.source) throw new Error("Outpaint requires a source image");
3673
- if (!input.rect) throw new Error("Outpaint requires a source placement");
3674
- return {
3675
- ...base,
3676
- image: input.source.path,
3677
- outpaint: {
3678
- width: defaultImageSize,
3679
- height: defaultImageSize,
3680
- sourceRect: input.rect,
3681
- autoCrop: true
3682
- },
3683
- strength: .8,
3684
- width: defaultImageSize,
3685
- height: defaultImageSize
3686
4168
  };
3687
4169
  }
3688
- function useImageComposer(modeOrOptions, options = {}) {
3689
- if (typeof modeOrOptions !== "string") return useImageComposerController(modeOrOptions ?? {});
3690
- const mode = modeOrOptions;
3691
- if (mode === "text") return useTextComposer(options);
3692
- if (mode === "subject") return useSubjectComposer(options);
3693
- if (mode === "edit") return useEditComposer(options);
3694
- return useOutpaintComposer(options);
3695
- }
3696
- function useImageComposerController(options) {
3697
- const [mode, setMode] = useAtom(useComposerAtom(options.initialMode ?? "text"));
3698
- const text = useTextComposer(options);
3699
- const subject = useSubjectComposer(options);
3700
- const edit = useEditComposer(options);
3701
- const outpaint = useOutpaintComposer(options);
3702
- const active = mode === "text" ? text : mode === "subject" ? subject : mode === "edit" ? edit : outpaint;
3703
- const error = active.error ?? text.error ?? subject.error ?? edit.error ?? outpaint.error;
4170
+ function formatQwen3KleinPrompt(prompt) {
4171
+ return [
4172
+ "<|im_start|>user",
4173
+ `${prompt.replaceAll("[IMG]", "")}<|im_end|>`,
4174
+ "<|im_start|>assistant",
4175
+ "<think>",
4176
+ "",
4177
+ "</think>",
4178
+ ""
4179
+ ].join("\n");
4180
+ }
4181
+ function assertPositiveInteger(value, name) {
4182
+ if (!Number.isInteger(value) || value <= 0) throw new AIError("invalid_model", `${name} must be a positive integer`);
4183
+ }
4184
+ function assertUnitInterval(value, name) {
4185
+ if (!Number.isFinite(value) || value <= 0 || value > 1) throw new AIError("invalid_model", `${name} must be greater than 0 and at most 1`);
4186
+ }
4187
+ function filePathFromUri(value, name) {
4188
+ const path = value.trim();
4189
+ if (!path) throw new AIError("invalid_message", `${name} must not be empty`);
4190
+ if (!path.startsWith("file://")) return path;
4191
+ try {
4192
+ return decodeURIComponent(new URL(path).pathname);
4193
+ } catch (error) {
4194
+ throw new AIError("invalid_message", `Invalid ${name} file URI`, error);
4195
+ }
4196
+ }
4197
+ function assertTokenArray(value, name) {
4198
+ if (value.length === 0) throw new AIError("invalid_message", `${name} must not be empty`);
4199
+ for (const token of value) if (!Number.isInteger(token) || token < 0) throw new AIError("invalid_message", `${name} must contain token ids`);
4200
+ }
4201
+ function imageResult(value, model, fallbackMetadata) {
4202
+ if (!isRecord(value) || typeof value.uri !== "string" || typeof value.width !== "number" || typeof value.height !== "number" || value.model !== model) throw new AIError("image_generation_failed", "Expected generated image URI");
4203
+ const result = value;
4204
+ const metadata = isRecord(result.metadata) ? result.metadata : {};
3704
4205
  return {
3705
- mode,
3706
- setMode,
3707
- active,
3708
- text,
3709
- subject,
3710
- edit,
3711
- outpaint,
3712
- isPicking: text.isPicking || subject.isPicking || edit.isPicking || outpaint.isPicking,
3713
- error,
3714
- request: (prompt) => active.request(prompt),
3715
- clear() {
3716
- text.clear();
3717
- subject.clear();
3718
- edit.clear();
3719
- outpaint.clear();
4206
+ uri: value.uri,
4207
+ width: value.width,
4208
+ height: value.height,
4209
+ model,
4210
+ metadata: {
4211
+ ...fallbackMetadata,
4212
+ model: metadata.model === model ? model : fallbackMetadata.model,
4213
+ width: typeof metadata.width === "number" ? metadata.width : value.width,
4214
+ height: typeof metadata.height === "number" ? metadata.height : value.height,
4215
+ steps: typeof metadata.steps === "number" ? metadata.steps : fallbackMetadata.steps,
4216
+ guidance: typeof metadata.guidance === "number" ? metadata.guidance : fallbackMetadata.guidance,
4217
+ strength: typeof metadata.strength === "number" ? metadata.strength : fallbackMetadata.strength,
4218
+ seed: typeof metadata.seed === "number" ? metadata.seed : fallbackMetadata.seed,
4219
+ elapsedMs: typeof metadata.elapsedMs === "number" ? metadata.elapsedMs : fallbackMetadata.elapsedMs,
4220
+ appliedLoRAs: Array.isArray(metadata.appliedLoRAs) ? metadata.appliedLoRAs.flatMap((item) => {
4221
+ if (!isRecord(item) || typeof item.path !== "string") return [];
4222
+ return [{
4223
+ id: typeof item.id === "string" ? item.id : void 0,
4224
+ path: item.path,
4225
+ scale: typeof item.scale === "number" ? item.scale : 1
4226
+ }];
4227
+ }) : fallbackMetadata.appliedLoRAs
3720
4228
  }
3721
4229
  };
3722
4230
  }
3723
- function useTextComposer(options) {
3724
- const store = useComposerAtom({
3725
- refs: [],
3726
- isPicking: false,
3727
- error: null
3728
- });
3729
- const [state, setState] = useAtom(store);
3730
- const maxRefs = options.maxRefs ?? 3;
3731
- async function pickRefs() {
3732
- setState((current) => ({
3733
- ...current,
3734
- isPicking: true,
3735
- error: null
3736
- }));
3737
- try {
3738
- const refs = [...store.get().refs, ...await pickImages(options.inputRoot)].slice(0, maxRefs);
3739
- setState((current) => ({
3740
- ...current,
3741
- refs,
3742
- isPicking: false
3743
- }));
3744
- } catch (error) {
3745
- setState((current) => ({
3746
- ...current,
3747
- error: errorFromUnknown(error),
3748
- isPicking: false
3749
- }));
3750
- }
4231
+ async function withImageStage(stage, operation) {
4232
+ try {
4233
+ return await operation();
4234
+ } catch (error) {
4235
+ if (error instanceof ImageGenerationError) throw error;
4236
+ if (error instanceof AIError && error.code === "generation_canceled") throw error;
4237
+ throw new ImageGenerationError(stage, error instanceof Error ? error.message : String(error), error);
3751
4238
  }
3752
- return {
3753
- mode: "text",
3754
- ...state,
3755
- pickRefs,
3756
- removeRef: (index) => setState((current) => removeRefFromState(current, index)),
3757
- request: (prompt) => ({
3758
- mode: "text",
3759
- prompt,
3760
- refs: store.get().refs
3761
- }),
3762
- clear: () => setState({
3763
- refs: [],
3764
- isPicking: false,
3765
- error: null
3766
- })
3767
- };
3768
4239
  }
3769
- function useSubjectComposer(options) {
3770
- const store = useComposerAtom({
3771
- subject: null,
3772
- refs: [],
3773
- isPicking: false,
3774
- error: null
3775
- });
3776
- const [state, setState] = useAtom(store);
3777
- const maxRefs = options.maxRefs ?? 2;
3778
- async function pickSubject() {
3779
- setState((current) => ({
3780
- ...current,
3781
- isPicking: true,
3782
- error: null
3783
- }));
3784
- try {
3785
- const subject = await pickOneImage(options.inputRoot);
3786
- setState((current) => ({
3787
- ...current,
3788
- subject: subject ?? current.subject,
3789
- isPicking: false
3790
- }));
3791
- } catch (error) {
3792
- setState((current) => ({
3793
- ...current,
3794
- error: errorFromUnknown(error),
3795
- isPicking: false
3796
- }));
3797
- }
3798
- }
3799
- async function pickRefs() {
3800
- setState((current) => ({
3801
- ...current,
3802
- isPicking: true,
3803
- error: null
3804
- }));
3805
- try {
3806
- const refs = [...store.get().refs, ...await pickImages(options.inputRoot)].slice(0, maxRefs);
3807
- setState((current) => ({
3808
- ...current,
3809
- refs,
3810
- isPicking: false
3811
- }));
3812
- } catch (error) {
3813
- setState((current) => ({
3814
- ...current,
3815
- error: errorFromUnknown(error),
3816
- isPicking: false
3817
- }));
3818
- }
3819
- }
4240
+ function imagegenProgress(value) {
4241
+ const currentStep = value.currentStep;
4242
+ const totalSteps = value.totalSteps;
4243
+ if (typeof currentStep !== "number" || !Number.isFinite(currentStep) || typeof totalSteps !== "number" || !Number.isFinite(totalSteps) || totalSteps <= 0) return;
3820
4244
  return {
3821
- mode: "subject",
3822
- ...state,
3823
- pickSubject,
3824
- removeSubject: () => setState((current) => ({
3825
- ...current,
3826
- subject: null
3827
- })),
3828
- pickRefs,
3829
- removeRef: (index) => setState((current) => removeRefFromState(current, index)),
3830
- request: (prompt) => {
3831
- const current = store.get();
3832
- return {
3833
- mode: "subject",
3834
- prompt,
3835
- subject: current.subject,
3836
- refs: current.refs
3837
- };
3838
- },
3839
- clear: () => setState({
3840
- subject: null,
3841
- refs: [],
3842
- isPicking: false,
3843
- error: null
3844
- })
4245
+ currentStep,
4246
+ totalSteps,
4247
+ fraction: Math.max(0, Math.min(1, currentStep / totalSteps))
3845
4248
  };
3846
4249
  }
3847
- function useEditComposer(options) {
3848
- const store = useComposerAtom({
3849
- source: null,
3850
- refs: [],
3851
- isPicking: false,
3852
- error: null
3853
- });
3854
- const [state, setState] = useAtom(store);
3855
- const maxRefs = options.maxRefs ?? 3;
3856
- async function pickSource() {
3857
- setState((current) => ({
3858
- ...current,
3859
- isPicking: true,
3860
- error: null
3861
- }));
3862
- try {
3863
- const source = await pickOneImage(options.inputRoot);
3864
- setState((current) => ({
3865
- ...current,
3866
- source: source ?? current.source,
3867
- isPicking: false
3868
- }));
3869
- } catch (error) {
3870
- setState((current) => ({
3871
- ...current,
3872
- error: errorFromUnknown(error),
3873
- isPicking: false
3874
- }));
3875
- }
3876
- }
3877
- async function pickRefs() {
3878
- setState((current) => ({
3879
- ...current,
3880
- isPicking: true,
3881
- error: null
3882
- }));
3883
- try {
3884
- const refs = [...store.get().refs, ...await pickImages(options.inputRoot)].slice(0, maxRefs);
3885
- setState((current) => ({
3886
- ...current,
3887
- refs,
3888
- isPicking: false
3889
- }));
3890
- } catch (error) {
3891
- setState((current) => ({
3892
- ...current,
3893
- error: errorFromUnknown(error),
3894
- isPicking: false
3895
- }));
3896
- }
4250
+ function throwIfAborted(signal) {
4251
+ if (signal?.aborted) throw new AIError("generation_canceled", "Image generation canceled");
4252
+ }
4253
+ function nativeErrorStage(error) {
4254
+ const stage = (error instanceof Error ? error.message : String(error)).match(/^\[(download|tokenize|encode|denoise|decode|write)]\s/)?.[1] ?? (isRecord(error) && typeof error.stage === "string" ? error.stage : isRecord(error) && isRecord(error.userInfo) && typeof error.userInfo.stage === "string" ? error.userInfo.stage : void 0);
4255
+ return stage === "download" || stage === "tokenize" || stage === "encode" || stage === "denoise" || stage === "decode" || stage === "write" ? stage : void 0;
4256
+ }
4257
+ function nativeErrorMessage(error) {
4258
+ return (error instanceof Error ? error.message : String(error)).replace(/^\[(download|tokenize|encode|denoise|decode|write)]\s*/, "");
4259
+ }
4260
+ async function prepareImageModel(options = {}) {
4261
+ const definition = imageModelDefinition(options.model ?? flux2Klein4B8BitAbliterated.model);
4262
+ return prepareImageModelAtPath(definition, options, options.directory ? files.directory(options.directory, definition.manifest.directory).path : modelCacheRoot(definition.manifest).path);
4263
+ }
4264
+ async function prepareImageModelAtPath(definition, options, path) {
4265
+ const model = definition.manifest.model;
4266
+ const root = files.directory(path);
4267
+ await root.create({ recursive: true });
4268
+ const headers = options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : void 0;
4269
+ const total = definition.files.length;
4270
+ const bytesByFile = /* @__PURE__ */ new Map();
4271
+ const emitProgress = (progress) => {
4272
+ const file = definition.files.find((candidate) => candidate.destination === progress.file);
4273
+ const bytesWritten = file ? Math.min(progress.bytesWritten, file.bytes) : progress.bytesWritten;
4274
+ bytesByFile.set(progress.file, bytesWritten);
4275
+ const modelBytesWritten = Array.from(bytesByFile.values()).reduce((sum, bytes) => sum + bytes, 0);
4276
+ options.onProgress?.({
4277
+ ...progress,
4278
+ bytesWritten,
4279
+ modelBytesWritten,
4280
+ totalModelBytes: definition.totalBytes,
4281
+ modelFraction: modelBytesWritten / definition.totalBytes
4282
+ });
4283
+ };
4284
+ const missingFiles = [];
4285
+ for (const [index, file] of definition.files.entries()) {
4286
+ const stat = await files.file(root.path, file.destination).stat();
4287
+ if (stat.type === "file" && stat.size === file.bytes) emitProgress({
4288
+ model,
4289
+ file: file.destination,
4290
+ index: index + 1,
4291
+ total,
4292
+ bytesWritten: file.bytes,
4293
+ totalBytes: file.bytes,
4294
+ fraction: 1
4295
+ });
4296
+ else missingFiles.push({
4297
+ file,
4298
+ index: index + 1
4299
+ });
3897
4300
  }
4301
+ await runConcurrent(missingFiles, downloadConcurrency(options.concurrency), async ({ file, index }) => {
4302
+ await ensureModelFile({
4303
+ model,
4304
+ path: root.path,
4305
+ file,
4306
+ headers,
4307
+ index,
4308
+ total,
4309
+ onProgress: emitProgress
4310
+ });
4311
+ });
4312
+ await writePreparedManifest(root.path, definition.manifest);
3898
4313
  return {
3899
- mode: "edit",
3900
- ...state,
3901
- pickSource,
3902
- removeSource: () => setState((current) => ({
3903
- ...current,
3904
- source: null
3905
- })),
3906
- pickRefs,
3907
- removeRef: (index) => setState((current) => removeRefFromState(current, index)),
3908
- request: (prompt) => {
3909
- const current = store.get();
3910
- return {
3911
- mode: "edit",
3912
- prompt,
3913
- source: current.source,
3914
- refs: current.refs
3915
- };
3916
- },
3917
- clear: () => setState({
3918
- source: null,
3919
- refs: [],
3920
- isPicking: false,
3921
- error: null
3922
- })
4314
+ model,
4315
+ ...fluxImageModelPaths(root.path, definition.manifest),
4316
+ tokenizer: await createFluxTokenizer(root.path, definition.manifest)
3923
4317
  };
3924
4318
  }
3925
- function useOutpaintComposer(options) {
3926
- const store = useComposerAtom({
3927
- source: null,
3928
- rect: null,
3929
- isPicking: false,
3930
- error: null
4319
+ async function verifyImageModel(options = {}) {
4320
+ const definition = imageModelDefinition(options.model ?? flux2Klein4B8BitAbliterated.model);
4321
+ return imageModelState(definition.manifest.model, modelPathFromOptions(definition, options.path));
4322
+ }
4323
+ async function listImageModels(options = {}) {
4324
+ return [...await Promise.all([flux2Klein4B8BitAbliterated.model, ternaryBonsaiImage4B.model].map((model) => {
4325
+ const definition = imageModelDefinition(model);
4326
+ return imageModelState(model, options.directory ? files.directory(options.directory, definition.manifest.directory).path : modelPathFromOptions(definition, void 0));
4327
+ }))];
4328
+ }
4329
+ async function deleteImageModel(options = {}) {
4330
+ const definition = imageModelDefinition(options.model ?? flux2Klein4B8BitAbliterated.model);
4331
+ await files.directory(modelPathFromOptions(definition, options.path)).delete({ recursive: true });
4332
+ }
4333
+ async function imageMemoryTelemetry() {
4334
+ const value = await bridge().imageMemoryTelemetry?.();
4335
+ if (!value) throw new AIError("image_generation_failed", "Image service is unavailable");
4336
+ return value;
4337
+ }
4338
+ async function unloadImageModel() {
4339
+ return await bridge().unloadImageModel?.() ?? false;
4340
+ }
4341
+ async function upscaleImage(options) {
4342
+ throwIfAborted(options.signal);
4343
+ const scale = normalizeUpscaleScale(options.scale);
4344
+ const value = await bridge().upscaleImage?.({
4345
+ imagePath: filePathFromUri(options.image, "image"),
4346
+ scale
3931
4347
  });
3932
- const [state, setState] = useAtom(store);
3933
- async function pickSource() {
3934
- setState((current) => ({
3935
- ...current,
3936
- isPicking: true,
3937
- error: null
3938
- }));
3939
- try {
3940
- const source = await pickOneImage(options.inputRoot);
3941
- setState((current) => ({
3942
- ...current,
3943
- source: source ?? current.source,
3944
- rect: source ? initialOutpaintRect(source.size) : current.rect,
3945
- isPicking: false
3946
- }));
3947
- } catch (error) {
3948
- setState((current) => ({
3949
- ...current,
3950
- error: errorFromUnknown(error),
3951
- isPicking: false
3952
- }));
3953
- }
3954
- }
3955
- return {
3956
- mode: "outpaint",
3957
- ...state,
3958
- pickSource,
3959
- removeSource: () => setState((current) => ({
3960
- ...current,
3961
- source: null,
3962
- rect: null
3963
- })),
3964
- setRect: (rect) => setState((current) => ({
3965
- ...current,
3966
- rect
3967
- })),
3968
- request: (prompt) => {
3969
- const current = store.get();
3970
- return {
3971
- mode: "outpaint",
3972
- prompt,
3973
- source: current.source,
3974
- rect: current.rect
3975
- };
3976
- },
3977
- clear: () => setState({
3978
- source: null,
3979
- rect: null,
3980
- isPicking: false,
3981
- error: null
3982
- })
3983
- };
4348
+ throwIfAborted(options.signal);
4349
+ if (!value || typeof value.uri !== "string" || !Number.isInteger(value.width) || !Number.isInteger(value.height) || value.scale !== scale) throw new AIError("image_generation_failed", "Native image upscaling returned an invalid result");
4350
+ return value;
3984
4351
  }
3985
- function useImageGeneration() {
3986
- const [state, setState] = useAtom(useComposerAtom({
3987
- imageUri: null,
3988
- result: null,
3989
- progress: 0,
3990
- status: "",
3991
- isGenerating: false,
3992
- error: null
3993
- }));
3994
- const abortControllerRef = useStableRef(null);
3995
- async function run(input, options = {}) {
3996
- if (abortControllerRef.current) return null;
3997
- const abortController = new AbortController();
3998
- abortControllerRef.current = abortController;
3999
- setState((current) => ({
4000
- ...current,
4001
- imageUri: null,
4002
- result: null,
4003
- progress: 0,
4004
- status: "Generating...",
4005
- isGenerating: true,
4006
- error: null
4007
- }));
4008
- try {
4009
- const result = await generateImage(buildImageGenerationRequest(input, {
4010
- ...options,
4011
- signal: abortController.signal,
4012
- onModelProgress(progress) {
4013
- setState((current) => ({
4014
- ...current,
4015
- progress: progress.modelFraction >= 1 ? .15 : progress.modelFraction * .15,
4016
- status: progress.modelFraction >= 1 ? "Generating..." : modelProgressStatus(progress)
4017
- }));
4018
- },
4019
- onProgress(progress) {
4020
- setState((current) => ({
4021
- ...current,
4022
- progress: .15 + progress.currentStep / progress.totalSteps * .85,
4023
- status: `Step ${progress.currentStep}/${progress.totalSteps}`
4024
- }));
4025
- }
4026
- }));
4027
- setState((current) => ({
4028
- ...current,
4029
- imageUri: result.uri,
4030
- result,
4031
- progress: 1,
4032
- status: `${result.metadata.width}×${result.metadata.height} • ${result.metadata.steps} steps`,
4033
- isGenerating: false
4034
- }));
4035
- return result;
4036
- } catch (error) {
4037
- setState((current) => ({
4038
- ...current,
4039
- status: error instanceof Error ? error.message : String(error),
4040
- error: errorFromUnknown(error),
4041
- isGenerating: false
4042
- }));
4043
- return null;
4044
- } finally {
4045
- if (abortControllerRef.current === abortController) abortControllerRef.current = null;
4046
- }
4047
- }
4048
- function cancel() {
4049
- setState((current) => ({
4050
- ...current,
4051
- status: "Canceling..."
4052
- }));
4053
- abortControllerRef.current?.abort();
4054
- }
4055
- function clear() {
4056
- setState({
4057
- imageUri: null,
4058
- result: null,
4059
- progress: 0,
4060
- status: "",
4061
- isGenerating: false,
4062
- error: null
4063
- });
4352
+ async function prepareImageLoRA(lora, options = {}) {
4353
+ assertLoRADefinition(lora);
4354
+ const resolvedDefinition = await resolveHuggingFaceLoRA(lora, options);
4355
+ const id = safeCacheName(lora.id, "lora.id");
4356
+ const scale = assertLoRAScale(lora.scale ?? lora.metadata?.recommendedScale);
4357
+ if (resolvedDefinition.source.type === "local") {
4358
+ const path = filePathFromUri(resolvedDefinition.source.path, `lora ${id}`);
4359
+ const stat$1 = await files.file(path).stat();
4360
+ if (stat$1.type !== "file") throw new AIError("invalid_model", `Missing LoRA file: ${path}`);
4361
+ if (!hasSafetensorsHeader(stat$1.size)) throw new AIError("invalid_model", `Invalid LoRA safetensors file: ${path}`);
4362
+ return {
4363
+ id: lora.id,
4364
+ description: lora.description,
4365
+ path,
4366
+ uri: stat$1.uri,
4367
+ scale,
4368
+ source: resolvedDefinition.source,
4369
+ metadata: lora.metadata
4370
+ };
4064
4371
  }
4372
+ const url = loraUrl(resolvedDefinition);
4373
+ if (!url) throw new AIError("invalid_model", `Unsupported LoRA source: ${lora.id}`);
4374
+ const root = imageLoRARoot().directory(id);
4375
+ await root.create({ recursive: true });
4376
+ const destination = root.file(safeCacheName(sourceFileName(resolvedDefinition), "lora filename"));
4377
+ const expectedBytes = loraExpectedBytes(resolvedDefinition);
4378
+ const stat = await destination.stat();
4379
+ if (stat.type !== "file" || !hasSafetensorsHeader(stat.size) || expectedBytes !== void 0 && stat.size !== expectedBytes) await destination.download(url, {
4380
+ headers: loraHeaders(resolvedDefinition, options.accessToken),
4381
+ expectedBytes,
4382
+ atomic: true,
4383
+ resume: true,
4384
+ signal: options.signal,
4385
+ onProgress(progress) {
4386
+ options.onProgress?.({
4387
+ lora: lora.id,
4388
+ file: destination.path,
4389
+ bytesWritten: progress.bytesWritten,
4390
+ totalBytes: progress.totalBytes,
4391
+ fraction: progress.fraction
4392
+ });
4393
+ }
4394
+ }).result;
4395
+ await root.file("manifest.json").write(JSON.stringify({
4396
+ formatVersion: 1,
4397
+ id: lora.id,
4398
+ file: destination.path.split("/").pop(),
4399
+ source: resolvedDefinition.source,
4400
+ metadata: lora.metadata
4401
+ }, null, 2));
4402
+ const preparedStat = await destination.stat();
4403
+ if (preparedStat.type !== "file" || !hasSafetensorsHeader(preparedStat.size)) throw new AIError("invalid_model", `Invalid LoRA safetensors file: ${destination.path}`);
4065
4404
  return {
4066
- ...state,
4067
- run,
4068
- cancel,
4069
- clear
4405
+ id: lora.id,
4406
+ description: lora.description,
4407
+ path: destination.path,
4408
+ uri: preparedStat.uri,
4409
+ scale,
4410
+ source: resolvedDefinition.source,
4411
+ metadata: lora.metadata
4070
4412
  };
4071
4413
  }
4072
- function useImageModel() {
4073
- const [state, setState] = useAtom(useComposerAtom({
4074
- checking: false,
4075
- state: null,
4076
- error: null
4077
- }));
4078
- async function check() {
4079
- setState((current) => ({
4080
- ...current,
4081
- checking: true,
4082
- error: null
4083
- }));
4084
- try {
4085
- const [modelState] = await listImageModels();
4086
- setState({
4087
- checking: false,
4088
- state: modelState ?? null,
4089
- error: null
4090
- });
4091
- return modelState ?? null;
4092
- } catch (error) {
4093
- setState((current) => ({
4094
- ...current,
4095
- checking: false,
4096
- error: errorFromUnknown(error)
4097
- }));
4098
- return null;
4414
+ async function verifyImageLoRA(lora) {
4415
+ assertLoRADefinition(lora);
4416
+ const scale = assertLoRAScale(lora.scale ?? lora.metadata?.recommendedScale);
4417
+ let resolvedDefinition = lora;
4418
+ if (lora.source.type === "huggingface" && !lora.source.path) {
4419
+ const manifestFile = imageLoRARoot().directory(safeCacheName(lora.id, "lora.id")).file("manifest.json");
4420
+ if ((await manifestFile.stat()).type === "file") {
4421
+ const manifest = await manifestFile.json();
4422
+ if (isRecord(manifest) && isRecord(manifest.source) && manifest.source.type === "huggingface" && manifest.source.repo === lora.source.repo && (manifest.source.revision ?? "main") === (lora.source.revision ?? "main") && typeof manifest.source.path === "string") resolvedDefinition = {
4423
+ ...lora,
4424
+ source: {
4425
+ ...lora.source,
4426
+ path: manifest.source.path,
4427
+ revision: typeof manifest.source.revision === "string" ? manifest.source.revision : lora.source.revision,
4428
+ bytes: typeof manifest.source.bytes === "number" ? manifest.source.bytes : lora.source.bytes
4429
+ }
4430
+ };
4099
4431
  }
4100
4432
  }
4433
+ const file = resolvedDefinition.source.type === "local" ? files.file(filePathFromUri(resolvedDefinition.source.path, `lora ${lora.id}`)) : cachedLoRAFile(resolvedDefinition);
4434
+ const stat = await file.stat();
4435
+ const expectedBytes = loraExpectedBytes(resolvedDefinition);
4436
+ const installed = stat.type === "file";
4437
+ const verified = installed && hasSafetensorsHeader(stat.size) && (expectedBytes === void 0 || stat.size === expectedBytes);
4101
4438
  return {
4102
- ...state,
4103
- installed: state.state?.installed ?? false,
4104
- verified: state.state?.verified ?? false,
4105
- missingFiles: state.state?.missingFiles ?? [],
4106
- bytesPresent: state.state?.bytesPresent ?? 0,
4107
- totalBytes: state.state?.totalBytes ?? 0,
4108
- check
4109
- };
4110
- }
4111
- function useComposerAtom(initialValue) {
4112
- const ref = useStableRef(null);
4113
- ref.current ??= atom(initialValue);
4114
- return ref.current;
4115
- }
4116
- function useStableRef(initialValue) {
4117
- return useRef(initialValue);
4118
- }
4119
- function removeRefFromState(state, index) {
4120
- return {
4121
- ...state,
4122
- refs: state.refs.filter((_, i) => i !== index)
4439
+ id: lora.id,
4440
+ description: lora.description,
4441
+ path: file.path,
4442
+ uri: stat.uri,
4443
+ scale,
4444
+ source: resolvedDefinition.source,
4445
+ metadata: lora.metadata,
4446
+ installed,
4447
+ verified,
4448
+ size: stat.size
4123
4449
  };
4124
4450
  }
4125
- function inputDestination(inputRoot) {
4126
- return files.directory(inputRoot ?? files.paths.shared, "ImageGenerationInputs", String(Date.now()));
4127
- }
4128
- async function pickOneImage(inputRoot) {
4129
- const [picked] = await files.pick({
4130
- type: "image",
4131
- destination: inputDestination(inputRoot)
4132
- });
4133
- if (!picked) return null;
4134
- return Object.assign(picked, { size: await getImageSize(picked.uri) });
4135
- }
4136
- async function pickImages(inputRoot) {
4137
- const picked = await files.pick({
4138
- type: "image",
4139
- multiple: true,
4140
- destination: inputDestination(inputRoot)
4141
- });
4142
- return Promise.all(picked.map(async (image) => Object.assign(image, { size: await getImageSize(image.uri) })));
4143
- }
4144
- function getImageSize(uri) {
4145
- return new Promise((resolve, reject) => {
4146
- Image.getSize(uri, (width, height) => resolve({
4147
- width,
4148
- height
4149
- }), reject);
4150
- });
4151
- }
4152
- function errorFromUnknown(error) {
4153
- return error instanceof Error ? error : new Error(String(error));
4451
+ async function listImageLoRAs(loras) {
4452
+ return Promise.all(loras.map((lora) => verifyImageLoRA(lora)));
4154
4453
  }
4155
- function modelProgressStatus(progress) {
4156
- return `Model ${Math.round(progress.modelFraction * 100)}% ${formatBytes(progress.modelBytesWritten)} / ${formatBytes(progress.totalModelBytes)}`;
4454
+ async function deleteImageLoRA(lora) {
4455
+ const id = safeCacheName(typeof lora === "string" ? lora : lora.id, "lora.id");
4456
+ await imageLoRARoot().directory(id).delete({ recursive: true });
4157
4457
  }
4158
- function formatBytes(value) {
4159
- if (value < 1024) return `${value} B`;
4160
- const units = [
4161
- "KB",
4162
- "MB",
4163
- "GB",
4164
- "TB"
4165
- ];
4166
- let size = value / 1024;
4167
- let index = 0;
4168
- while (size >= 1024 && index < units.length - 1) {
4169
- size /= 1024;
4170
- index += 1;
4458
+ async function prepareSelectedImageLoRAs(loras, model, options = {}) {
4459
+ const prepared = [];
4460
+ for (const lora of loras) {
4461
+ assertLoRADefinition(lora);
4462
+ assertLoRACompatibility(lora, model);
4463
+ prepared.push(await prepareImageLoRA(lora, options));
4171
4464
  }
4172
- return `${size.toFixed(size >= 10 ? 1 : 2)} ${units[index]}`;
4465
+ return prepared;
4173
4466
  }
4174
-
4175
- //#endregion
4176
- //#region src/ai/shape.ts
4177
- var ShapeError = class extends Error {
4178
- constructor(code, message, issues = []) {
4179
- super(message);
4180
- this.code = code;
4181
- this.issues = issues;
4182
- this.name = "ShapeError";
4467
+ async function generateImage(options) {
4468
+ throwIfAborted(options.signal);
4469
+ const definition = imageModelDefinition(options.model ?? flux2Klein4B8BitAbliterated.model);
4470
+ const model = definition.manifest.model;
4471
+ const prompt = options.prompt.trim();
4472
+ if (!prompt) throw new AIError("invalid_message", "Expected prompt");
4473
+ const presetSize = options.aspectRatio ? imageSizeForPreset(options.aspectRatio) : void 0;
4474
+ const requestedSize = normalizeImageSize({
4475
+ width: options.width ?? presetSize?.width ?? 1024,
4476
+ height: options.height ?? presetSize?.height ?? 1024
4477
+ }, false);
4478
+ const width = requestedSize.width;
4479
+ const height = requestedSize.height;
4480
+ const outpaintSize = options.outpaint ? normalizeImageSize({
4481
+ width: options.outpaint.width,
4482
+ height: options.outpaint.height
4483
+ }, false) : void 0;
4484
+ if (options.outpaint && (outpaintSize?.width !== options.outpaint.width || outpaintSize?.height !== options.outpaint.height)) throw new AIError("invalid_model", "outpaint width and height must be multiples of 16");
4485
+ const steps = options.steps ?? 4;
4486
+ const guidance = options.guidance ?? 1;
4487
+ const seed = options.seed ?? Math.floor(Math.random() * 4294967296);
4488
+ const sourceImagePath = options.image ? filePathFromUri(options.image, "image") : void 0;
4489
+ const maskImagePath = options.mask ? filePathFromUri(options.mask, "mask") : void 0;
4490
+ const referenceImagePaths = (options.references ?? []).map((reference, index) => filePathFromUri(reference, `references[${index}]`));
4491
+ const isImageConditioned = Boolean(sourceImagePath) || referenceImagePaths.length > 0;
4492
+ const strength = options.strength ?? (isImageConditioned ? .8 : void 0);
4493
+ if (maskImagePath && !sourceImagePath) throw new AIError("invalid_message", "mask requires image");
4494
+ if (options.maskMode !== void 0 && options.maskMode !== "paint" && options.maskMode !== "preserve") throw new AIError("invalid_model", "maskMode must be paint or preserve");
4495
+ if (options.outpaint && !sourceImagePath) throw new AIError("invalid_message", "outpaint requires image");
4496
+ if (options.outpaint) {
4497
+ assertPositiveInteger(options.outpaint.width, "outpaint.width");
4498
+ assertPositiveInteger(options.outpaint.height, "outpaint.height");
4499
+ const rect = options.outpaint.sourceRect;
4500
+ if (!rect) throw new AIError("invalid_model", "outpaint.sourceRect is required");
4501
+ assertPositiveInteger(rect.width, "outpaint.sourceRect.width");
4502
+ assertPositiveInteger(rect.height, "outpaint.sourceRect.height");
4503
+ if (!Number.isInteger(rect.x) || !Number.isInteger(rect.y)) throw new AIError("invalid_model", "outpaint.sourceRect x and y must be integers");
4504
+ const canvasWidth = outpaintSize?.width ?? options.outpaint.width;
4505
+ const canvasHeight = outpaintSize?.height ?? options.outpaint.height;
4506
+ if (!(rect.x < canvasWidth && rect.y < canvasHeight && rect.x + rect.width > 0 && rect.y + rect.height > 0)) throw new AIError("invalid_model", "outpaint.sourceRect must intersect the canvas");
4507
+ if (!options.outpaint.autoCrop && (rect.x < 0 || rect.y < 0 || rect.x + rect.width > canvasWidth || rect.y + rect.height > canvasHeight)) throw new AIError("invalid_model", "outpaint.sourceRect must fit within the outpaint canvas");
4183
4508
  }
4184
- };
4185
- function issue(message, path = []) {
4186
- return {
4187
- message,
4188
- path
4189
- };
4190
- }
4191
- function validateDefinition(definition, value, path = []) {
4192
- if (definition === "string" || definition === "number" || definition === "boolean") {
4193
- if (typeof value === definition) return { value };
4194
- return { issues: [issue(`Expected ${path.join(".") || "value"} to be ${definition}`, path)] };
4195
- }
4196
- if (Array.isArray(definition)) {
4197
- if (!Array.isArray(value)) return { issues: [issue(`Expected ${path.join(".") || "value"} to be array`, path)] };
4198
- const itemDefinition = definition[0];
4199
- const issues$1 = [];
4200
- const output$1 = [];
4201
- for (const [index, item] of value.entries()) {
4202
- const result = validateDefinition(itemDefinition, item, [...path, index]);
4203
- if (result.issues !== void 0) issues$1.push(...result.issues);
4204
- else output$1.push(result.value);
4205
- }
4206
- if (issues$1.length > 0) return { issues: issues$1 };
4207
- return { value: output$1 };
4208
- }
4209
- if (!isRecord(value)) return { issues: [issue(`Expected ${path.join(".") || "value"} to be object`, path)] };
4210
- const output = {};
4211
- const issues = [];
4212
- for (const [key, field] of Object.entries(definition)) {
4213
- const result = validateDefinition(field, value[key], [...path, key]);
4214
- if (result.issues !== void 0) issues.push(...result.issues);
4215
- else output[key] = result.value;
4216
- }
4217
- if (issues.length > 0) return { issues };
4218
- return { value: output };
4219
- }
4220
- function bridgeSchema(definition) {
4221
- if (definition === "string" || definition === "number" || definition === "boolean") return { type: definition };
4222
- if (Array.isArray(definition)) return {
4223
- type: "array",
4224
- items: bridgeSchema(definition[0])
4225
- };
4226
- const properties = {};
4227
- const required = [];
4228
- for (const [key, value] of Object.entries(definition)) {
4229
- properties[key] = bridgeSchema(value);
4230
- required.push(key);
4509
+ if (options.resizeMode !== void 0 && options.resizeMode !== "stretch" && options.resizeMode !== "fit" && options.resizeMode !== "crop") throw new AIError("invalid_model", "resizeMode must be stretch, fit, or crop");
4510
+ if (options.maxInputLongSide !== void 0 && options.maxInputLongSide !== false && (!Number.isInteger(options.maxInputLongSide) || options.maxInputLongSide < 64)) throw new AIError("invalid_model", "maxInputLongSide must be false or an integer of at least 64");
4511
+ assertPositiveInteger(width, "width");
4512
+ assertPositiveInteger(height, "height");
4513
+ assertPositiveInteger(steps, "steps");
4514
+ if (seed !== void 0 && (!Number.isInteger(seed) || seed < 0)) throw new AIError("invalid_model", "seed must be a non-negative integer");
4515
+ if (!Number.isFinite(guidance) || guidance <= 0) throw new AIError("invalid_model", "guidance must be a positive number");
4516
+ if (referenceImagePaths.length > 3) throw new AIError("invalid_model", "references must contain at most 3 images");
4517
+ if (options.referenceInfluences !== void 0) {
4518
+ if (options.referenceInfluences.length !== referenceImagePaths.length) throw new AIError("invalid_model", "referenceInfluences must match references length");
4519
+ for (const [index, influence] of options.referenceInfluences.entries()) if (!Number.isFinite(influence) || influence < 0) throw new AIError("invalid_model", `referenceInfluences[${index}] must be a non-negative number`);
4231
4520
  }
4232
- return {
4233
- type: "object",
4234
- properties,
4235
- required
4521
+ if (strength !== void 0) assertUnitInterval(strength, "strength");
4522
+ const selectedLoRAs = options.loras?.length ? await withImageStage("download", () => prepareSelectedImageLoRAs(options.loras ?? [], model, {
4523
+ accessToken: options.accessToken,
4524
+ signal: options.signal
4525
+ })) : [];
4526
+ const sigmaSchedule = imageSigmaSchedule(selectedLoRAs.map((lora) => lora.metadata?.sigmaSchedule));
4527
+ if (sigmaSchedule && options.steps !== void 0 && options.steps !== sigmaSchedule.length) throw new AIError("invalid_model", `steps must equal the LoRA sigma schedule length (${sigmaSchedule.length})`);
4528
+ const generationSteps = sigmaSchedule?.length ?? steps;
4529
+ const prepared = options.path && options.tokenizer ? void 0 : await withImageStage("download", () => prepareImageModelAtPath(definition, {
4530
+ model,
4531
+ accessToken: options.accessToken,
4532
+ concurrency: options.concurrency,
4533
+ onProgress: options.onModelProgress
4534
+ }, options.path ?? modelCacheRoot(definition.manifest).path));
4535
+ throwIfAborted(options.signal);
4536
+ const tokenizer = options.tokenizer ?? prepared?.tokenizer;
4537
+ const modelPath = options.path ?? prepared?.path;
4538
+ if (!tokenizer || !modelPath) throw new AIError("invalid_model", "Expected image model path and tokenizer");
4539
+ const tokenized = await withImageStage("tokenize", () => tokenizer({
4540
+ prompt,
4541
+ maxLength: 512
4542
+ }));
4543
+ throwIfAborted(options.signal);
4544
+ await withImageStage("tokenize", () => {
4545
+ assertTokenArray(tokenized.inputIds, "inputIds");
4546
+ assertTokenArray(tokenized.attentionMask, "attentionMask");
4547
+ if (tokenized.inputIds.length !== tokenized.attentionMask.length) throw new AIError("invalid_message", "inputIds and attentionMask must have the same length");
4548
+ });
4549
+ const paths = fluxImageModelPaths(modelPath, definition.manifest);
4550
+ const request = {
4551
+ model,
4552
+ prompt,
4553
+ sourceImagePath,
4554
+ maskImagePath,
4555
+ maskMode: options.maskMode,
4556
+ outpaintWidth: outpaintSize?.width,
4557
+ outpaintHeight: outpaintSize?.height,
4558
+ outpaintSourceX: options.outpaint?.sourceRect.x,
4559
+ outpaintSourceY: options.outpaint?.sourceRect.y,
4560
+ outpaintSourceWidth: options.outpaint?.sourceRect.width,
4561
+ outpaintSourceHeight: options.outpaint?.sourceRect.height,
4562
+ outpaintAutoCrop: options.outpaint?.autoCrop,
4563
+ resizeMode: options.resizeMode,
4564
+ maxInputLongSide: options.maxInputLongSide === false ? 0 : options.maxInputLongSide ?? defaultImageLongSide,
4565
+ referenceImagePaths,
4566
+ referenceInfluences: options.referenceInfluences,
4567
+ loraPaths: selectedLoRAs.map((lora) => lora.path),
4568
+ loraScales: selectedLoRAs.map((lora) => lora.scale),
4569
+ loraIds: selectedLoRAs.map((lora) => lora.id),
4570
+ sigmaSchedule,
4571
+ width,
4572
+ height,
4573
+ steps: generationSteps,
4574
+ guidance,
4575
+ strength,
4576
+ seed,
4577
+ inputIds: tokenized.inputIds,
4578
+ attentionMask: tokenized.attentionMask,
4579
+ modelRoot: paths.path,
4580
+ textEncoderPath: paths.textEncoderPath,
4581
+ transformerPath: paths.transformerPath,
4582
+ vaePath: paths.vaePath
4236
4583
  };
4237
- }
4238
- function assertValidShape(definition, path = "shape") {
4239
- if (definition === "string" || definition === "number" || definition === "boolean") return;
4240
- if (Array.isArray(definition)) {
4241
- if (definition.length !== 1) throw new ShapeError("invalid_shape", `${path} arrays must contain exactly one item shape`);
4242
- assertValidShape(definition[0], `${path}[0]`);
4243
- return;
4244
- }
4245
- if (!isRecord(definition)) throw new ShapeError("invalid_shape", `${path} must be a shape object`);
4246
- for (const [key, value] of Object.entries(definition)) assertValidShape(value, `${path}.${key}`);
4247
- }
4248
- function createShape(definition) {
4249
- assertValidShape(definition);
4250
- const api = {
4251
- "~standard": {
4252
- version: 1,
4253
- vendor: "bleam",
4254
- validate(value) {
4255
- return api.safeParse(value);
4256
- }
4257
- },
4258
- parse(value) {
4259
- const result = api.safeParse(value);
4260
- if (result.issues !== void 0) throw new ShapeError("validation_failed", result.issues.map((nextIssue) => nextIssue.message).join("\n"), result.issues);
4261
- return result.value;
4262
- },
4263
- safeParse(value) {
4264
- return validateDefinition(definition, value);
4265
- },
4266
- toJSONSchema() {
4267
- return bridgeSchema(definition);
4268
- }
4584
+ const fallbackMetadata = {
4585
+ model,
4586
+ width: outpaintSize?.width ?? width,
4587
+ height: outpaintSize?.height ?? height,
4588
+ steps: generationSteps,
4589
+ guidance,
4590
+ strength,
4591
+ seed,
4592
+ appliedLoRAs: selectedLoRAs.map((lora) => ({
4593
+ id: lora.id,
4594
+ path: lora.path,
4595
+ scale: lora.scale
4596
+ })),
4597
+ sigmaSchedule
4269
4598
  };
4270
- return api;
4271
- }
4272
- function shape(definition) {
4273
- return createShape(definition);
4274
- }
4275
- function schemaToBridgeSchema(schema) {
4276
- const schemaWithBridge = schema;
4277
- if (typeof schemaWithBridge.toJSONSchema === "function") return schemaWithBridge.toJSONSchema();
4278
- throw new AIError("invalid_schema", "Structured output schemas must implement toJSONSchema()");
4279
- }
4280
- function validateStructuredInput(input) {
4281
- const result = input.shape["~standard"].validate(input.value);
4282
- if (result.issues !== void 0) throw new AIError("validation_failed", result.issues.map((nextIssue) => nextIssue.message).join("\n"), result.issues);
4283
- return result.value;
4284
- }
4285
- function stableStringify(value) {
4286
- if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
4287
- if (isRecord(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
4288
- return JSON.stringify(value) ?? "undefined";
4289
- }
4290
-
4291
- //#endregion
4292
- //#region src/ai/bonsai-generation.ts
4293
- async function prepareBonsaiGeneration(input) {
4294
- const state = await verifyBonsaiTextModel(input.model, { path: input.path });
4295
- if (!state.verified) throw new AIError("model_unavailable", `${input.model.id} is not prepared. Call prepareTextModel() before generation.`);
4296
- const tokenizer = new Tokenizer_default(await files.file(state.path, "tokenizer.json").json(), await files.file(state.path, "tokenizer_config.json").json());
4297
- const inputIds = tokenizer.encode(formatMessages(messagesFromInput(input))).ids.map(Number);
4298
- if (!inputIds.length || inputIds.some((token) => !Number.isInteger(token))) throw new AIError("invalid_message", "Tokenizer returned invalid token ids");
4299
- return {
4300
- request: {
4301
- id: input.id,
4302
- model: input.model.id,
4303
- modelPath: state.path,
4304
- inputIds,
4305
- endTokenIds: endTokenIds(input.model.id),
4306
- maxTokens: input.maxTokens,
4307
- temperature: input.temperature,
4308
- seed: input.seed
4309
- },
4310
- decode(tokenIds) {
4311
- return tokenIds.length ? tokenizer.decode(tokenIds, { skip_special_tokens: true }) : "";
4599
+ try {
4600
+ const native = bridge();
4601
+ const cancelNative = () => {
4602
+ native.cancelImagegen?.();
4603
+ };
4604
+ const subscription = options.onProgress ? native.addListener?.("imagegenProgress", (event) => {
4605
+ const progress = imagegenProgress(event);
4606
+ if (progress) options.onProgress?.(progress);
4607
+ }) : void 0;
4608
+ try {
4609
+ options.signal?.addEventListener("abort", cancelNative, { once: true });
4610
+ throwIfAborted(options.signal);
4611
+ const value = await native.generateImage?.(request);
4612
+ throwIfAborted(options.signal);
4613
+ return imageResult(value, model, fallbackMetadata);
4614
+ } finally {
4615
+ subscription?.remove();
4616
+ options.signal?.removeEventListener("abort", cancelNative);
4312
4617
  }
4313
- };
4314
- }
4315
- function messagesFromInput(input) {
4316
- if (input.messages) {
4317
- if (input.system !== void 0 || input.prompt !== void 0) throw new AIError("invalid_message", "messages cannot be combined with system or prompt");
4318
- if (!input.messages.length) throw new AIError("invalid_message", "Expected at least one message");
4319
- return input.messages;
4320
- }
4321
- if (!input.prompt?.trim()) throw new AIError("invalid_message", "Expected prompt");
4322
- return [...input.system ? [{
4323
- role: "system",
4324
- content: input.system
4325
- }] : [], {
4326
- role: "user",
4327
- content: input.prompt
4328
- }];
4618
+ } catch (error) {
4619
+ if (error instanceof ImageGenerationError) throw error;
4620
+ if (error instanceof AIError) throw error;
4621
+ if (options.signal?.aborted) throw new AIError("generation_canceled", "Image generation canceled", error);
4622
+ const mapped = mapNativeError(error);
4623
+ if (mapped.code === "generation_failed" || mapped.code === "image_generation_failed") throw new ImageGenerationError(nativeErrorStage(error) ?? "denoise", nativeErrorMessage(error), error);
4624
+ throw mapped;
4625
+ }
4329
4626
  }
4330
- function formatMessages(messages) {
4331
- if (messages[0]?.role === "assistant") throw new AIError("invalid_message", "Conversation cannot begin with assistant");
4332
- const parts = messages.map((message, index) => {
4333
- if (!message.content.trim()) throw new AIError("invalid_message", `Message ${index + 1} is empty`);
4334
- if (message.role === "system" && index !== 0) throw new AIError("invalid_message", "System message must be first");
4335
- return `<|im_start|>${message.role}\n${message.content}<|im_end|>\n`;
4336
- });
4337
- parts.push("<|im_start|>assistant\n<think>\n\n</think>\n\n");
4338
- return parts.join("");
4627
+ async function generateImages(options) {
4628
+ const { count,...imageOptions } = options;
4629
+ const results = [];
4630
+ for (const seed of batchImageSeeds(count, options.seed)) {
4631
+ throwIfAborted(options.signal);
4632
+ results.push(await generateImage({
4633
+ ...imageOptions,
4634
+ seed
4635
+ }));
4636
+ }
4637
+ return results;
4339
4638
  }
4340
- function endTokenIds(model) {
4341
- return model === "ternary-bonsai-27b" ? [248044, 248046] : [151643, 151645];
4639
+ const imageJobManagerKey = Symbol.for("bleam.ai.imageJobManager.v2");
4640
+ function imageJobManager() {
4641
+ const scope = globalThis;
4642
+ const manager = scope[imageJobManagerKey] ?? new ImageJobManager(new CollectionImageJobRepository(), generateImage);
4643
+ manager.setExecutor(generateImage);
4644
+ scope[imageJobManagerKey] = manager;
4645
+ return manager;
4646
+ }
4647
+ async function queueImage(options) {
4648
+ return imageJobManager().queue(options);
4649
+ }
4650
+ const image = Object.freeze({
4651
+ generate: generateImage,
4652
+ generateMany: generateImages,
4653
+ queue: queueImage,
4654
+ upscale: upscaleImage
4655
+ });
4656
+ const jobs = Object.freeze({
4657
+ get: (id) => imageJobManager().get(id),
4658
+ list: () => imageJobManager().list(),
4659
+ cancel: (id) => imageJobManager().cancel(id),
4660
+ retry: (id) => imageJobManager().retry(id),
4661
+ resume: (id) => imageJobManager().resume(id),
4662
+ remove: (id) => imageJobManager().remove(id)
4663
+ });
4664
+ function useJob(id) {
4665
+ return useManagedJob(imageJobManager(), id);
4666
+ }
4667
+ function useJobList() {
4668
+ return useManagedJobList(imageJobManager());
4342
4669
  }
4343
4670
 
4344
4671
  //#endregion
4345
- //#region src/ai/text.ts
4346
- function promptFromInput(options) {
4347
- const parts = [];
4348
- if (options.prompt) parts.push(options.prompt);
4349
- if (typeof options.input === "string") parts.push(options.input);
4350
- else if (options.input) parts.push(stableStringify(validateStructuredInput(options.input)));
4351
- if (parts.length === 0) throw new AIError("invalid_message", "Expected prompt or input");
4352
- return parts.join("\n\n");
4353
- }
4354
- async function isAvailable(model, options = {}) {
4355
- if (model) return (await availability(model, options)).available;
4356
- try {
4357
- return await bridge().isAvailable?.() ?? false;
4358
- } catch {
4359
- return false;
4360
- }
4672
+ //#region src/ai/image-composer.tsx
4673
+ const defaultImageSize = defaultImageLongSide;
4674
+ const defaultStepCount = 4;
4675
+ const minOutpaintScale = .35;
4676
+ const maxOutpaintScale = .95;
4677
+ function roundImageDimension(value) {
4678
+ return normalizeImageSize({
4679
+ width: value,
4680
+ height: value
4681
+ }, false).width;
4361
4682
  }
4362
- async function availability(model, options = {}) {
4363
- if (model) {
4364
- const state = await verifyBonsaiTextModel(model, options);
4365
- if (!state.installed) return {
4366
- available: false,
4367
- reason: "not_installed"
4368
- };
4369
- if (!state.verified) return {
4370
- available: false,
4371
- reason: "invalid_model"
4372
- };
4373
- return { available: true };
4374
- }
4375
- try {
4376
- return await bridge().availability?.() ?? {
4377
- available: false,
4378
- reason: "unknown"
4379
- };
4380
- } catch {
4381
- return {
4382
- available: false,
4383
- reason: "unknown"
4384
- };
4385
- }
4683
+ function imageSizeForAspectRatio(size, maxSide = defaultImageSize) {
4684
+ if (size.width <= 0 || size.height <= 0) return {
4685
+ width: maxSide,
4686
+ height: maxSide
4687
+ };
4688
+ const aspect = size.width / size.height;
4689
+ return normalizeImageSize({
4690
+ width: aspect >= 1 ? maxSide : maxSide * aspect,
4691
+ height: aspect >= 1 ? maxSide / aspect : maxSide
4692
+ }, maxSide);
4386
4693
  }
4387
- function generationId() {
4388
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
4694
+ function roundedImageSize(size) {
4695
+ return normalizeImageSize(size);
4389
4696
  }
4390
- function nativeRequest(options, id) {
4391
- if (options.temperature !== void 0 && (!Number.isFinite(options.temperature) || options.temperature < 0)) throw new AIError("invalid_message", "temperature must be a non-negative number");
4392
- if (options.maxTokens !== void 0 && (!Number.isInteger(options.maxTokens) || options.maxTokens <= 0)) throw new AIError("invalid_message", "maxTokens must be a positive integer");
4393
- const names = /* @__PURE__ */ new Set();
4394
- for (const tool of options.tools ?? []) {
4395
- if (!tool.name.trim()) throw new AIError("invalid_schema", "Tool names must not be empty");
4396
- if (names.has(tool.name)) throw new AIError("invalid_schema", `Duplicate tool name: ${tool.name}`);
4397
- names.add(tool.name);
4398
- }
4697
+ function clamp(value, min$1, max) {
4698
+ return Math.min(max, Math.max(min$1, value));
4699
+ }
4700
+ function clampOutpaintRect(rect) {
4701
+ const width = Math.min(defaultImageSize, Math.max(1, Math.round(rect.width)));
4702
+ const height = Math.min(defaultImageSize, Math.max(1, Math.round(rect.height)));
4399
4703
  return {
4400
- id,
4401
- system: options.system,
4402
- prompt: promptFromInput(options),
4403
- temperature: options.temperature,
4404
- maxTokens: options.maxTokens,
4405
- outputSchema: options.output ? schemaToBridgeSchema(options.output) : void 0,
4406
- tools: options.tools?.map((tool) => ({
4407
- name: tool.name,
4408
- description: tool.description,
4409
- inputSchema: schemaToBridgeSchema(tool.input)
4410
- }))
4704
+ x: Math.round(clamp(rect.x, 0, defaultImageSize - width)),
4705
+ y: Math.round(clamp(rect.y, 0, defaultImageSize - height)),
4706
+ width,
4707
+ height
4411
4708
  };
4412
4709
  }
4413
- function listenForTools(id, tools) {
4414
- if (!tools?.length) return void 0;
4415
- const native = bridge();
4416
- return native.addListener?.("toolCall", (event) => {
4417
- if (event.generationId !== id) return;
4418
- const tool = tools.find((candidate) => candidate.name === event.name);
4419
- (async () => {
4420
- try {
4421
- if (!tool) throw new Error(`Unknown tool: ${event.name}`);
4422
- const validation = tool.input["~standard"].validate(event.arguments);
4423
- if (validation.issues !== void 0) throw new Error(validation.issues.map((issue$1) => issue$1.message).join("\n"));
4424
- const output = await tool.execute(validation.value);
4425
- await native.resolveToolCall?.({
4426
- generationId: id,
4427
- callId: event.callId,
4428
- output: typeof output === "string" ? output : stableStringify(output)
4429
- });
4430
- } catch (error) {
4431
- await native.resolveToolCall?.({
4432
- generationId: id,
4433
- callId: event.callId,
4434
- error: error instanceof Error ? error.message : String(error)
4435
- });
4436
- }
4437
- })();
4438
- });
4439
- }
4440
- async function generate(options) {
4441
- const output = options.output;
4442
- const id = generationId();
4443
- const native = bridge();
4444
- const toolSubscription = listenForTools(id, "tools" in options ? options.tools : void 0);
4445
- const abort = () => void native.cancelTextGeneration?.(id);
4446
- options.signal?.addEventListener("abort", abort, { once: true });
4447
- try {
4448
- if (options.signal?.aborted) throw new AIError("generation_canceled", "Generation canceled");
4449
- if (options.model) {
4450
- const prepared = await prepareBonsaiGeneration({
4451
- id,
4452
- model: options.model,
4453
- path: options.path,
4454
- system: options.system,
4455
- prompt: options.prompt,
4456
- messages: options.messages,
4457
- temperature: options.temperature,
4458
- maxTokens: options.maxTokens,
4459
- seed: options.seed
4460
- });
4461
- if (options.signal?.aborted) throw new AIError("generation_canceled", "Generation canceled");
4462
- const tokenIds = await native.generateLocalText?.(prepared.request);
4463
- if (!tokenIds) throw new AIError("unsupported_runtime", "Local text generation is unavailable in this runtime");
4464
- return prepared.decode(tokenIds);
4465
- }
4466
- const value = await native.generate?.(nativeRequest(options, id));
4467
- if (output) {
4468
- const result = output["~standard"].validate(value);
4469
- if (result.issues !== void 0) throw new AIError("validation_failed", result.issues.map((nextIssue) => nextIssue.message).join("\n"), result.issues);
4470
- return result.value;
4471
- }
4472
- if (typeof value !== "string") throw new AIError("generation_failed", "Expected generated text");
4473
- return value;
4474
- } catch (error) {
4475
- if (error instanceof AIError) throw error;
4476
- throw mapNativeError(error);
4477
- } finally {
4478
- options.signal?.removeEventListener("abort", abort);
4479
- toolSubscription?.remove();
4480
- }
4481
- }
4482
- async function* stream(options) {
4483
- if (options.model) {
4484
- yield* streamBonsai(options);
4485
- return;
4486
- }
4487
- const id = generationId();
4488
- const native = bridge();
4489
- const updates = [];
4490
- let wake;
4491
- let settled = false;
4492
- let failure;
4493
- const updateSubscription = native.addListener?.("textGenerationUpdate", (event) => {
4494
- if (event.id !== id) return;
4495
- updates.push(event.content);
4496
- wake?.();
4497
- wake = void 0;
4498
- });
4499
- const toolSubscription = listenForTools(id, options.tools);
4500
- const abort = () => void native.cancelTextGeneration?.(id);
4501
- options.signal?.addEventListener("abort", abort, { once: true });
4502
- const completion = native.streamGenerate?.(nativeRequest(options, id)).catch((error) => {
4503
- failure = error;
4504
- }).finally(() => {
4505
- settled = true;
4506
- wake?.();
4507
- wake = void 0;
4710
+ function rectForSourceScale(sourceSize, scale, center) {
4711
+ const aspect = sourceSize.width / sourceSize.height;
4712
+ const longSide = defaultImageSize * clamp(scale, minOutpaintScale, maxOutpaintScale);
4713
+ const width = aspect >= 1 ? longSide : longSide * aspect;
4714
+ const height = aspect >= 1 ? longSide / aspect : longSide;
4715
+ const nextCenter = center ?? {
4716
+ x: defaultImageSize / 2,
4717
+ y: defaultImageSize / 2
4718
+ };
4719
+ return clampOutpaintRect({
4720
+ x: nextCenter.x - width / 2,
4721
+ y: nextCenter.y - height / 2,
4722
+ width,
4723
+ height
4508
4724
  });
4509
- try {
4510
- if (!completion) throw new AIError("unsupported_runtime", "Streaming is unavailable in this runtime");
4511
- while (!settled || updates.length > 0) if (updates.length > 0) yield updates.shift();
4512
- else await new Promise((resolve) => {
4513
- wake = resolve;
4514
- });
4515
- await completion;
4516
- if (failure) throw mapNativeError(failure);
4517
- } finally {
4518
- if (!settled) await native.cancelTextGeneration?.(id);
4519
- options.signal?.removeEventListener("abort", abort);
4520
- updateSubscription?.remove();
4521
- toolSubscription?.remove();
4522
- }
4523
4725
  }
4524
- async function* streamBonsai(options) {
4525
- const id = generationId();
4526
- const native = bridge();
4527
- if (options.signal?.aborted) throw new AIError("generation_canceled", "Generation canceled");
4528
- const prepared = await prepareBonsaiGeneration({
4529
- id,
4530
- model: options.model,
4531
- path: options.path,
4532
- system: options.system,
4533
- prompt: options.prompt,
4534
- messages: options.messages,
4535
- temperature: options.temperature,
4536
- maxTokens: options.maxTokens,
4537
- seed: options.seed
4538
- });
4539
- if (options.signal?.aborted) throw new AIError("generation_canceled", "Generation canceled");
4540
- const updates = [];
4541
- let wake;
4542
- let settled = false;
4543
- let failure;
4544
- const updateSubscription = native.addListener?.("localTextGenerationUpdate", (event) => {
4545
- if (event.id !== id) return;
4546
- updates.push(event.tokenIds);
4547
- wake?.();
4548
- wake = void 0;
4549
- });
4550
- const abort = () => void native.cancelTextGeneration?.(id);
4551
- options.signal?.addEventListener("abort", abort, { once: true });
4552
- const completion = native.streamLocalText?.(prepared.request).catch((error) => {
4553
- failure = error;
4554
- return [];
4555
- }).finally(() => {
4556
- settled = true;
4557
- wake?.();
4558
- wake = void 0;
4559
- });
4560
- try {
4561
- if (!completion) throw new AIError("unsupported_runtime", "Local text streaming is unavailable in this runtime");
4562
- while (!settled || updates.length > 0) if (updates.length > 0) yield prepared.decode(updates.shift());
4563
- else await new Promise((resolve) => {
4564
- wake = resolve;
4565
- });
4566
- await completion;
4567
- if (failure) throw mapNativeError(failure);
4568
- } finally {
4569
- if (!settled) await native.cancelTextGeneration?.(id);
4570
- options.signal?.removeEventListener("abort", abort);
4571
- updateSubscription?.remove();
4572
- }
4726
+ function initialOutpaintRect(sourceSize) {
4727
+ return rectForSourceScale(sourceSize, .72);
4573
4728
  }
4574
-
4575
- //#endregion
4576
- //#region src/ai/text-hook.ts
4577
- const initialState = {
4578
- text: "",
4579
- isGenerating: false,
4580
- error: null
4581
- };
4582
- function useTextGeneration() {
4583
- const [state, setState] = useState(initialState);
4584
- const abortControllerRef = useRef(null);
4585
- async function run(options) {
4586
- if (abortControllerRef.current) return null;
4587
- const abortController = new AbortController();
4588
- const abort = () => abortController.abort();
4589
- abortControllerRef.current = abortController;
4590
- options.signal?.addEventListener("abort", abort, { once: true });
4591
- if (options.signal?.aborted) abortController.abort();
4592
- setState({
4593
- text: "",
4594
- isGenerating: true,
4595
- error: null
4596
- });
4597
- let text = "";
4598
- try {
4599
- for await (const snapshot of stream({
4600
- ...options,
4601
- signal: abortController.signal
4602
- })) {
4603
- text = snapshot;
4604
- setState({
4605
- text,
4606
- isGenerating: true,
4607
- error: null
4608
- });
4609
- }
4610
- setState({
4611
- text,
4612
- isGenerating: false,
4613
- error: null
4614
- });
4615
- return text;
4616
- } catch (error) {
4617
- setState({
4618
- text,
4619
- isGenerating: false,
4620
- error: error instanceof Error ? error : new Error(String(error))
4621
- });
4622
- return null;
4623
- } finally {
4624
- options.signal?.removeEventListener("abort", abort);
4625
- if (abortControllerRef.current === abortController) abortControllerRef.current = null;
4626
- }
4729
+ function buildImageGenerationRequest(input, options = {}) {
4730
+ const base = {
4731
+ prompt: input.prompt,
4732
+ mode: input.mode,
4733
+ steps: defaultStepCount,
4734
+ guidance: 1,
4735
+ ...options
4736
+ };
4737
+ if (input.mode === "text") {
4738
+ const references = (input.refs ?? []).map((image$1) => image$1.path);
4739
+ return {
4740
+ ...base,
4741
+ references: references.length > 0 ? references : void 0,
4742
+ referenceInfluences: references.length > 0 ? references.map(() => 1) : void 0,
4743
+ strength: references.length > 0 ? 1 : void 0,
4744
+ width: defaultImageSize,
4745
+ height: defaultImageSize
4746
+ };
4627
4747
  }
4628
- function cancel() {
4629
- abortControllerRef.current?.abort();
4748
+ if (input.mode === "subject") {
4749
+ if (!input.subject) throw new Error("Subject mode requires a subject image");
4750
+ const refs = input.refs ?? [];
4751
+ const references = [input.subject, ...refs].map((image$1) => image$1.path);
4752
+ const size = imageSizeForAspectRatio(input.subject.size);
4753
+ return {
4754
+ ...base,
4755
+ references,
4756
+ referenceInfluences: references.map(() => 1),
4757
+ strength: 1,
4758
+ width: size.width,
4759
+ height: size.height
4760
+ };
4630
4761
  }
4631
- function clear() {
4632
- if (abortControllerRef.current) return;
4633
- setState(initialState);
4762
+ if (input.mode === "edit") {
4763
+ if (!input.source) throw new Error("Edit requires a source image");
4764
+ const references = (input.refs ?? []).map((image$1) => image$1.path);
4765
+ const size = roundedImageSize(input.source.size);
4766
+ return {
4767
+ ...base,
4768
+ image: input.source.path,
4769
+ references: references.length > 0 ? references : void 0,
4770
+ referenceInfluences: references.length > 0 ? references.map(() => 1) : void 0,
4771
+ strength: references.length > 0 ? 1 : .35,
4772
+ width: size.width,
4773
+ height: size.height
4774
+ };
4634
4775
  }
4776
+ if (!input.source) throw new Error("Outpaint requires a source image");
4777
+ if (!input.rect) throw new Error("Outpaint requires a source placement");
4635
4778
  return {
4636
- ...state,
4637
- run,
4638
- cancel,
4639
- clear
4779
+ ...base,
4780
+ image: input.source.path,
4781
+ outpaint: {
4782
+ width: defaultImageSize,
4783
+ height: defaultImageSize,
4784
+ sourceRect: input.rect,
4785
+ autoCrop: true
4786
+ },
4787
+ strength: .8,
4788
+ width: defaultImageSize,
4789
+ height: defaultImageSize
4640
4790
  };
4641
4791
  }
4642
4792
 
4643
4793
  //#endregion
4644
- export { AIError, ImageGenerationError, availability, bonsai, bonsaiTextModelCatalog, buildImageGenerationRequest, clampOutpaintRect, defaultImageLongSide, deleteImageLoRA, deleteImageModel, deleteBonsaiTextModel as deleteTextModel, flux2Klein4B8BitAbliterated, fluxImageModelPaths, generate, generateImage, generateImages, getImageGenerationJob, imageMemoryTelemetry, imageModelManifest, imageModelManifests, imageSizeForAspectRatio, imageSizeForPreset, initialOutpaintRect, isAvailable, listImageGenerationJobs, listImageLoRAs, listImageModels, listBonsaiTextModels as listTextModels, normalizeImageSize, prepareImageLoRA, prepareImageModel, prepareBonsaiTextModel as prepareTextModel, rectForSourceScale, roundImageDimension, roundedImageSize, scheduleImageGeneration, shape, stream, ternaryBonsaiImage4B, unloadImageModel, upscaleImage, useImageComposer, useImageGeneration, useImageModel, useTextGeneration, verifyImageLoRA, verifyImageModel, verifyBonsaiTextModel as verifyTextModel };
4794
+ export { AIError, ImageGenerationError, bonsai, bonsaiTextModelCatalog, buildImageGenerationRequest, chat, clampOutpaintRect, defaultImageLongSide, deleteImageLoRA, deleteImageModel, deleteBonsaiTextModel as deleteTextModel, flux2Klein4B8BitAbliterated, fluxImageModelPaths, image, imageMemoryTelemetry, imageModelManifest, imageModelManifests, imageSizeForAspectRatio, imageSizeForPreset, initialOutpaintRect, jobs, listImageLoRAs, listImageModels, listBonsaiTextModels as listTextModels, normalizeImageSize, prepareImageLoRA, prepareImageModel, prepareBonsaiTextModel as prepareTextModel, rectForSourceScale, roundImageDimension, roundedImageSize, ternaryBonsaiImage4B, unloadImageModel, useChat, useChatList, useJob, useJobList, verifyImageLoRA, verifyImageModel, verifyBonsaiTextModel as verifyTextModel };