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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
import { promises as fsPromises } from 'node:fs';
import path from 'node:path';
import urlJoin from 'url-join';
import { DEFAULT_AVATAR_PATH } from './constants.js';
import { extractFileFromZipBuffer, humanizedISO8601DateTime } from './util.js';

/**
 * A parser for BYAF (Backyard Archive Format) files.
 */
export class ByafParser {
    /**
     * @param {ArrayBufferLike} data BYAF ZIP buffer
     */
    #data;

    /**
     * Creates an instance of ByafParser.
     * @param {ArrayBufferLike} data BYAF ZIP buffer
     */
    constructor(data) {
        this.#data = data;
    }

    /**
     * Replaces known macros in a string.
     * @param {string} [str] String to process
     * @returns {string} String with macros replaced
     * @private
     */
    static replaceMacros(str) {
        return String(str || '')
            .replace(/#{user}:/gi, '{{user}}:')
            .replace(/#{character}:/gi, '{{char}}:')
            .replace(/{character}(?!})/gi, '{{char}}')
            .replace(/{user}(?!})/gi, '{{user}}');
    }

    /**
     * Formats example messages for a character.
     * @param {ByafExampleMessage[]} [examples] Array of example objects
     * @returns {string} Formatted example messages
     * @private
     */
    static formatExampleMessages(examples) {
        if (!Array.isArray(examples)) {
            return '';
        }

        let formattedExamples = '';

        examples.forEach((example) => {
            if (!example?.text) {
                return;
            }
            formattedExamples += `<START>\n${ByafParser.replaceMacros(example.text)}\n`;
        });

        return formattedExamples.trimEnd();
    }

    /**
     * Formats alternate greetings for a character.
     * @param {Partial<ByafScenario>[]} [scenarios] Array of scenario objects
     * @returns {string[]} Formatted alternate greetings
     * @private
     */
    formatAlternateGreetings(scenarios) {
        if (!Array.isArray(scenarios)) {
            return [];
        }

        // Skip one because it goes into 'first_mes'
        if (scenarios.length <= 1) {
            return [];
        }
        const greetings = new Set();
        const firstScenarioFirstMessage = scenarios?.[0]?.firstMessages?.[0]?.text;
        for (const scenario of scenarios.slice(1).filter(s => Array.isArray(s.firstMessages) && s.firstMessages.length > 0)) {
            // As per the BYAF spec, "firstMessages" array MUST contain AT MOST one message.
            // So we only consider the first one if it exists.
            const firstMessage = scenario?.firstMessages?.[0];
            if (firstMessage?.text && firstMessage.text !== firstScenarioFirstMessage) {
                greetings.add(ByafParser.replaceMacros(firstMessage.text));
            }
        }
        return Array.from(greetings);
    }

    /**
     * Converts character book items to a structured format.
     * @param {ByafLoreItem[]} items Array of key-value pairs
     * @returns {CharacterBook|undefined} Converted character book or undefined if invalid
     * @private
     */
    convertCharacterBook(items) {
        if (!Array.isArray(items) || items.length === 0) {
            return undefined;
        }

        /** @type {CharacterBook} */
        const book = {
            entries: [],
            extensions: {},
        };

        items.forEach((item, index) => {
            if (!item) {
                return;
            }
            book.entries.push({
                keys: ByafParser.replaceMacros(item?.key).split(',').map(key => key.trim()).filter(Boolean),
                content: ByafParser.replaceMacros(item?.value),
                extensions: {},
                enabled: true,
                insertion_order: index,
            });
        });

        return book;
    }

    /**
     * Extracts a character object from BYAF buffer.
     * @param {ByafManifest} manifest BYAF manifest
     * @returns {Promise<{character:ByafCharacter,characterPath:string}>} Character object
     * @private
     */
    async getCharacterFromManifest(manifest) {
        const charactersArray = manifest?.characters;

        if (!Array.isArray(charactersArray)) {
            throw new Error('Invalid BYAF file: missing characters array');
        }

        if (charactersArray.length === 0) {
            throw new Error('Invalid BYAF file: characters array is empty');
        }

        if (charactersArray.length > 1) {
            console.warn('Warning: BYAF manifest contains more than one character, only the first one will be imported');
        }

        const characterPath = charactersArray[0];
        if (!characterPath) {
            throw new Error('Invalid BYAF file: missing character path');
        }

        const characterBuffer = await extractFileFromZipBuffer(this.#data, characterPath);
        if (!characterBuffer) {
            throw new Error('Invalid BYAF file: failed to extract character JSON');
        }

        try {
            const character = JSON.parse(characterBuffer.toString());
            return { character, characterPath };
        } catch (error) {
            console.error('Failed to parse character JSON from BYAF:', error);
            throw new Error('Invalid BYAF file: character is not a valid JSON');
        }
    }

    /**
     * Extracts all scenario objects from BYAF buffer.
     * @param {ByafManifest} manifest BYAF manifest
     * @returns {Promise<Partial<ByafScenario>[]>} Scenarios array
     * @private
     */
    async getScenariosFromManifest(manifest) {
        const scenariosArray = manifest?.scenarios;

        if (!Array.isArray(scenariosArray) || scenariosArray.length === 0) {
            console.warn('Warning: BYAF manifest contains no scenarios');
            return [{}];
        }

        const scenarios = [];

        for (const scenarioPath of scenariosArray) {
            const scenarioBuffer = await extractFileFromZipBuffer(this.#data, scenarioPath);
            if (!scenarioBuffer) {
                console.warn('Warning: failed to extract BYAF scenario JSON');
            }
            if (scenarioBuffer) {
                try {
                    scenarios.push(JSON.parse(scenarioBuffer.toString()));
                } catch (error) {
                    console.warn('Warning: BYAF scenario is not a valid JSON', error);
                }
            }
        }

        if (scenarios.length === 0) {
            console.warn('Warning: BYAF manifest contains no valid scenarios');
            return [{}];
        }

        return scenarios;
    }

    /**
     * Extracts all character icon images from BYAF buffer.
     * @param {ByafCharacter} character Character object
     * @param {string} characterPath Path to the character in the BYAF manifest
     * @return {Promise<{filename: string, image: Buffer, label: string}[]>} Image buffer
     * @private
     */
    async getCharacterImages(character, characterPath) {
        const defaultAvatarBuffer = await fsPromises.readFile(DEFAULT_AVATAR_PATH);
        const characterImages = character?.images;

        if (!Array.isArray(characterImages) || characterImages.length === 0) {
            console.warn('Warning: BYAF character has no images');
            return [{ filename: '', image: defaultAvatarBuffer, label: '' }];
        }

        const imageBuffers = [];
        for (const image of characterImages) {
            const imagePath = image?.path;
            if (!imagePath) {
                console.warn('Warning: BYAF character image path is empty');
                continue;
            }

            const fullImagePath = urlJoin(path.dirname(characterPath), imagePath);
            const imageBuffer = await extractFileFromZipBuffer(this.#data, fullImagePath);
            if (!imageBuffer) {
                console.warn('Warning: failed to extract BYAF character image');
                continue;
            }

            imageBuffers.push({ filename: path.basename(imagePath), image: imageBuffer, label: image?.label || '' });
        }
        if (imageBuffers.length === 0) {
            console.warn('Warning: BYAF character has no valid images');
            return [{ filename: '', image: defaultAvatarBuffer, label: '' }];
        }
        return imageBuffers;
    }

    /**
     * Formats BYAF data as a character card.
     * @param {ByafManifest} manifest BYAF manifest
     * @param {ByafCharacter} character Character object
     * @param {Partial<ByafScenario>[]} scenarios Scenarios array
     * @return {TavernCardV2} Character card object
     * @private
     */
    getCharacterCard(manifest, character, scenarios) {
        return {
            spec: 'chara_card_v2',
            spec_version: '2.0',
            data: {
                name: character?.name || character?.displayName || '',
                description: ByafParser.replaceMacros(character?.persona),
                personality: '',
                scenario: ByafParser.replaceMacros(scenarios[0]?.narrative),
                first_mes: ByafParser.replaceMacros(scenarios[0]?.firstMessages?.[0]?.text),
                mes_example: ByafParser.formatExampleMessages(scenarios[0]?.exampleMessages),
                creator_notes: manifest?.author?.backyardURL || '', // To preserve the link to the author from BYAF manifest, this is a good place.
                system_prompt: ByafParser.replaceMacros(scenarios[0]?.formattingInstructions),
                post_history_instructions: '',
                alternate_greetings: this.formatAlternateGreetings(scenarios),
                character_book: this.convertCharacterBook(character?.loreItems),
                tags: character?.isNSFW ? ['nsfw'] : [], // Since there are no tags in BYAF spec, we can use this to preserve the isNSFW flag.
                creator: manifest?.author?.name || '',
                character_version: '',
                extensions: { ...(character?.displayName && { 'display_name': character?.displayName }) }, // Preserve display name unmodified using extensions. "display_name" is not used by SillyTavern currently.
            },
            // @ts-ignore Non-standard spec extension
            create_date: humanizedISO8601DateTime(),
        };
    }
    /**
     * Gets chat backgrounds from BYAF data mapped to their respective scenarios.
     * @param {ByafCharacter} character Character object
     * @param {Partial<ByafScenario>[]} scenarios Scenarios array
     * @returns {Promise<Array<ByafChatBackground>>} Chat backgrounds
     * @private
     */
    async getChatBackgrounds(character, scenarios) {
        // Implementation for extracting chat backgrounds from BYAF data
        const backgrounds = [];
        let i = 1;
        for (const scenario of scenarios) {
            const bgImagePath = scenario?.backgroundImage;
            if (bgImagePath) {
                const data = await extractFileFromZipBuffer(this.#data, bgImagePath);
                if (data) {
                    const existingIndex = backgrounds.findIndex(bg => bg.data.compare(data) === 0);
                    if (existingIndex !== -1) {
                        backgrounds[existingIndex].paths.push(bgImagePath);
                        continue; // Skip adding a new background since it already exists
                    }
                    backgrounds.push({
                        name: `${character?.name} bg ${i++}` || '',
                        data: data,
                        paths: [bgImagePath],
                    });
                }
            }
        }
        return backgrounds;
    }

    /**
     * Gets the manifest from the BYAF data.
     * @returns {Promise<ByafManifest>} Parsed manifest
     * @private
     */
    async getManifest() {
        const manifestBuffer = await extractFileFromZipBuffer(this.#data, 'manifest.json');
        if (!manifestBuffer) {
            throw new Error('Failed to extract manifest.json from BYAF file');
        }

        const manifest = JSON.parse(manifestBuffer.toString());
        if (!manifest || typeof manifest !== 'object') {
            throw new Error('Invalid BYAF manifest');
        }

        return manifest;
    }

    /**
     * Imports a chat from BYAF format.
     * @param {Partial<ByafScenario>} scenario Scenario object
     * @param {string} userName User name
     * @param {string} characterName Character name
     * @param {Array<ByafChatBackground>} chatBackgrounds Chat backgrounds
     * @returns {string} Chat data
     */
    static getChatFromScenario(scenario, userName, characterName, chatBackgrounds) {
        const chatStartDate = scenario?.messages?.length == 0 ? humanizedISO8601DateTime() : scenario?.messages?.filter(m => 'createdAt' in m)[0].createdAt;
        const chatBackground = chatBackgrounds.find(bg => bg.paths.includes(scenario?.backgroundImage || ''))?.name || '';
        /** @type {object[]} */
        const chat = [{
            user_name: userName,
            character_name: characterName,
            create_date: chatStartDate,
            chat_metadata: {
                scenario: scenario?.narrative ?? '',
                mes_example: ByafParser.formatExampleMessages(scenario?.exampleMessages),
                system_prompt: ByafParser.replaceMacros(scenario?.formattingInstructions),
                mes_examples_optional: scenario?.canDeleteExampleMessages ?? false,
                byaf_model_settings: {
                    model: scenario?.model ?? '',
                    temperature: scenario?.temperature ?? 1.2,
                    top_k: scenario?.topK ?? 40,
                    top_p: scenario?.topP ?? 0.9,
                    min_p: scenario?.minP ?? 0.1,
                    min_p_enabled: scenario?.minPEnabled ?? true,
                    repeat_penalty: scenario?.repeatPenalty ?? 1.05,
                    repeat_penalty_tokens: scenario?.repeatLastN ?? 256,
                    by_prompt_template: scenario?.promptTemplate ?? 'general',
                    grammar: scenario?.grammar ?? null,
                },
                chat_backgrounds: chatBackground ? [chatBackground] : [],
                custom_background: chatBackground ? `url("${encodeURI(chatBackground)}")` : '',
            },
        }];
        // Add the first message IF it exists.
        if (scenario?.firstMessages?.length && scenario?.firstMessages?.length > 0 && scenario?.firstMessages?.[0]?.text) {
            chat.push({
                name: characterName,
                is_user: false,
                send_date: chatStartDate,
                mes: scenario?.firstMessages?.[0]?.text || '',
            });
        }

        const sortByTimestamp = (newest, curr) => {
            const aTime = new Date(newest.activeTimestamp);
            const bTime = new Date(curr.activeTimestamp);
            return aTime >= bTime ? newest : curr;
        };

        const getNewestAiMessage = (message) => {
            return message.outputs.reduce(sortByTimestamp);
        };
        const getSwipesForAiMessage = (aiMessage) => {
            return aiMessage.outputs.map(output => output.text);
        };

        const userMessages = scenario?.messages?.filter(msg => msg.type === 'human');
        const characterMessages = scenario?.messages?.filter(msg => msg.type === 'ai');
        /**
         * Reorders messages by interleaving user and character messages so that they are in correct chronological order.
         * This is only needed to import old chats from Backyard AI that were incorrectly imported by an earlier version
         * that completely messed up the order of messages. Backyard AI Windows frontend never supported creation of chats
         * with which were ordered like this in the first place, so for most users this is desired functionality.
         */
        if (userMessages && characterMessages && userMessages.length === characterMessages.length) { // Only do the reordering if there are equal numbers of user and character messages, otherwise just import in existing order, because it's probably correct already.
            for (let i = 0; i < userMessages.length; i++) {
                chat.push({
                    name: userName,
                    is_user: true,
                    send_date: Number(userMessages[i]?.createdAt),
                    mes: userMessages[i]?.text,
                });
                const aiMessage = getNewestAiMessage(characterMessages[i]);
                const aiSwipes = getSwipesForAiMessage(characterMessages[i]);
                chat.push({
                    name: characterName,
                    is_user: false,
                    send_date: Number(aiMessage.createdAt),
                    mes: aiMessage.text,
                    swipes: aiSwipes,
                    swipe_id: aiSwipes.findIndex(s => s === aiMessage.text),
                });
            }
        } else if (scenario?.messages) {
            for (const message of scenario.messages) {
                const isUser = message.type === 'human';
                const aiMessage = !isUser ? getNewestAiMessage(message) : null;
                const chatMessage = {
                    name: isUser ? userName : characterName,
                    is_user: isUser,
                    send_date: Number(isUser ? message.createdAt : aiMessage.createdAt),
                    mes: isUser ? message.text : aiMessage.text,
                };
                if (!isUser) {
                    const aiSwipes = getSwipesForAiMessage(message);
                    chatMessage.swipes = aiSwipes;
                    chatMessage.swipe_id = aiSwipes.findIndex(s => s === aiMessage.text);
                }
                chat.push(chatMessage);
            }
        } else {
            console.warn('Warning: BYAF scenario contained no messages property.');
        }

        return chat.map(obj => JSON.stringify(obj)).join('\n');
    }

    /**
     * Parses the BYAF data.
     * @return {Promise<ByafParseResult>} Parsed character card and image buffer
     */
    async parse() {
        const manifest = await this.getManifest();
        const { character, characterPath } = await this.getCharacterFromManifest(manifest);
        const scenarios = await this.getScenariosFromManifest(manifest);
        const images = await this.getCharacterImages(character, characterPath);
        const card = this.getCharacterCard(manifest, character, scenarios);
        const chatBackgrounds = await this.getChatBackgrounds(character, scenarios);
        return { card, images, scenarios, chatBackgrounds, character };
    }
}

export default ByafParser;