briyah 1.3.4 → 1.3.5

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 (93) hide show
  1. package/README.md +65 -0
  2. package/data/common/config/comfyui-workflows/flux-kontext.edit.json +98 -0
  3. package/data/common/config/comfyui-workflows/flux-kontext.t2i.json +80 -0
  4. package/data/common/config/comfyui-workflows/flux2-dev.edit.json +125 -0
  5. package/data/common/config/comfyui-workflows/flux2-dev.t2i.json +96 -0
  6. package/data/common/config/image_models_full.json +186 -99
  7. package/data/common/config/markup +1 -1
  8. package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +1 -0
  9. package/dist-sdk/server/src/ai/LLM/base-ai.service.js +4 -2
  10. package/dist-sdk/server/src/ai/LLM/base-ai.service.spec.d.ts +1 -0
  11. package/dist-sdk/server/src/ai/LLM/base-ai.service.spec.js +89 -0
  12. package/dist-sdk/server/src/ai/LLM/comfyui-client.d.ts +29 -0
  13. package/dist-sdk/server/src/ai/LLM/comfyui-client.js +142 -0
  14. package/dist-sdk/server/src/ai/LLM/comfyui-client.spec.d.ts +1 -0
  15. package/dist-sdk/server/src/ai/LLM/comfyui-client.spec.js +143 -0
  16. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.d.ts +19 -0
  17. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.js +217 -0
  18. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.spec.d.ts +1 -0
  19. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.spec.js +207 -0
  20. package/dist-sdk/server/src/ai/LLM/comfyui.module.d.ts +2 -0
  21. package/dist-sdk/server/src/ai/LLM/comfyui.module.js +21 -0
  22. package/dist-sdk/server/src/ai/LLM/comfyui.service.d.ts +26 -0
  23. package/dist-sdk/server/src/ai/LLM/comfyui.service.js +191 -0
  24. package/dist-sdk/server/src/ai/LLM/mock.service.d.ts +1 -0
  25. package/dist-sdk/server/src/ai/LLM/mock.service.js +3 -0
  26. package/dist-sdk/server/src/ai/LLM/self-hosted.module.d.ts +2 -0
  27. package/dist-sdk/server/src/ai/LLM/self-hosted.module.js +21 -0
  28. package/dist-sdk/server/src/ai/LLM/self-hosted.service.d.ts +13 -0
  29. package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +205 -0
  30. package/dist-sdk/server/src/ai/ai-factory.module.js +4 -0
  31. package/dist-sdk/server/src/ai/ai-factory.service.d.ts +5 -1
  32. package/dist-sdk/server/src/ai/ai-factory.service.js +16 -2
  33. package/dist-sdk/server/src/app.service.js +1 -1
  34. package/dist-sdk/server/src/sdk/briyah.js +9 -3
  35. package/dist-sdk/server/src/story/story.service.js +11 -0
  36. package/docs/classes/Agent.html +15 -15
  37. package/docs/classes/Briyah.html +14 -14
  38. package/docs/classes/BriyahConfigService.html +5 -5
  39. package/docs/classes/Room.html +27 -27
  40. package/docs/classes/RoomMessage.html +10 -10
  41. package/docs/enums/MessageAction.html +3 -3
  42. package/docs/hierarchy.html +1 -1
  43. package/docs/index.html +47 -3
  44. package/docs/interfaces/AgentInfo.html +2 -2
  45. package/docs/interfaces/AgentMessagesResponse.html +2 -2
  46. package/docs/interfaces/AppService.html +119 -119
  47. package/docs/interfaces/Artifact.html +3 -3
  48. package/docs/interfaces/ArtifactMetadata.html +2 -2
  49. package/docs/interfaces/AttachDocumentResponse.html +2 -2
  50. package/docs/interfaces/BriyahConfigOptions.html +9 -9
  51. package/docs/interfaces/ChapterInfo.html +2 -2
  52. package/docs/interfaces/Character.html +2 -2
  53. package/docs/interfaces/CreateAgentResponse.html +2 -2
  54. package/docs/interfaces/CreateRoomResponse.html +2 -2
  55. package/docs/interfaces/CreateStoryResponse.html +2 -2
  56. package/docs/interfaces/FileList.html +2 -2
  57. package/docs/interfaces/FileMetadata.html +3 -3
  58. package/docs/interfaces/IConfigService.html +3 -3
  59. package/docs/interfaces/LoggingOptions.html +6 -6
  60. package/docs/interfaces/Message.html +2 -2
  61. package/docs/interfaces/ModelInfo.html +2 -2
  62. package/docs/interfaces/NativeToolDefinition.html +7 -7
  63. package/docs/interfaces/PreparedPromptResponse.html +2 -2
  64. package/docs/interfaces/ProcessTextResponse.html +2 -2
  65. package/docs/interfaces/PromptFile.html +2 -2
  66. package/docs/interfaces/PromptFileContent.html +2 -2
  67. package/docs/interfaces/PromptFilesResponse.html +2 -2
  68. package/docs/interfaces/PromptFolder.html +2 -2
  69. package/docs/interfaces/PromptFoldersResponse.html +2 -2
  70. package/docs/interfaces/RoomDetails.html +2 -2
  71. package/docs/interfaces/RoomInfo.html +2 -2
  72. package/docs/interfaces/RoomMessageUpdate.html +2 -2
  73. package/docs/interfaces/RoomMessagesResponse.html +2 -2
  74. package/docs/interfaces/SendMessageResult.html +2 -2
  75. package/docs/interfaces/StoryErrorEvent.html +3 -3
  76. package/docs/interfaces/StoryIdea.html +2 -2
  77. package/docs/interfaces/StoryInfo.html +3 -3
  78. package/docs/interfaces/StoryIntroduceCharacterEvent.html +3 -3
  79. package/docs/interfaces/StoryProgressChapterEvent.html +3 -3
  80. package/docs/interfaces/StoryState.html +5 -5
  81. package/docs/interfaces/StoryStateEvent.html +3 -3
  82. package/docs/interfaces/ToolDefinition.html +2 -2
  83. package/docs/interfaces/ToolHelpers.html +3 -3
  84. package/docs/interfaces/ToolParameter.html +2 -2
  85. package/docs/interfaces/ToolSummary.html +2 -2
  86. package/docs/interfaces/ToolsResponse.html +2 -2
  87. package/docs/interfaces/Transaction.html +2 -2
  88. package/docs/interfaces/TransactionHistoryResponse.html +2 -2
  89. package/docs/modules.html +1 -1
  90. package/docs/types/PromptScope.html +1 -1
  91. package/docs/types/ToolContext.html +2 -2
  92. package/docs/types/ToolRunResult.html +1 -1
  93. package/package.json +2 -1
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const comfyui_client_1 = require("./comfyui-client");
4
+ describe('ComfyUiClient', () => {
5
+ let fetchSpy;
6
+ beforeEach(() => {
7
+ fetchSpy = jest.spyOn(global, 'fetch');
8
+ });
9
+ afterEach(() => {
10
+ fetchSpy.mockRestore();
11
+ });
12
+ function jsonResponse(body, ok = true, status = 200) {
13
+ return {
14
+ ok,
15
+ status,
16
+ statusText: ok ? 'OK' : 'Error',
17
+ json: async () => body,
18
+ arrayBuffer: async () => new ArrayBuffer(0),
19
+ };
20
+ }
21
+ function makeClient(overrides = {}) {
22
+ return new comfyui_client_1.ComfyUiClient({
23
+ baseUrl: 'http://gpu-box:8188',
24
+ pollIntervalMs: 1,
25
+ timeoutMs: 500,
26
+ ...overrides,
27
+ });
28
+ }
29
+ describe('uploadImage', () => {
30
+ it('posts multipart form data and returns the server name/subfolder', async () => {
31
+ fetchSpy.mockResolvedValueOnce(jsonResponse({ name: 'stored.png', subfolder: 'sub' }));
32
+ const client = makeClient();
33
+ const result = await client.uploadImage(Buffer.from('fake-png'), 'ref.png');
34
+ expect(result).toEqual({ name: 'stored.png', subfolder: 'sub' });
35
+ const [url, options] = fetchSpy.mock.calls[0];
36
+ expect(url).toBe('http://gpu-box:8188/upload/image');
37
+ expect(options.method).toBe('POST');
38
+ expect(options.body).toBeInstanceOf(FormData);
39
+ });
40
+ it('throws on a non-OK response', async () => {
41
+ fetchSpy.mockResolvedValueOnce(jsonResponse({}, false, 500));
42
+ const client = makeClient();
43
+ await expect(client.uploadImage(Buffer.from('x'), 'ref.png')).rejects.toThrow(/upload failed/);
44
+ });
45
+ });
46
+ describe('queuePrompt', () => {
47
+ it('posts the workflow with a client_id and returns prompt_id', async () => {
48
+ fetchSpy.mockResolvedValueOnce(jsonResponse({ prompt_id: 'p-123' }));
49
+ const client = makeClient();
50
+ const workflow = { '1': { class_type: 'KSampler', inputs: {} } };
51
+ const promptId = await client.queuePrompt(workflow);
52
+ expect(promptId).toBe('p-123');
53
+ const [url, options] = fetchSpy.mock.calls[0];
54
+ expect(url).toBe('http://gpu-box:8188/prompt');
55
+ const body = JSON.parse(options.body);
56
+ expect(body.prompt).toEqual(workflow);
57
+ expect(body.client_id).toBeTruthy();
58
+ });
59
+ it('includes validation details when the workflow is rejected', async () => {
60
+ fetchSpy.mockResolvedValueOnce(jsonResponse({ error: { message: 'invalid node' } }, false, 400));
61
+ const client = makeClient();
62
+ await expect(client.queuePrompt({})).rejects.toThrow(/invalid node/);
63
+ });
64
+ it('sends extra headers on every request', async () => {
65
+ fetchSpy.mockResolvedValueOnce(jsonResponse({ prompt_id: 'p-1' }));
66
+ const client = makeClient({ extraHeaders: { Authorization: 'Basic abc' } });
67
+ await client.queuePrompt({});
68
+ const [, options] = fetchSpy.mock.calls[0];
69
+ expect(options.headers['Authorization']).toBe('Basic abc');
70
+ });
71
+ });
72
+ describe('waitForCompletion', () => {
73
+ it('polls until the prompt appears with an output image', async () => {
74
+ fetchSpy
75
+ .mockResolvedValueOnce(jsonResponse({}))
76
+ .mockResolvedValueOnce(jsonResponse({
77
+ 'p-1': {
78
+ status: { status_str: 'success', completed: true },
79
+ outputs: {
80
+ '10': {
81
+ images: [
82
+ { filename: 'out.png', subfolder: '', type: 'output' },
83
+ ],
84
+ },
85
+ },
86
+ },
87
+ }));
88
+ const client = makeClient();
89
+ const result = await client.waitForCompletion('p-1');
90
+ expect(result).toEqual({ filename: 'out.png', subfolder: '', type: 'output' });
91
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
92
+ });
93
+ it('throws with node error details on execution error', async () => {
94
+ fetchSpy.mockResolvedValueOnce(jsonResponse({
95
+ 'p-1': {
96
+ status: {
97
+ status_str: 'error',
98
+ messages: [
99
+ [
100
+ 'execution_error',
101
+ {
102
+ node_type: 'UNETLoader',
103
+ exception_message: 'model file not found',
104
+ },
105
+ ],
106
+ ],
107
+ },
108
+ outputs: {},
109
+ },
110
+ }));
111
+ const client = makeClient();
112
+ await expect(client.waitForCompletion('p-1')).rejects.toThrow(/UNETLoader: model file not found/);
113
+ });
114
+ it('throws a descriptive timeout error when the prompt never completes', async () => {
115
+ fetchSpy.mockResolvedValue(jsonResponse({}));
116
+ const client = makeClient({ timeoutMs: 20, pollIntervalMs: 1 });
117
+ await expect(client.waitForCompletion('p-1')).rejects.toThrow(/timed out/);
118
+ });
119
+ });
120
+ describe('fetchOutput', () => {
121
+ it('requests /view with filename, subfolder, and type', async () => {
122
+ const bytes = new TextEncoder().encode('png-bytes');
123
+ fetchSpy.mockResolvedValueOnce({
124
+ ok: true,
125
+ status: 200,
126
+ statusText: 'OK',
127
+ arrayBuffer: async () => bytes.buffer,
128
+ });
129
+ const client = makeClient();
130
+ const buffer = await client.fetchOutput({
131
+ filename: 'out.png',
132
+ subfolder: 'sub',
133
+ type: 'output',
134
+ });
135
+ expect(buffer.toString()).toBe('png-bytes');
136
+ const [url] = fetchSpy.mock.calls[0];
137
+ expect(url).toContain('/view?');
138
+ expect(url).toContain('filename=out.png');
139
+ expect(url).toContain('subfolder=sub');
140
+ expect(url).toContain('type=output');
141
+ });
142
+ });
143
+ });
@@ -0,0 +1,19 @@
1
+ import { UserPathsService } from '../../config/user-paths.service';
2
+ export type WorkflowVariant = 't2i' | 'edit';
3
+ export interface WorkflowPair {
4
+ name: string;
5
+ variants: WorkflowVariant[];
6
+ }
7
+ export interface WorkflowValues {
8
+ prompt: string;
9
+ seed: number;
10
+ width: number;
11
+ height: number;
12
+ refImage?: string;
13
+ }
14
+ export declare function getCommonWorkflowsDir(): string;
15
+ export declare function resolveWorkflowFile(pairName: string, variant: WorkflowVariant, userPaths?: UserPathsService): string | null;
16
+ export declare function listWorkflowPairs(): WorkflowPair[];
17
+ export declare function loadWorkflowTemplate(filePath: string): any;
18
+ export declare function patchWorkflow(templateJson: any, values: WorkflowValues): any;
19
+ export declare function chainReferenceImages(workflow: any, extraRefImages: string[]): any;
@@ -0,0 +1,217 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.getCommonWorkflowsDir = getCommonWorkflowsDir;
37
+ exports.resolveWorkflowFile = resolveWorkflowFile;
38
+ exports.listWorkflowPairs = listWorkflowPairs;
39
+ exports.loadWorkflowTemplate = loadWorkflowTemplate;
40
+ exports.patchWorkflow = patchWorkflow;
41
+ exports.chainReferenceImages = chainReferenceImages;
42
+ const fs = __importStar(require("fs"));
43
+ const path = __importStar(require("path"));
44
+ const logger_1 = require("../../common/logger");
45
+ const WORKFLOWS_SUBDIR = 'comfyui-workflows';
46
+ function getCommonWorkflowsDir() {
47
+ const dataDir = process.env.BRIYAH_DATA_PATH || path.resolve(process.cwd(), 'briyah-data');
48
+ return path.join(dataDir, 'common', 'config', WORKFLOWS_SUBDIR);
49
+ }
50
+ function getUserWorkflowsDir(userPaths) {
51
+ return path.join(userPaths.getUserDataDir(), WORKFLOWS_SUBDIR);
52
+ }
53
+ function resolveWorkflowFile(pairName, variant, userPaths) {
54
+ const fileName = `${pairName}.${variant}.json`;
55
+ const searchPaths = [];
56
+ if (userPaths) {
57
+ searchPaths.push(path.join(getUserWorkflowsDir(userPaths), fileName));
58
+ }
59
+ searchPaths.push(path.join(getCommonWorkflowsDir(), fileName));
60
+ for (const filePath of searchPaths) {
61
+ if (fs.existsSync(filePath)) {
62
+ return filePath;
63
+ }
64
+ }
65
+ return null;
66
+ }
67
+ function listWorkflowPairs() {
68
+ const dir = getCommonWorkflowsDir();
69
+ if (!fs.existsSync(dir)) {
70
+ return [];
71
+ }
72
+ const pairs = new Map();
73
+ for (const file of fs.readdirSync(dir)) {
74
+ const match = /^(.+)\.(t2i|edit)\.json$/.exec(file);
75
+ if (!match)
76
+ continue;
77
+ const [, name, variant] = match;
78
+ if (!pairs.has(name))
79
+ pairs.set(name, new Set());
80
+ pairs.get(name).add(variant);
81
+ }
82
+ return [...pairs.entries()]
83
+ .map(([name, variants]) => ({ name, variants: [...variants] }))
84
+ .sort((a, b) => a.name.localeCompare(b.name));
85
+ }
86
+ function loadWorkflowTemplate(filePath) {
87
+ const raw = fs.readFileSync(filePath, 'utf8');
88
+ return JSON.parse(raw);
89
+ }
90
+ function patchWorkflow(templateJson, values) {
91
+ const numericTokens = {
92
+ '{{seed}}': values.seed,
93
+ '{{width}}': values.width,
94
+ '{{height}}': values.height,
95
+ };
96
+ const patchValue = (value) => {
97
+ if (typeof value === 'string') {
98
+ if (value in numericTokens) {
99
+ return numericTokens[value];
100
+ }
101
+ if (value === '{{ref_image}}') {
102
+ return values.refImage ?? value;
103
+ }
104
+ let result = value.replaceAll('{{prompt}}', values.prompt);
105
+ if (values.refImage) {
106
+ result = result.replaceAll('{{ref_image}}', values.refImage);
107
+ }
108
+ return result;
109
+ }
110
+ if (Array.isArray(value)) {
111
+ return value.map(patchValue);
112
+ }
113
+ if (value !== null && typeof value === 'object') {
114
+ const patched = {};
115
+ for (const key of Object.keys(value)) {
116
+ patched[key] = patchValue(value[key]);
117
+ }
118
+ return patched;
119
+ }
120
+ return value;
121
+ };
122
+ const patched = patchValue(templateJson);
123
+ const leftovers = findLeftoverTokens(patched);
124
+ if (leftovers.length > 0) {
125
+ logger_1.logger.warn(`ComfyUI workflow still contains unresolved tokens after patching: ${leftovers.join(', ')}`);
126
+ }
127
+ return patched;
128
+ }
129
+ function chainReferenceImages(workflow, extraRefImages) {
130
+ if (extraRefImages.length === 0)
131
+ return workflow;
132
+ const result = JSON.parse(JSON.stringify(workflow));
133
+ const refLatentIds = Object.keys(result).filter((id) => result[id]?.class_type === 'ReferenceLatent');
134
+ if (refLatentIds.length !== 1) {
135
+ throw new Error(`Multi-reference chaining requires exactly one ReferenceLatent node in the edit ` +
136
+ `workflow template (found ${refLatentIds.length}).`);
137
+ }
138
+ const refLatentId = refLatentIds[0];
139
+ const latentInput = result[refLatentId].inputs?.latent;
140
+ if (!Array.isArray(latentInput)) {
141
+ throw new Error('ReferenceLatent node has no latent input connection.');
142
+ }
143
+ const vaeEncodeId = String(latentInput[0]);
144
+ const vaeEncode = result[vaeEncodeId];
145
+ if (vaeEncode?.class_type !== 'VAEEncode') {
146
+ throw new Error(`Expected the ReferenceLatent latent input to come from a VAEEncode node, ` +
147
+ `found '${vaeEncode?.class_type}'.`);
148
+ }
149
+ const middleChain = [];
150
+ let cursor = String(vaeEncode.inputs.pixels?.[0]);
151
+ while (result[cursor] && result[cursor].class_type !== 'LoadImage') {
152
+ middleChain.push(cursor);
153
+ const imageInput = result[cursor].inputs?.image;
154
+ if (!Array.isArray(imageInput)) {
155
+ throw new Error(`Cannot trace the reference image chain past node '${cursor}' ` +
156
+ `(${result[cursor].class_type}) — expected an 'image' input connection.`);
157
+ }
158
+ cursor = String(imageInput[0]);
159
+ }
160
+ if (!result[cursor]) {
161
+ throw new Error('Could not find the LoadImage node feeding the ReferenceLatent chain.');
162
+ }
163
+ middleChain.reverse();
164
+ const consumers = [];
165
+ for (const nodeId of Object.keys(result)) {
166
+ const inputs = result[nodeId].inputs ?? {};
167
+ for (const inputKey of Object.keys(inputs)) {
168
+ const value = inputs[inputKey];
169
+ if (Array.isArray(value) && String(value[0]) === refLatentId) {
170
+ consumers.push({ nodeId, inputKey });
171
+ }
172
+ }
173
+ }
174
+ let nextId = Math.max(...Object.keys(result).map(Number).filter((n) => !isNaN(n)), 0) + 1;
175
+ let lastRefLatentId = refLatentId;
176
+ for (const refImage of extraRefImages) {
177
+ const loadId = String(nextId++);
178
+ result[loadId] = { class_type: 'LoadImage', inputs: { image: refImage } };
179
+ let sourceId = loadId;
180
+ for (const midId of middleChain) {
181
+ const cloneId = String(nextId++);
182
+ result[cloneId] = JSON.parse(JSON.stringify(result[midId]));
183
+ result[cloneId].inputs.image = [sourceId, 0];
184
+ sourceId = cloneId;
185
+ }
186
+ const encodeId = String(nextId++);
187
+ result[encodeId] = JSON.parse(JSON.stringify(vaeEncode));
188
+ result[encodeId].inputs.pixels = [sourceId, 0];
189
+ const newRefLatentId = String(nextId++);
190
+ result[newRefLatentId] = {
191
+ class_type: 'ReferenceLatent',
192
+ inputs: {
193
+ conditioning: [lastRefLatentId, 0],
194
+ latent: [encodeId, 0],
195
+ },
196
+ };
197
+ lastRefLatentId = newRefLatentId;
198
+ }
199
+ for (const { nodeId, inputKey } of consumers) {
200
+ result[nodeId].inputs[inputKey] = [lastRefLatentId, 0];
201
+ }
202
+ return result;
203
+ }
204
+ function findLeftoverTokens(value, found = new Set()) {
205
+ if (typeof value === 'string') {
206
+ for (const match of value.matchAll(/\{\{[^}]+\}\}/g)) {
207
+ found.add(match[0]);
208
+ }
209
+ }
210
+ else if (Array.isArray(value)) {
211
+ value.forEach((v) => findLeftoverTokens(v, found));
212
+ }
213
+ else if (value !== null && typeof value === 'object') {
214
+ Object.values(value).forEach((v) => findLeftoverTokens(v, found));
215
+ }
216
+ return [...found];
217
+ }
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ const fs = __importStar(require("fs"));
37
+ const os = __importStar(require("os"));
38
+ const path = __importStar(require("path"));
39
+ const comfyui_workflow_1 = require("./comfyui-workflow");
40
+ describe('comfyui-workflow', () => {
41
+ let tmpDir;
42
+ let originalDataPath;
43
+ beforeEach(() => {
44
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'briyah-workflow-test-'));
45
+ originalDataPath = process.env.BRIYAH_DATA_PATH;
46
+ process.env.BRIYAH_DATA_PATH = tmpDir;
47
+ });
48
+ afterEach(() => {
49
+ if (originalDataPath === undefined) {
50
+ delete process.env.BRIYAH_DATA_PATH;
51
+ }
52
+ else {
53
+ process.env.BRIYAH_DATA_PATH = originalDataPath;
54
+ }
55
+ fs.rmSync(tmpDir, { recursive: true, force: true });
56
+ });
57
+ function writeCommonWorkflow(fileName, content = {}) {
58
+ const dir = (0, comfyui_workflow_1.getCommonWorkflowsDir)();
59
+ fs.mkdirSync(dir, { recursive: true });
60
+ fs.writeFileSync(path.join(dir, fileName), JSON.stringify(content));
61
+ }
62
+ describe('patchWorkflow', () => {
63
+ const template = {
64
+ '1': {
65
+ class_type: 'CLIPTextEncode',
66
+ inputs: { text: 'masterpiece, {{prompt}}, cinematic', clip: ['2', 0] },
67
+ },
68
+ '2': {
69
+ class_type: 'EmptySD3LatentImage',
70
+ inputs: { width: '{{width}}', height: '{{height}}', batch_size: 1 },
71
+ },
72
+ '3': {
73
+ class_type: 'KSampler',
74
+ inputs: { seed: '{{seed}}', steps: 20 },
75
+ },
76
+ '4': {
77
+ class_type: 'LoadImage',
78
+ inputs: { image: '{{ref_image}}' },
79
+ },
80
+ };
81
+ const values = {
82
+ prompt: 'a red fox',
83
+ seed: 12345,
84
+ width: 1024,
85
+ height: 768,
86
+ refImage: 'briyah-ref-abc.png',
87
+ };
88
+ it('coerces exact-match numeric tokens to numbers', () => {
89
+ const patched = (0, comfyui_workflow_1.patchWorkflow)(template, values);
90
+ expect(patched['2'].inputs.width).toBe(1024);
91
+ expect(patched['2'].inputs.height).toBe(768);
92
+ expect(patched['3'].inputs.seed).toBe(12345);
93
+ expect(typeof patched['3'].inputs.seed).toBe('number');
94
+ });
95
+ it('substring-replaces the prompt so templates can wrap it', () => {
96
+ const patched = (0, comfyui_workflow_1.patchWorkflow)(template, values);
97
+ expect(patched['1'].inputs.text).toBe('masterpiece, a red fox, cinematic');
98
+ });
99
+ it('replaces ref_image in LoadImage inputs', () => {
100
+ const patched = (0, comfyui_workflow_1.patchWorkflow)(template, values);
101
+ expect(patched['4'].inputs.image).toBe('briyah-ref-abc.png');
102
+ });
103
+ it('leaves ref_image token in place when no refImage value is given', () => {
104
+ const patched = (0, comfyui_workflow_1.patchWorkflow)(template, { ...values, refImage: undefined });
105
+ expect(patched['4'].inputs.image).toBe('{{ref_image}}');
106
+ });
107
+ it('does not modify the input template', () => {
108
+ (0, comfyui_workflow_1.patchWorkflow)(template, values);
109
+ expect(template['3'].inputs.seed).toBe('{{seed}}');
110
+ });
111
+ it('preserves node connections (arrays)', () => {
112
+ const patched = (0, comfyui_workflow_1.patchWorkflow)(template, values);
113
+ expect(patched['1'].inputs.clip).toEqual(['2', 0]);
114
+ });
115
+ });
116
+ describe('chainReferenceImages', () => {
117
+ const editWorkflow = {
118
+ '3': { class_type: 'VAELoader', inputs: { vae_name: 'ae.safetensors' } },
119
+ '4': { class_type: 'LoadImage', inputs: { image: 'ref-1.png' } },
120
+ '5': { class_type: 'FluxKontextImageScale', inputs: { image: ['4', 0] } },
121
+ '6': { class_type: 'VAEEncode', inputs: { pixels: ['5', 0], vae: ['3', 0] } },
122
+ '7': { class_type: 'CLIPTextEncode', inputs: { text: 'prompt', clip: ['2', 0] } },
123
+ '8': {
124
+ class_type: 'ReferenceLatent',
125
+ inputs: { conditioning: ['7', 0], latent: ['6', 0] },
126
+ },
127
+ '9': { class_type: 'FluxGuidance', inputs: { conditioning: ['8', 0], guidance: 2.5 } },
128
+ '11': {
129
+ class_type: 'KSampler',
130
+ inputs: { positive: ['9', 0], latent_image: ['6', 0], seed: 1 },
131
+ },
132
+ };
133
+ it('returns the workflow unchanged for zero extra references', () => {
134
+ expect((0, comfyui_workflow_1.chainReferenceImages)(editWorkflow, [])).toBe(editWorkflow);
135
+ });
136
+ it('clones the image chain and appends ReferenceLatent nodes per extra reference', () => {
137
+ const result = (0, comfyui_workflow_1.chainReferenceImages)(editWorkflow, ['ref-2.png', 'ref-3.png']);
138
+ const refLatents = Object.keys(result).filter((id) => result[id].class_type === 'ReferenceLatent');
139
+ expect(refLatents).toHaveLength(3);
140
+ const loadImages = Object.keys(result)
141
+ .filter((id) => result[id].class_type === 'LoadImage')
142
+ .map((id) => result[id].inputs.image);
143
+ expect(loadImages).toEqual(['ref-1.png', 'ref-2.png', 'ref-3.png']);
144
+ const encodes = Object.keys(result).filter((id) => result[id].class_type === 'VAEEncode');
145
+ expect(encodes).toHaveLength(3);
146
+ for (const id of encodes) {
147
+ expect(result[id].inputs.vae).toEqual(['3', 0]);
148
+ }
149
+ });
150
+ it('chains conditioning in order and rewires the consumer to the last link', () => {
151
+ const result = (0, comfyui_workflow_1.chainReferenceImages)(editWorkflow, ['ref-2.png', 'ref-3.png']);
152
+ const lastId = result['9'].inputs.conditioning[0];
153
+ expect(lastId).not.toBe('8');
154
+ const middleId = result[lastId].inputs.conditioning[0];
155
+ expect(result[middleId].class_type).toBe('ReferenceLatent');
156
+ expect(result[middleId].inputs.conditioning[0]).toBe('8');
157
+ expect(result['11'].inputs.latent_image).toEqual(['6', 0]);
158
+ });
159
+ it('does not modify the input workflow', () => {
160
+ (0, comfyui_workflow_1.chainReferenceImages)(editWorkflow, ['ref-2.png']);
161
+ expect(editWorkflow['9'].inputs.conditioning).toEqual(['8', 0]);
162
+ expect(Object.keys(editWorkflow)).toHaveLength(8);
163
+ });
164
+ it('throws when the template has no ReferenceLatent node', () => {
165
+ const t2i = { '1': { class_type: 'KSampler', inputs: {} } };
166
+ expect(() => (0, comfyui_workflow_1.chainReferenceImages)(t2i, ['ref-2.png'])).toThrow(/exactly one ReferenceLatent/);
167
+ });
168
+ });
169
+ describe('resolveWorkflowFile', () => {
170
+ it('finds a template in the common directory', () => {
171
+ writeCommonWorkflow('flux-kontext.t2i.json');
172
+ const resolved = (0, comfyui_workflow_1.resolveWorkflowFile)('flux-kontext', 't2i');
173
+ expect(resolved).toBe(path.join((0, comfyui_workflow_1.getCommonWorkflowsDir)(), 'flux-kontext.t2i.json'));
174
+ });
175
+ it('returns null when no template exists', () => {
176
+ expect((0, comfyui_workflow_1.resolveWorkflowFile)('missing', 'edit')).toBeNull();
177
+ });
178
+ it('prefers the user directory over common', () => {
179
+ writeCommonWorkflow('flux-kontext.t2i.json', { source: 'common' });
180
+ const userDataDir = path.join(tmpDir, 'user', 'test-user');
181
+ const userWorkflowsDir = path.join(userDataDir, 'comfyui-workflows');
182
+ fs.mkdirSync(userWorkflowsDir, { recursive: true });
183
+ fs.writeFileSync(path.join(userWorkflowsDir, 'flux-kontext.t2i.json'), JSON.stringify({ source: 'user' }));
184
+ const fakeUserPaths = {
185
+ getUserDataDir: () => userDataDir,
186
+ };
187
+ const resolved = (0, comfyui_workflow_1.resolveWorkflowFile)('flux-kontext', 't2i', fakeUserPaths);
188
+ expect(resolved).toBe(path.join(userWorkflowsDir, 'flux-kontext.t2i.json'));
189
+ });
190
+ });
191
+ describe('listWorkflowPairs', () => {
192
+ it('returns empty when the directory does not exist', () => {
193
+ expect((0, comfyui_workflow_1.listWorkflowPairs)()).toEqual([]);
194
+ });
195
+ it('groups t2i and edit variants into pairs', () => {
196
+ writeCommonWorkflow('flux-kontext.t2i.json');
197
+ writeCommonWorkflow('flux-kontext.edit.json');
198
+ writeCommonWorkflow('qwen-edit.edit.json');
199
+ writeCommonWorkflow('notes.txt');
200
+ const pairs = (0, comfyui_workflow_1.listWorkflowPairs)();
201
+ expect(pairs).toEqual([
202
+ { name: 'flux-kontext', variants: expect.arrayContaining(['t2i', 'edit']) },
203
+ { name: 'qwen-edit', variants: ['edit'] },
204
+ ]);
205
+ });
206
+ });
207
+ });
@@ -0,0 +1,2 @@
1
+ export declare class ComfyUiModule {
2
+ }
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.ComfyUiModule = void 0;
10
+ const common_1 = require("@nestjs/common");
11
+ const comfyui_service_1 = require("./comfyui.service");
12
+ let ComfyUiModule = class ComfyUiModule {
13
+ };
14
+ exports.ComfyUiModule = ComfyUiModule;
15
+ exports.ComfyUiModule = ComfyUiModule = __decorate([
16
+ (0, common_1.Module)({
17
+ imports: [],
18
+ providers: [comfyui_service_1.ComfyUiAiService],
19
+ exports: [comfyui_service_1.ComfyUiAiService],
20
+ })
21
+ ], ComfyUiModule);
@@ -0,0 +1,26 @@
1
+ import { BaseAiService } from './base-ai.service';
2
+ import { Agent } from '../agent';
3
+ import { ModelInfo } from '../../../../shared/types/app.types';
4
+ export declare class ComfyUiAiService extends BaseAiService {
5
+ private client;
6
+ constructor();
7
+ getServiceName(): string;
8
+ supportsImageGeneration(): boolean;
9
+ requiresKnownModel(): boolean;
10
+ fetchModelsFromApi(): Promise<ModelInfo[]>;
11
+ textPrompt(_agent: Agent, _prompt: string, _jsonSchema?: any, _saveResponse?: boolean, _promptInstructions?: string, _cacheConfig?: any, _maxOutputChars?: number): Promise<any>;
12
+ generateImage(agent: Agent, prompt: string, imageProperties?: Record<string, any>): Promise<{
13
+ artifactId?: string;
14
+ error?: any;
15
+ }>;
16
+ editImage(agent: Agent, prompt: string, imageProperties?: Record<string, any>, referenceImageArtifactIds?: string[]): Promise<{
17
+ artifactId?: string;
18
+ error?: any;
19
+ }>;
20
+ private checkBalance;
21
+ private prepareWorkflow;
22
+ private runWorkflow;
23
+ private computeImageCost;
24
+ private loadReferenceBuffers;
25
+ private buildMultiRefPreamble;
26
+ }