Repository navigation
Expand file tree
/
Copy pathquickstart.js
More file actions
305 lines (278 loc) · 12.2 KB
/
Copy pathquickstart.js
File metadata and controls
305 lines (278 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
import { getSettings, getActiveChatId } from './state-manager.js';
import {
getArchetypesForGenre,
generateQuickStartCharacter,
generatePersonaBio,
addPlayerCardToLorebookAgent,
activateSillyTavernPersona,
} from './character-creator.js';
import { saveSettings, autoApplySysprompt } from './src/app/runtime-bridge.js';
import { pickGenreCharacterName } from './src/state/character-names.js';
import {
buildInstantActionOpeningMessage,
buildInstantActionPromptSection,
extractInstantActionLevel,
normalizeInstantActionInstructions,
resolveInstantActionPlayerCardWords,
resolveInstantActionStartingLevel,
} from './src/state/instant-action-instructions.js';
import { createChatCommitGuard } from './src/state/pass-affinity.js';
/** @type {boolean} */
let _quickStartRunning = false;
const GENRE_LABELS = {
fantasy: 'Fantasy',
realistic: 'Modern',
scifi: 'Sci-Fi',
horror: 'Horror',
};
/**
* @param {Uint32Array} [buf]
* @returns {number} 0..1
*/
function secureRandom() {
const buf = new Uint32Array(1);
crypto.getRandomValues(buf);
return buf[0] / (0xFFFFFFFF + 1);
}
/**
* @param {string[]} list
* @returns {string}
*/
function pickRandomArchetype(list) {
if (!list.length) return 'Fighter';
const idx = Math.floor(secureRandom() * list.length);
return list[idx] || list[0];
}
/**
* @param {HTMLElement|null} rootEl
* @param {string} text
*/
function setQuickStartStatus(rootEl, text) {
const status = rootEl?.querySelector('#rt-quickstart-status');
if (status) status.textContent = text;
}
/**
* @param {HTMLElement|null} rootEl
* @param {boolean} disabled
*/
function setQuickStartBusy(rootEl, disabled) {
if (!rootEl) return;
rootEl.querySelectorAll('.rt-quickstart button, .rt-random-char-btn').forEach((btn) => {
/** @type {HTMLButtonElement} */ (btn).disabled = disabled;
});
rootEl.querySelectorAll('.rt-quickstart input, .rt-quickstart textarea').forEach((field) => {
/** @type {HTMLInputElement|HTMLTextAreaElement} */ (field).disabled = disabled;
});
const genBtn = /** @type {HTMLButtonElement|null} */ (rootEl.querySelector('#rt-cr-generate-btn'));
if (genBtn) genBtn.disabled = disabled;
}
/**
* Apply the player's current Narrator Configuration before Instant Action begins.
*/
async function applyQuickStartConfiguration(canCommit) {
saveSettings();
await autoApplySysprompt(true, { canCommit });
if (!canCommit()) return;
if (typeof globalThis._rpgRenderAgentModules === 'function') {
globalThis._rpgRenderAgentModules();
}
}
/**
* Send an outgoing user chat message the same way CYOA buttons do.
* @param {string} text
*/
function sendOutgoingChatMessage(text) {
const textarea = /** @type {HTMLTextAreaElement|null} */ (document.getElementById('send_textarea'));
const sendBtn = /** @type {HTMLButtonElement|null} */ (document.getElementById('send_but'));
if (!textarea || !sendBtn) {
throw new Error('Chat input is not available.');
}
textarea.value = text;
textarea.dispatchEvent(new Event('input', { bubbles: true }));
sendBtn.click();
}
/**
* Full Instant Action pipeline for one genre. Steps are strictly sequential.
* @param {string} genre
* @param {HTMLElement|null} [rootEl]
* @param {string} [selectedName]
* @param {string} [instructionText]
*/
export async function runQuickStart(genre, rootEl = null, selectedName = '', instructionText = '') {
if (_quickStartRunning) {
toastr['info']('Quick Start is already running. Please wait.', 'Quick Start');
return;
}
const validGenre = ['fantasy', 'realistic', 'scifi', 'horror'].includes(genre) ? genre : 'fantasy';
const root = rootEl || /** @type {HTMLElement|null} */ (document.querySelector('.rt-empty'));
const nameVal = String(selectedName || '').trim();
const instantActionInstructions = normalizeInstantActionInstructions(instructionText);
const passChatId = getActiveChatId();
const ownsChat = createChatCommitGuard(passChatId, getActiveChatId);
_quickStartRunning = true;
setQuickStartBusy(root, true);
try {
setQuickStartStatus(root, 'Enabling systems…');
await applyQuickStartConfiguration(ownsChat);
if (!ownsChat()) throw new Error('Quick Start stopped because the active chat changed.');
const s = getSettings();
s.onboardingGenre = validGenre;
saveSettings();
const archetypes = getArchetypesForGenre(validGenre);
const className = pickRandomArchetype(archetypes);
const noLevel = s.onboardingLevel === 'none';
const randomLevel = s.onboardingInstantActionRandomLevel === true;
const level = resolveInstantActionStartingLevel({
noLevel,
randomLevel,
random: secureRandom,
});
const gearTier = s.onboardingGearTier || 'auto';
const wordCount = resolveInstantActionPlayerCardWords(
s.onboardingPersonaWords || '150',
s.onboardingPersonaWordsCustom,
);
const genreLabel = GENRE_LABELS[validGenre] || validGenre;
const setupLevel = extractInstantActionLevel(instantActionInstructions);
const levelDetail = setupLevel != null
? `Lv ${setupLevel} (Initial Setup)`
: (noLevel ? 'no levels' : `Lv ${level}`);
const creationDetails = [
genreLabel,
instantActionInstructions ? 'custom setup' : className,
nameVal || 'AI-chosen name',
levelDetail,
].join(' · ');
setQuickStartStatus(root, `Creating character (${creationDetails})…`);
const { charName } = await generateQuickStartCharacter({
chatId: passChatId, canCommit: ownsChat,
genre: validGenre,
className,
level,
gearTier,
nameVal,
instantActionInstructions,
});
if (!ownsChat()) {
throw new Error('Quick Start stopped because the active chat changed.');
}
setQuickStartStatus(root, 'Creating Lorebook Agent Player Card…');
const bio = await generatePersonaBio(
charName,
wordCount,
buildInstantActionPromptSection(instantActionInstructions),
);
if (!ownsChat()) {
throw new Error('Quick Start stopped because the active chat changed.');
}
if (!bio) {
throw new Error('Persona generation returned empty.');
}
const ok = await addPlayerCardToLorebookAgent(charName, bio, wordCount, { chatId: passChatId, canCommit: ownsChat });
if (!ok) {
throw new Error(
ownsChat()
? 'Could not add Player Card — no active chat.'
: 'Quick Start stopped because the active chat changed.',
);
}
if (!ownsChat()) {
throw new Error('Quick Start stopped because the active chat changed.');
}
setQuickStartStatus(root, 'Creating name-only chat persona…');
await activateSillyTavernPersona(charName, { chatId: passChatId, canCommit: ownsChat });
if (!ownsChat()) {
throw new Error('Quick Start stopped because the active chat changed.');
}
const readyDetail = instantActionInstructions ? 'custom instructions' : className;
if (s.onboardingSendStarterMessage !== false) {
setQuickStartStatus(root, 'Starting adventure…');
sendOutgoingChatMessage(buildInstantActionOpeningMessage(instantActionInstructions));
setQuickStartStatus(root, `Ready — ${charName} (${readyDetail})`);
} else {
setQuickStartStatus(root, `Ready — ${charName} (${readyDetail}). Type your first action.`);
}
toastr['success'](`Quick Start ready: ${charName} · ${readyDetail}`, 'Quick Start');
} catch (err) {
const msg = err?.message || String(err);
console.error('[Quick Start]', err);
setQuickStartStatus(root, 'Ready');
toastr['error'](`Quick Start failed: ${msg}`, 'Quick Start', { timeOut: 8000 });
} finally {
_quickStartRunning = false;
setQuickStartBusy(root, false);
}
}
/**
* Wire Quick Start genre buttons inside an onboarding root.
* @param {HTMLElement} rootEl
*/
export function bindQuickStartEvents(rootEl) {
if (!rootEl) return;
const section = rootEl.querySelector('#rt-quickstart');
if (!section || /** @type {any} */ (section)._qsBound) return;
/** @type {any} */ (section)._qsBound = true;
const genreButtons = [...section.querySelectorAll('.rt-quickstart-genre-btn')];
const rollButton = /** @type {HTMLButtonElement|null} */ (section.querySelector('#rt-quickstart-roll-name'));
const startButton = /** @type {HTMLButtonElement|null} */ (section.querySelector('#rt-quickstart-begin'));
const nameInput = /** @type {HTMLInputElement|null} */ (section.querySelector('#rt-quickstart-name'));
const instructionsInput = /** @type {HTMLTextAreaElement|null} */ (section.querySelector('#rt-quickstart-instructions'));
const wordCountSelect = /** @type {HTMLSelectElement|null} */ (section.querySelector('#rt-quickstart-persona-words'));
const wordCountCustom = /** @type {HTMLInputElement|null} */ (section.querySelector('#rt-quickstart-persona-words-custom'));
const sendStarterCheckbox = /** @type {HTMLInputElement|null} */ (section.querySelector('#rt-quickstart-send-starter'));
const randomLevelCheckbox = /** @type {HTMLInputElement|null} */ (section.querySelector('#rt-quickstart-random-level'));
let selectedGenre = '';
let selectedName = '';
const persistQuickStartOptions = () => {
const s = getSettings();
if (wordCountSelect) s.onboardingPersonaWords = wordCountSelect.value || '150';
if (wordCountCustom) s.onboardingPersonaWordsCustom = wordCountCustom.value;
if (wordCountCustom) wordCountCustom.style.display = wordCountSelect?.value === 'other' ? 'block' : 'none';
if (sendStarterCheckbox) s.onboardingSendStarterMessage = !!sendStarterCheckbox.checked;
if (randomLevelCheckbox) s.onboardingInstantActionRandomLevel = !!randomLevelCheckbox.checked;
saveSettings();
};
genreButtons.forEach((btn) => {
btn.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
selectedGenre = /** @type {HTMLButtonElement} */ (btn).dataset.genre || 'fantasy';
genreButtons.forEach((genreButton) => {
const isSelected = genreButton === btn;
genreButton.classList.toggle('is-selected', isSelected);
genreButton.setAttribute('aria-pressed', String(isSelected));
});
if (rollButton) rollButton.disabled = false;
if (startButton) startButton.disabled = false;
setQuickStartStatus(rootEl, `${GENRE_LABELS[selectedGenre] || selectedGenre} selected — name optional`);
});
});
rollButton?.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
if (!selectedGenre) return;
selectedName = pickGenreCharacterName(selectedGenre);
if (nameInput) nameInput.value = selectedName;
if (startButton) startButton.disabled = false;
setQuickStartStatus(rootEl, 'Name ready — reroll or begin');
});
nameInput?.addEventListener('input', () => {
selectedName = nameInput.value.trim();
if (selectedName) {
setQuickStartStatus(rootEl, 'Name ready — edit, reroll, or begin');
} else if (selectedGenre) {
setQuickStartStatus(rootEl, 'Name blank — the AI will choose');
}
});
wordCountSelect?.addEventListener('change', persistQuickStartOptions);
wordCountCustom?.addEventListener('input', persistQuickStartOptions);
sendStarterCheckbox?.addEventListener('change', persistQuickStartOptions);
randomLevelCheckbox?.addEventListener('change', persistQuickStartOptions);
startButton?.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
if (!selectedGenre) return;
persistQuickStartOptions();
void runQuickStart(selectedGenre, rootEl, selectedName, instructionsInput?.value || '');
});
}