Repository navigation
Expand file tree
/
Copy path_worker.ts
More file actions
2829 lines (2524 loc) · 132 KB
/
Copy path_worker.ts
File metadata and controls
2829 lines (2524 loc) · 132 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
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Hono } from 'hono';
import { Lobby } from './src/lobby';
import { SignJWT, jwtVerify } from 'jose';
import { aiChat, aiChatStream, aiStatus, aiImage } from './src/lib/aiClient';
// Worker types - declared locally to avoid DOM type conflicts in mixed frontend/backend repo
declare const WebSocketPair: { new (): { 0: WebSocket; 1: WebSocket } };
type DurableObjectNamespace = { idFromName(name: string): { toString(): string }; get(id: unknown): { fetch(req: RequestInfo | URL): Promise<Response> } };
type ExecutionContext = { waitUntil(promise: Promise<unknown>): void; passThroughOnException(): void };
interface Ai {
run(model: string, input: Record<string, unknown>): Promise<ArrayBuffer | ReadableStream | Record<string, unknown>>;
}
interface KVNamespace {
get(key: string, options?: { type?: string }): Promise<string | ArrayBuffer | null>;
put(key: string, value: string | ArrayBuffer, options?: { expirationTtl?: number; metadata?: Record<string, string> }): Promise<void>;
delete(key: string): Promise<void>;
}
interface R2Bucket {
put(key: string, value: ArrayBuffer | ReadableStream | string, options?: { httpMetadata?: { contentType?: string }; customMetadata?: Record<string, string> }): Promise<unknown>;
get(key: string): Promise<{ body: ReadableStream; httpMetadata?: { contentType?: string }; customMetadata?: Record<string, string>; size: number } | null>;
delete(key: string): Promise<void>;
head(key: string): Promise<{ httpMetadata?: { contentType?: string }; customMetadata?: Record<string, string>; size: number } | null>;
}
interface D1Database {
prepare(query: string): D1PreparedStatement;
batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;
exec(query: string): Promise<D1ExecResult>;
}
interface D1PreparedStatement {
bind(...values: unknown[]): D1PreparedStatement;
first<T = Record<string, unknown>>(column?: string): Promise<T | null>;
all<T = Record<string, unknown>>(): Promise<D1Result<T>>;
run(): Promise<D1Result>;
raw<T = unknown[]>(): Promise<T[]>;
}
interface D1Result<T = unknown> {
results: T[];
success: boolean;
meta: Record<string, unknown>;
}
interface D1ExecResult {
count: number;
duration: number;
}
interface Env {
LOBBY: DurableObjectNamespace;
AI?: Ai;
ASSETS?: { fetch: (req: Request) => Promise<Response> };
PORTRAITS?: KVNamespace;
CHARACTERS?: KVNamespace;
CAMPAIGNS?: KVNamespace;
MAP_IMAGES?: R2Bucket;
DB?: D1Database;
DISCORD_CLIENT_ID: string;
DISCORD_CLIENT_SECRET: string;
GOOGLE_CLIENT_ID?: string;
GOOGLE_CLIENT_SECRET?: string;
GITHUB_CLIENT_ID?: string;
GITHUB_CLIENT_SECRET?: string;
JWT_SECRET?: string;
}
const app = new Hono<{ Bindings: Env }>();
// AI timeout wrapper — prevents hanging AI calls from blocking indefinitely.
// Workers AI can occasionally hang; this races the call against a timeout.
const AI_TIMEOUT_MS = 25_000; // 25s — under the Worker 30s limit on free plan
const AI_IMAGE_TIMEOUT_MS = 45_000; // 45s — image gen is slower
// ---- AI helpers ----
// All text AI goes through aiChat() / aiChatStream() from src/lib/aiClient.ts.
// Image/vision models (FLUX, Llama Vision) bypass the unified client — Workers AI only.
class AiTimeoutError extends Error {
constructor(model: string, ms: number) { super(`AI ${model} timed out after ${ms / 1000}s`); this.name = 'AiTimeoutError'; }
}
// Cast Hono env to the shape aiClient expects
function aiEnv(env: unknown): import('./src/lib/aiClient').AiEnv {
return env as unknown as import('./src/lib/aiClient').AiEnv;
}
// Text chat: prompt in, string out. Works offline, local, or cloud.
async function aiText(env: unknown, messages: Array<{ role: string; content: string }>, maxTokens?: number): Promise<string> {
const result = await aiChat(aiEnv(env), messages as Array<{ role: 'system' | 'user' | 'assistant'; content: string }>, maxTokens);
return result.text;
}
// Image/vision models — Workers AI only (no local equivalent), with timeout
async function aiRunDirect(ai: Ai, model: string, input: Record<string, unknown>): Promise<ArrayBuffer | ReadableStream | Record<string, unknown>> {
const ms = model.includes('FLUX') ? AI_IMAGE_TIMEOUT_MS : AI_TIMEOUT_MS;
return Promise.race([ai.run(model, input), new Promise<never>((_, reject) => setTimeout(() => reject(new AiTimeoutError(model, ms)), ms))]);
}
// Error logging helper — ensures all catch blocks leave a trace
function logError(context: string, err: unknown): void {
const msg = err instanceof Error ? err.message : String(err);
console.error(`[adventure] ${context}: ${msg}`);
}
// Discord OAuth
const DISCORD_AUTH_URI = 'https://discord.com/api/oauth2/authorize';
const DISCORD_TOKEN_URI = 'https://discord.com/api/oauth2/token';
const DISCORD_USERINFO_URI = 'https://discord.com/api/users/@me';
const DISCORD_REDIRECT_URIS = ['http://localhost:5173/api/auth/discord/callback', 'https://adventure.notebooks.cloudflare.com/api/auth/discord/callback'];
// Google OAuth
const GOOGLE_AUTH_URI = 'https://accounts.google.com/o/oauth2/v2/auth';
const GOOGLE_TOKEN_URI = 'https://oauth2.googleapis.com/token';
const GOOGLE_USERINFO_URI = 'https://www.googleapis.com/oauth2/v2/userinfo';
const GOOGLE_REDIRECT_URIS = ['http://localhost:5173/api/auth/google/callback', 'https://adventure.notebooks.cloudflare.com/api/auth/google/callback'];
// GitHub OAuth
const GITHUB_AUTH_URI = 'https://github.com/login/oauth/authorize';
const GITHUB_TOKEN_URI = 'https://github.com/login/oauth/access_token';
const GITHUB_USERINFO_URI = 'https://api.github.com/user';
const GITHUB_REDIRECT_URIS = ['http://localhost:5173/api/auth/github/callback', 'https://adventure.notebooks.cloudflare.com/api/auth/github/callback'];
const COOKIE_NAME = 'adventure_session';
const DEV_JWT_FALLBACK = 'adventure-dev-secret-do-not-use-in-prod';
const CAMPAIGN_BACKFILL_LIMIT = 500;
const CAMPAIGN_OWNER_LOOKUP_CHUNK = 100;
const D1_BATCH_CHUNK = 100;
const CAMPAIGN_MIGRATION_MARKER_VERSION = 'd1:v1';
function legacyCampaignListKey(userId: string): string {
return `user:${userId}:campaigns`;
}
function campaignMigrationMarkerKey(userId: string): string {
return `user:${userId}:campaigns:migrated:${CAMPAIGN_MIGRATION_MARKER_VERSION}`;
}
function getJwtKey(env: Env) {
return new TextEncoder().encode(env.JWT_SECRET || DEV_JWT_FALLBACK);
}
// GET /api/auth/discord - redirect to Discord OAuth
// AI encounter post-mortem
app.post('/api/dm/encounter-postmortem', async (c) => {
try {
const body = await c.req.json<Record<string, unknown>>();
const combatLog = (body.combatLog as string[]) || [];
const chars = (body.characters as Array<Record<string, unknown>>) || [];
if (combatLog.length < 3) return c.json({ analysis: '' });
const names = chars.map((ch) => `${ch.name} (${ch.class})`).join(', ');
const text = await aiText(c.env, [
{ role: 'system', content: 'D&D tactical analyst. Brief, specific.' },
{ role: 'user', content: `Analyze combat. Party: ${names}.\nLog:\n${combatLog.slice(-25).join('\n')}\n\n3-4 bullets: what went well, what went wrong, tactical tips.` },
], 300);
return c.json({ analysis: text.trim() });
} catch { return c.json({ analysis: '' }); }
});
// Quick NPC generator
app.get('/api/dm/random-npc', async (c) => {
try {
const text = await aiText(c.env, [
{ role: 'system', content: 'D&D NPC generator. Return valid JSON only.' },
{ role: 'user', content: 'Generate a random D&D NPC. JSON: {"name":"Name","race":"Race","class":"Class or trade","personality":"2-3 words","quirk":"One quirk","motivation":"What they want"}' },
], 150);
const match = text.match(/\{[\s\S]*\}/);
return c.json({ npc: match ? JSON.parse(match[0]) : null });
} catch { return c.json({ npc: null }); }
});
// AI map cell description — describe what the party sees at a location
app.post('/api/dm/describe-cell', async (c) => {
try {
const body = await c.req.json<Record<string, unknown>>();
const terrain = String(body.terrain || 'floor');
const lighting = String(body.lighting || 'normal');
const scene = String(body.sceneName || '');
const prompt = `In 1-2 vivid sentences, describe a ${terrain} area${lighting !== 'normal' ? ` (${lighting} lighting)` : ''}${scene ? ` in ${scene}` : ''}. What does the party see, hear, smell? No game mechanics.`;
const text = await aiText(c.env, [{ role: 'system', content: 'D&D narrator. Brief, vivid.' }, { role: 'user', content: prompt }], 100);
return c.json({ description: text.trim() });
} catch { return c.json({ description: '' }); }
});
// AI backend status
app.get('/api/ai/status', (c) => {
return c.json(aiStatus(aiEnv(c.env)));
});
app.get('/api/auth/discord', (c) => {
const redirect_uri = DISCORD_REDIRECT_URIS.find((uri) => c.req.url.startsWith(uri.split('/api')[0])) || DISCORD_REDIRECT_URIS[0];
const params = new URLSearchParams({
client_id: c.env.DISCORD_CLIENT_ID,
redirect_uri,
response_type: 'code',
scope: 'identify email',
prompt: 'consent',
});
return c.redirect(`${DISCORD_AUTH_URI}?${params.toString()}`);
});
// GET /api/auth/discord/callback - exchange code for token, set JWT cookie
app.get('/api/auth/discord/callback', async (c) => {
const url = new URL(c.req.url);
const code = url.searchParams.get('code');
if (!code) return c.text('Missing code', 400);
const redirect_uri = DISCORD_REDIRECT_URIS.find((uri) => c.req.url.startsWith(uri.split('/api')[0])) || DISCORD_REDIRECT_URIS[0];
const tokenRes = await fetch(DISCORD_TOKEN_URI, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
code,
client_id: c.env.DISCORD_CLIENT_ID,
client_secret: c.env.DISCORD_CLIENT_SECRET,
redirect_uri,
grant_type: 'authorization_code',
scope: 'identify email',
}),
});
const tokenData: Record<string, string> = await tokenRes.json();
if (!tokenData.access_token) return c.text('Failed to get token', 400);
const userRes = await fetch(DISCORD_USERINFO_URI, {
headers: { Authorization: `Bearer ${tokenData.access_token}` },
});
const user = await userRes.json();
const jwt = await new SignJWT({ user, provider: 'discord' }).setProtectedHeader({ alg: 'HS256' }).setIssuedAt().setExpirationTime('7d').sign(getJwtKey(c.env));
// No Secure flag so cookies work on localhost HTTP during dev
c.header('Set-Cookie', `${COOKIE_NAME}=${jwt}; Path=/; HttpOnly; SameSite=Lax; Max-Age=604800`);
return c.redirect('/');
});
// GET /api/auth/me - return current user from JWT cookie
app.get('/api/auth/me', async (c) => {
const cookie = c.req.header('Cookie') || '';
const match = cookie.match(new RegExp(`${COOKIE_NAME}=([^;]+)`));
if (!match) return c.json({ user: null });
try {
const { payload } = await jwtVerify(match[1], getJwtKey(c.env));
return c.json({ user: payload.user });
} catch {
return c.json({ user: null });
}
});
// GET /api/auth/signout - clear session cookie
app.get('/api/auth/signout', (c) => {
c.header('Set-Cookie', `${COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`);
return c.redirect('/');
});
// ── Google OAuth ──
// GET /api/auth/google - redirect to Google OAuth
app.get('/api/auth/google', (c) => {
if (!c.env.GOOGLE_CLIENT_ID) return c.text('Google OAuth not configured', 503);
const redirect_uri = GOOGLE_REDIRECT_URIS.find((uri) => c.req.url.startsWith(uri.split('/api')[0])) || GOOGLE_REDIRECT_URIS[0];
const params = new URLSearchParams({
client_id: c.env.GOOGLE_CLIENT_ID,
redirect_uri,
response_type: 'code',
scope: 'openid email profile',
access_type: 'offline',
prompt: 'consent',
});
return c.redirect(`${GOOGLE_AUTH_URI}?${params.toString()}`);
});
// GET /api/auth/google/callback - exchange code for token, set JWT cookie
app.get('/api/auth/google/callback', async (c) => {
if (!c.env.GOOGLE_CLIENT_ID || !c.env.GOOGLE_CLIENT_SECRET) return c.text('Google OAuth not configured', 503);
const url = new URL(c.req.url);
const code = url.searchParams.get('code');
if (!code) return c.text('Missing code', 400);
const redirect_uri = GOOGLE_REDIRECT_URIS.find((uri) => c.req.url.startsWith(uri.split('/api')[0])) || GOOGLE_REDIRECT_URIS[0];
const tokenRes = await fetch(GOOGLE_TOKEN_URI, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
code,
client_id: c.env.GOOGLE_CLIENT_ID,
client_secret: c.env.GOOGLE_CLIENT_SECRET,
redirect_uri,
grant_type: 'authorization_code',
}),
});
const tokenData: Record<string, string> = await tokenRes.json();
if (!tokenData.access_token) return c.text('Failed to get token', 400);
const userRes = await fetch(GOOGLE_USERINFO_URI, {
headers: { Authorization: `Bearer ${tokenData.access_token}` },
});
const googleUser = (await userRes.json()) as Record<string, string>;
// Normalize Google user to match our JWT format (compatible with Discord layout)
const user = {
id: googleUser.id,
username: googleUser.email?.split('@')[0] || googleUser.name || 'User',
global_name: googleUser.name || googleUser.email?.split('@')[0] || 'User',
email: googleUser.email,
avatar: null, // Google uses picture URL directly, not a hash
picture: googleUser.picture, // full URL to profile picture
};
const jwt = await new SignJWT({ user, provider: 'google' }).setProtectedHeader({ alg: 'HS256' }).setIssuedAt().setExpirationTime('7d').sign(getJwtKey(c.env));
c.header('Set-Cookie', `${COOKIE_NAME}=${jwt}; Path=/; HttpOnly; SameSite=Lax; Max-Age=604800`);
return c.redirect('/');
});
// GET /api/auth/github - redirect to GitHub OAuth
app.get('/api/auth/github', (c) => {
if (!c.env.GITHUB_CLIENT_ID) return c.text('GitHub OAuth not configured', 503);
const redirect_uri = GITHUB_REDIRECT_URIS.find((uri) => c.req.url.startsWith(uri.split('/api')[0])) || GITHUB_REDIRECT_URIS[0];
const params = new URLSearchParams({
client_id: c.env.GITHUB_CLIENT_ID,
redirect_uri,
scope: 'read:user user:email',
});
return c.redirect(`${GITHUB_AUTH_URI}?${params.toString()}`);
});
// GET /api/auth/github/callback - exchange code for token, set JWT cookie
app.get('/api/auth/github/callback', async (c) => {
if (!c.env.GITHUB_CLIENT_ID || !c.env.GITHUB_CLIENT_SECRET) return c.text('GitHub OAuth not configured', 503);
const url = new URL(c.req.url);
const code = url.searchParams.get('code');
if (!code) return c.text('Missing code', 400);
const redirect_uri = GITHUB_REDIRECT_URIS.find((uri) => c.req.url.startsWith(uri.split('/api')[0])) || GITHUB_REDIRECT_URIS[0];
const tokenRes = await fetch(GITHUB_TOKEN_URI, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({
code,
client_id: c.env.GITHUB_CLIENT_ID,
client_secret: c.env.GITHUB_CLIENT_SECRET,
redirect_uri,
}),
});
const tokenData: Record<string, string> = await tokenRes.json();
if (!tokenData.access_token) return c.text('Failed to get token', 400);
const userRes = await fetch(GITHUB_USERINFO_URI, {
headers: { Authorization: `Bearer ${tokenData.access_token}`, 'User-Agent': 'Adventure-VTT' },
});
const ghUser = (await userRes.json()) as Record<string, unknown>;
const user = {
id: String(ghUser.id),
username: String(ghUser.login || 'User'),
global_name: String(ghUser.name || ghUser.login || 'User'),
email: String(ghUser.email || ''),
avatar: null,
picture: String(ghUser.avatar_url || ''),
};
const jwt = await new SignJWT({ user, provider: 'github' }).setProtectedHeader({ alg: 'HS256' }).setIssuedAt().setExpirationTime('7d').sign(getJwtKey(c.env));
c.header('Set-Cookie', `${COOKIE_NAME}=${jwt}; Path=/; HttpOnly; SameSite=Lax; Max-Age=604800`);
return c.redirect('/');
});
// Portrait generation via Workers AI
// Art style prompts — matched to frontend PORTRAIT_STYLES ids
const ART_STYLE_PROMPTS: Record<string, string> = {
'classic-fantasy': 'Detailed oil painting, medieval fantasy illustration, rich earth tones, dramatic chiaroscuro lighting, high fantasy RPG art',
watercolor: 'Soft watercolor painting with gentle washes, flowing lines, muted pastel palette, delicate brushwork, fantasy illustration',
'anime-fantasy': 'Anime-inspired fantasy art, vibrant saturated colors, expressive features, clean lines, dynamic composition, light cel-shading',
'dark-gothic': 'Dark gothic illustration, heavy shadows, dramatic contrast, muted desaturated palette, ornate details, grim and foreboding atmosphere',
storybook: 'Whimsical hand-drawn storybook illustration, warm soft lighting, cozy atmosphere, rounded shapes, gentle color palette',
'cel-shaded': 'Bold cel-shaded art, clean sharp outlines, flat vibrant colors, graphic novel style, strong silhouettes',
realistic: 'Photorealistic digital portrait, cinematic lighting, subsurface scattering on skin, sharp detail, studio photography feel',
painterly: 'Loose impressionist brushwork, rich textures, dramatic palette knife strokes, visible paint texture, expressive color mixing',
};
function buildPortraitPrompt(char: Record<string, unknown>): string {
const race = String(char.race || 'Human');
const cls = String(char.class || 'Fighter');
const name = String(char.name || 'Adventurer');
const stats = (char.stats || {}) as Record<string, number>;
const style = String(char.style || 'classic-fantasy');
const appearance = (char.appearance || {}) as Record<string, unknown>;
// Describe physique from stats
const physique: string[] = [];
if (stats.STR >= 16) physique.push('powerfully muscular');
else if (stats.STR <= 8) physique.push('slight and thin');
if (stats.DEX >= 16) physique.push('graceful and agile');
if (stats.CON >= 16) physique.push('hardy and robust');
else if (stats.CON <= 8) physique.push('frail-looking');
if (stats.INT >= 16) physique.push('with sharp, intelligent eyes');
if (stats.WIS >= 16) physique.push('with a calm, knowing gaze');
if (stats.CHA >= 16) physique.push('strikingly attractive');
// Appearance details (hair style, scars, markings)
const appearanceDetails: string[] = [];
if (appearance.hairStyle && appearance.hairStyle !== 'short') {
appearanceDetails.push(`${appearance.hairStyle} hair`);
}
if (appearance.scar && appearance.scar !== 'none') {
const scarName = String(appearance.scar).replace(/-/g, ' ');
appearanceDetails.push(`a ${scarName} scar`);
}
if (appearance.faceMarking && appearance.faceMarking !== 'none') {
const markingName = String(appearance.faceMarking).replace(/-/g, ' ');
appearanceDetails.push(`${markingName} face markings`);
}
if (appearance.facialHair && appearance.facialHair !== 'none') {
const fhName = String(appearance.facialHair).replace(/-/g, ' ');
appearanceDetails.push(`a ${fhName}`);
}
// Race-specific features
const raceTraits: Record<string, string> = {
Human: 'a human with varied features',
Elf: 'an elf with pointed ears, angular features, and an ethereal quality',
Dwarf: 'a stout dwarf with a thick beard and broad shoulders',
Halfling: 'a small halfling with a round, cheerful face and curly hair',
Gnome: 'a small gnome with an oversized head and curious, twinkling eyes',
'Half-Orc': 'a half-orc with greenish skin, prominent tusks, and a strong jaw',
Tiefling: 'a tiefling with reddish skin, curved horns, and a long tail',
Dragonborn: 'a dragonborn with scaled skin, a draconic snout, and no hair',
};
// Class-specific attire/vibe
const classAttire: Record<string, string> = {
Fighter: 'wearing practical plate armor with a sword at their hip',
Wizard: 'wearing flowing robes with arcane symbols, holding a staff',
Rogue: 'wearing dark leather armor with a hood and daggers',
Cleric: 'wearing polished chainmail with a holy symbol around their neck',
Ranger: 'wearing green-brown leathers with a longbow and a forest cloak',
Paladin: 'wearing gleaming full plate with a radiant holy emblem on their shield',
Barbarian: 'bare-chested with war paint, furs, and a massive greataxe',
Bard: 'wearing colorful, stylish clothes with a lute slung over their shoulder',
Sorcerer: 'with faintly glowing eyes and arcane energy crackling at their fingertips',
Warlock: 'wearing dark, otherworldly robes with an eldritch sigil on their hand',
Druid: 'wearing natural hide armor adorned with leaves and a wooden staff',
Monk: 'wearing simple wraps and a serene expression, hands in a fighting stance',
};
const raceTrait = raceTraits[race] || 'a fantasy adventurer';
const attire = classAttire[cls] || 'in adventuring gear';
const physiqueStr = physique.length > 0 ? `, ${physique.join(', ')}` : '';
const appearanceStr = appearanceDetails.length > 0 ? `, with ${appearanceDetails.join(', ')}` : '';
const artStyle = ART_STYLE_PROMPTS[style] || ART_STYLE_PROMPTS['classic-fantasy'];
return `Fantasy character portrait of ${name}, ${raceTrait}${physiqueStr}${appearanceStr}, ${attire}. Upper body portrait, dark atmospheric background. ${artStyle}.`;
}
app.post('/api/portrait/generate', async (c) => {
if (!c.env.AI) {
return c.json({ error: 'AI binding not available' }, 503);
}
const body = await c.req.json<Record<string, unknown>>();
const prompt = buildPortraitPrompt(body);
try {
const result = await aiImage(aiEnv(c.env), prompt);
if (result) return c.json({ portrait: result.base64, prompt, backend: result.backend });
return c.json({ error: 'No image generation backend available' }, 503);
} catch (err: unknown) {
return c.json({ error: err instanceof Error ? err.message : 'Portrait generation failed' }, 500);
}
});
// AI enemy token portrait — generates a combat-themed portrait for an enemy
app.post('/api/portrait/enemy', async (c) => {
if (!c.env.AI) return c.json({ error: 'AI binding not available' }, 503);
try {
const body = await c.req.json<{ name?: string; description?: string }>();
const name = String(body.name || 'Monster');
const desc = String(body.description || '').slice(0, 200);
const prompt = `Fantasy RPG enemy portrait, circular token style, dark dramatic lighting, detailed face. ${name}: ${desc}. Digital painting, high detail, menacing expression, battle-ready pose. No text, no frame, centered composition.`;
const result = await aiImage(aiEnv(c.env), prompt);
if (result) return c.json({ portrait: result.base64 });
return c.json({ error: 'No image generation backend available' }, 503);
} catch (err) {
return c.json({ error: err instanceof Error ? err.message : 'AI generation failed' }, 500);
}
});
// Name translation — translate a name's meaning into a random language via Workers AI
const NAME_LANGUAGES = [
{ name: 'Spanish', flag: '\u{1F1EA}\u{1F1F8}' },
{ name: 'French', flag: '\u{1F1EB}\u{1F1F7}' },
{ name: 'German', flag: '\u{1F1E9}\u{1F1EA}' },
{ name: 'Italian', flag: '\u{1F1EE}\u{1F1F9}' },
{ name: 'Portuguese', flag: '\u{1F1E7}\u{1F1F7}' },
{ name: 'Japanese', flag: '\u{1F1EF}\u{1F1F5}' },
{ name: 'Korean', flag: '\u{1F1F0}\u{1F1F7}' },
{ name: 'Mandarin Chinese', flag: '\u{1F1E8}\u{1F1F3}' },
{ name: 'Russian', flag: '\u{1F1F7}\u{1F1FA}' },
{ name: 'Arabic', flag: '\u{1F1F8}\u{1F1E6}' },
{ name: 'Hindi', flag: '\u{1F1EE}\u{1F1F3}' },
{ name: 'Turkish', flag: '\u{1F1F9}\u{1F1F7}' },
{ name: 'Polish', flag: '\u{1F1F5}\u{1F1F1}' },
{ name: 'Swedish', flag: '\u{1F1F8}\u{1F1EA}' },
{ name: 'Norwegian', flag: '\u{1F1F3}\u{1F1F4}' },
{ name: 'Finnish', flag: '\u{1F1EB}\u{1F1EE}' },
{ name: 'Dutch', flag: '\u{1F1F3}\u{1F1F1}' },
{ name: 'Greek', flag: '\u{1F1EC}\u{1F1F7}' },
{ name: 'Irish', flag: '\u{1F1EE}\u{1F1EA}' },
{ name: 'Welsh', flag: '\u{1F3F4}\u{E0067}\u{E0062}\u{E0077}\u{E006C}\u{E0073}\u{E007F}' },
{ name: 'Swahili', flag: '\u{1F1F0}\u{1F1EA}' },
{ name: 'Thai', flag: '\u{1F1F9}\u{1F1ED}' },
{ name: 'Vietnamese', flag: '\u{1F1FB}\u{1F1F3}' },
{ name: 'Hebrew', flag: '\u{1F1EE}\u{1F1F1}' },
{ name: 'Latin', flag: '\u{1F3DB}\u{FE0F}' },
{ name: 'Hawaiian', flag: '\u{1F1FA}\u{1F1F8}' },
{ name: 'Maori', flag: '\u{1F1F3}\u{1F1FF}' },
{ name: 'Icelandic', flag: '\u{1F1EE}\u{1F1F8}' },
{ name: 'Romanian', flag: '\u{1F1F7}\u{1F1F4}' },
{ name: 'Czech', flag: '\u{1F1E8}\u{1F1FF}' },
];
app.post('/api/name/translate', async (c) => {
if (!c.env.AI) {
return c.json({ error: 'AI binding not available' }, 503);
}
const body = await c.req.json<{ name: string; language?: string }>();
const name = String(body.name || '').trim();
if (!name) return c.json({ error: 'Name is required' }, 400);
// Pick a random language or use the one specified
const lang = body.language ? NAME_LANGUAGES.find((l) => l.name.toLowerCase() === body.language!.toLowerCase()) || NAME_LANGUAGES[Math.floor(Math.random() * NAME_LANGUAGES.length)] : NAME_LANGUAGES[Math.floor(Math.random() * NAME_LANGUAGES.length)];
const prompt = `Translate the meaning of the English word or name "${name}" into ${lang.name}. If the name is a compound word or has a clear meaning (like "Lumberjack" = one who cuts wood), translate that meaning. If it's a proper name with no obvious meaning, transliterate it into ${lang.name} phonetics. Return ONLY the single translated/transliterated word or short phrase in ${lang.name} script or romanized form — nothing else, no quotes, no explanation.`;
try {
const raw = (await aiText(c.env, [
{ role: 'system', content: 'You are a precise translator. Return ONLY the translated word. No quotes, no punctuation, no explanation. Just the word.' },
{ role: 'user', content: prompt },
], 50)).trim();
// Clean up: remove quotes, periods, extra whitespace, "Translation:" prefixes
const translated = raw
.replace(/^["'`]+|["'`.,!]+$/g, '')
.replace(/^(translation|answer|result)[:\s]*/i, '')
.trim();
if (!translated) return c.json({ error: 'Translation returned empty' }, 500);
return c.json({ translated, language: lang.name, flag: lang.flag, original: name });
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : 'Translation failed';
return c.json({ error: msg }, 500);
}
});
// AI full character generator — creative builds, not generic
app.post('/api/character/generate', async (c) => {
if (!c.env.AI) {
return c.json({ error: 'AI binding not available' }, 503);
}
const body = await c.req.json<{ campaign?: string }>();
const campaign = String(body.campaign || '').trim();
const campaignCtx = campaign ? `\nCAMPAIGN CONTEXT (tailor the character to fit this setting):\n${campaign}\n` : '';
const prompt = `Generate a COMPLETE, UNIQUE D&D 5e character concept. Return ONLY valid JSON, no markdown fences.
${campaignCtx}
RULES FOR INTERESTING BUILDS:
- Create UNEXPECTED but VIABLE race/class combos. Not "elf wizard" or "dwarf fighter". Think: gnome barbarian who channels rage through unhinged cackling. Tiefling paladin oath-bound to a trickster god. Half-orc bard whose instrument is a warhammer beaten against a shield. Dragonborn monk raised by a pacifist monastery who breathes fire when their vows crack.
- Background should ADD A TWIST, not just reinforce the class. A noble rogue. A criminal cleric. An entertainer barbarian.
- statPriority should be optimized for the build — list the 6 ability scores from most to least important.
- personalityTraits should be SPECIFIC and VIVID with concrete behaviors, not vague.
- ideals/bonds/flaws should create dramatic tension and RP hooks.
- backstory: 2-4 paragraphs. Must include a NAMED NPC, a SPECIFIC inciting incident, a SENSORY DETAIL, and an UNRESOLVED MYSTERY. No cliche openings ("Born in...", "From a young age..."). Third person past tense.
- name should be original and fitting for the race.
VALID VALUES:
- race: Human, Elf, Dwarf, Halfling, Gnome, Half-Orc, Tiefling, Dragonborn
- class: Fighter, Barbarian, Paladin, Ranger, Rogue, Monk, Cleric, Bard, Druid, Warlock, Wizard, Sorcerer
- background: Acolyte, Charlatan, Criminal, Entertainer, Folk Hero, Guild Artisan, Hermit, Noble, Outlander, Sage, Sailor, Soldier, Urchin
- alignment: Lawful Good, Neutral Good, Chaotic Good, Lawful Neutral, True Neutral, Chaotic Neutral, Lawful Evil, Neutral Evil, Chaotic Evil
- hairStyle: short, long, braided, mohawk, bald, wild
- scar: none, eye-scar, cheek-slash, forehead-mark
- faceMarking: none, tribal-lines, arcane-runes, war-paint, freckles
- facialHair: none, beard, goatee, mustache, stubble
JSON format:
{"name":"...","race":"...","class":"...","background":"...","alignment":"...","statPriority":["CHA","DEX","CON","WIS","INT","STR"],"personalityTraits":"...","ideals":"...","bonds":"...","flaws":"...","backstory":"...","appearance":{"hairStyle":"...","scar":"...","faceMarking":"...","facialHair":"..."},"concept":"one sentence pitch for this character"}`;
try {
const raw = (await aiText(c.env, [
{ role: 'system', content: 'You are a wildly creative D&D character designer. You hate boring builds. Every character should make a DM grin. Return ONLY valid JSON. No markdown. No explanation. No code fences.' },
{ role: 'user', content: prompt },
], 1200)).trim();
const jsonMatch = raw.match(/\{[\s\S]*\}/);
if (jsonMatch) {
const parsed = JSON.parse(jsonMatch[0]);
return c.json(parsed);
}
return c.json({ error: 'Failed to parse character concept', raw }, 500);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : 'Character generation failed';
return c.json({ error: msg }, 500);
}
});
// AI personality generator — personality traits + ideals + bonds + flaws as a group
app.post('/api/character/suggest-personality', async (c) => {
if (!c.env.AI) {
return c.json({ error: 'AI binding not available' }, 503);
}
const body = await c.req.json<Record<string, unknown>>();
const name = String(body.name || 'an adventurer');
const race = String(body.race || 'Human');
const cls = String(body.class || 'Fighter');
const bg = String(body.background || 'Folk Hero');
const alignment = String(body.alignment || 'True Neutral');
const backstory = String(body.backstory || '');
const backstoryCtx = backstory ? `\nTheir backstory: ${backstory.slice(0, 500)}` : '';
const prompt = `Generate personality details for ${name}, a ${race} ${cls} with the ${bg} background (${alignment}).${backstoryCtx}
Return ONLY valid JSON with these 4 fields:
- personalityTraits: 1-2 specific behavioral traits (not vague — concrete habits, tics, ways they talk or act)
- ideals: what drives them, what principle they'd die for
- bonds: who or what they're tied to, what they protect, who they owe
- flaws: a real weakness — not "I'm too brave". Something that causes actual problems.
Make these INTERESTING and SPECIFIC to this character. Create dramatic tension. A paladin whose flaw undermines their oath. A rogue whose bond is to the law. Contradict the obvious.
JSON only, no markdown fences:
{"personalityTraits":"...","ideals":"...","bonds":"...","flaws":"..."}`;
try {
const raw = (await aiText(c.env, [
{ role: 'system', content: 'You write vivid, specific D&D character personality details. Return ONLY valid JSON. No markdown. No explanation.' },
{ role: 'user', content: prompt },
], 400)).trim();
const jsonMatch = raw.match(/\{[\s\S]*\}/);
if (jsonMatch) {
const parsed = JSON.parse(jsonMatch[0]);
return c.json(parsed);
}
return c.json({ error: 'Failed to parse personality', raw }, 500);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : 'Personality generation failed';
return c.json({ error: msg }, 500);
}
});
// AI Backstory generator — creates unique, non-generic character origins
app.post('/api/backstory/generate', async (c) => {
if (!c.env.AI) {
return c.json({ error: 'AI binding not available' }, 503);
}
const body = await c.req.json<Record<string, unknown>>();
const name = String(body.name || 'a nameless wanderer');
const race = String(body.race || 'Human');
const cls = String(body.class || 'Fighter');
const bg = String(body.background || 'Folk Hero');
const alignment = String(body.alignment || 'True Neutral');
const stats = (body.stats || {}) as Record<string, number>;
const personalityTraits = String(body.personalityTraits || '');
const ideals = String(body.ideals || '');
const bonds = String(body.bonds || '');
const flaws = String(body.flaws || '');
// Build stat-derived personality hints
const statHints: string[] = [];
if (stats.STR >= 16) statHints.push('physically imposing');
else if (stats.STR <= 8) statHints.push('physically weak');
if (stats.INT >= 16) statHints.push('brilliantly intelligent');
else if (stats.INT <= 8) statHints.push('not book-smart');
if (stats.WIS >= 16) statHints.push('deeply perceptive');
if (stats.CHA >= 16) statHints.push('magnetically charismatic');
else if (stats.CHA <= 8) statHints.push('socially awkward');
if (stats.CON >= 16) statHints.push('unnaturally resilient');
else if (stats.CON <= 8) statHints.push('sickly or frail');
const traitContext = [personalityTraits && `Personality: ${personalityTraits}`, ideals && `Ideals: ${ideals}`, bonds && `Bonds: ${bonds}`, flaws && `Flaws: ${flaws}`].filter(Boolean).join('\n');
const prompt = `Write a backstory for a D&D character. 2-4 paragraphs, vivid and specific.
Character: ${name}, a ${race} ${cls} with a ${bg} background. Alignment: ${alignment}.
${statHints.length > 0 ? `They are ${statHints.join(', ')}.` : ''}
${traitContext ? `\n${traitContext}` : ''}
CRITICAL RULES — follow these or the backstory is garbage:
- NO generic origins. Not "you were a street urchin who learned to fight." Not "a wizard who studied in a tower." Not "a rogue from the thieves guild." Those are boring.
- Give them a SPECIFIC inciting incident that changed everything. A moment, a betrayal, a discovery, an accident.
- Include at least one NAMED person from their past (a mentor, rival, lost love, enemy, sibling — someone specific).
- Include a SENSORY DETAIL — a smell, a sound, a texture that haunts them or brings them comfort.
- Their class/background should inform the story but NOT define it predictably. A fighter doesn't have to come from military. A druid doesn't have to come from the forest. Subvert expectations.
- Weave in a MYSTERY or UNRESOLVED THREAD — something the character doesn't know or hasn't settled. A DM can hook into this.
- Write in third person past tense. Tone: literary fantasy, not dry encyclopedia.
- Do NOT start with "Born in" or "From a young age" or any cliche opening.`;
try {
const backstory = (await aiText(c.env, [
{ role: 'system', content: 'You are a fantasy author who writes compelling, original character backstories. You hate cliches. You love specificity, emotional hooks, and stories that make a DM excited to build on them. Never be generic. Every character deserves to be interesting.' },
{ role: 'user', content: prompt },
], 800)).trim();
if (!backstory) {
return c.json({ error: 'AI returned empty backstory' }, 500);
}
return c.json({ backstory });
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : 'Backstory generation failed';
return c.json({ error: msg }, 500);
}
});
// Backstory continuation — "what happened next" story beats
app.post('/api/backstory/continue', async (c) => {
try {
const body = await c.req.json<Record<string, unknown>>();
const name = String(body.name || 'Adventurer');
const cls = String(body.class || 'Fighter');
const backstory = String(body.backstory || '');
const recentEvents = (body.recentEvents as string[]) || [];
if (!backstory) return c.json({ continuation: '' });
const eventsCtx = recentEvents.length > 0 ? `\nRecent events:\n${recentEvents.slice(-10).join('\n')}` : '';
const text = await aiText(c.env, [
{ role: 'system', content: 'You are a fantasy author writing the next chapter of a D&D character\'s story. 2-3 paragraphs. Build on existing backstory and recent adventures. Include a new hook or unresolved thread.' },
{ role: 'user', content: `Character: ${name}, ${cls}.\n\nExisting backstory:\n${backstory.slice(0, 1000)}${eventsCtx}\n\nWrite what happened next — a new story beat that advances their personal arc.` },
], 500);
return c.json({ continuation: text.trim() });
} catch { return c.json({ continuation: '' }); }
});
// AI Dungeon Master — narration, encounters, NPC dialogue via Workers AI text generation
app.post('/api/dm/narrate', async (c) => {
if (!c.env.AI) {
return c.json({ error: 'AI binding not available' }, 503);
}
const body = await c.req.json<Record<string, unknown>>();
const characters = (body.characters as Array<Record<string, unknown>>) || [];
const context = String(body.context || '');
const action = String(body.action || '');
const history = (body.history as string[]) || [];
const scene = String(body.scene || '');
const personality = String(body.personality || 'theatrical');
// Build rich character descriptions with personality and backstory
const charDescriptions = characters
.map((ch) => {
const stats = (ch.stats || {}) as Record<string, number>;
const lines = [`${ch.name} — Level ${ch.level} ${ch.race} ${ch.class} (${ch.alignment || 'Neutral'}, ${ch.background || 'Unknown'} background)`, ` HP ${ch.hp}/${ch.maxHp}, AC ${ch.ac}, STR ${stats.STR || 10} DEX ${stats.DEX || 10} CON ${stats.CON || 10} INT ${stats.INT || 10} WIS ${stats.WIS || 10} CHA ${stats.CHA || 10}`, ` Condition: ${ch.condition || 'normal'}`];
if (ch.appearanceDescription) lines.push(` Appearance: ${ch.appearanceDescription}`);
if (ch.personalityTraits) lines.push(` Personality: ${ch.personalityTraits}`);
if (ch.ideals) lines.push(` Ideals: ${ch.ideals}`);
if (ch.bonds) lines.push(` Bonds: ${ch.bonds}`);
if (ch.flaws) lines.push(` Flaws: ${ch.flaws}`);
if (ch.backstory) lines.push(` Backstory (brief): ${String(ch.backstory).slice(0, 200)}`);
return lines.join('\n');
})
.join('\n\n');
const historyStr = history.length > 0 ? `\nRecent events:\n${history.slice(-10).join('\n')}` : '';
// Personality-specific DM styles
const DM_PERSONALITIES: Record<string, string> = {
theatrical: 'You are a master Dungeon Master — theatrical, unpredictable, and deeply immersive.',
comedic: 'You are a hilariously witty Dungeon Master — every situation has a punchline, NPCs are absurd, and the world is full of cosmic irony. You still take combat seriously but everything else gets the Terry Pratchett treatment.',
grimdark: 'You are a grim, relentless Dungeon Master — the world is harsh, resources are scarce, and hope is a luxury. Every victory has a cost. NPCs have dark secrets. Nature is hostile. Describe suffering, decay, and moral dilemmas with unflinching detail.',
tolkien: 'You are an epic, literary Dungeon Master in the style of Tolkien — grand landscapes, ancient languages, deep lore, and a sense of mythic destiny. NPCs speak with gravitas. Trees have souls. Describe the weight of ages and the beauty of forgotten kingdoms.',
noir: 'You are a hardboiled noir Dungeon Master — cynical inner monologue, rain-slicked streets, everyone has an angle, trust nobody. NPCs talk in clipped sentences and smoke too much. Describe shadows, silhouettes, and moral ambiguity.',
horror: 'You are a psychological horror Dungeon Master — slow dread, unreliable senses, things that are almost but not quite right. NPCs smile too wide. Doors appear where there were none. Describe the wrongness of everything with clinical precision.',
};
const personalityPrompt = DM_PERSONALITIES[personality] || DM_PERSONALITIES.theatrical;
const systemPrompt = `${personalityPrompt} You narrate a D&D 5e adventure in vivid second-person prose.
RULES:
- 2-4 sentences per response. Dense with sensory detail — sounds, smells, textures, light.
- Name every NPC. Give them a quirk, a voice, a motivation. "The barkeep" is lazy writing. "Marta Ashwick, the one-armed barkeep who hums battle hymns while she pours" is good.
- Subvert expectations. The chest is already open. The goblin wants to negotiate. The king is a fraud.
- React to WHO these characters are. A chaotic rogue and a lawful paladin experience the same tavern differently.
- When players have low HP or harsh conditions, reflect it — they limp, bleed, struggle.
- During combat, describe it cinematically with specific body language and impact.
- Never break character. Never mention rules, dice, or game mechanics.
THE PARTY:
${charDescriptions || 'A lone wanderer with no name.'}
${historyStr}
${scene ? `\nCurrent location: ${scene}` : ''}
${context ? `\nScene context: ${context}` : ''}`;
try {
const response = await aiText(c.env, [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: action || 'Set the scene for the beginning of a new adventure. The party gathers at a tavern.' },
], 400);
return c.json({ narration: response.trim() });
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : 'DM narration failed';
return c.json({ error: msg }, 500);
}
});
// AI DM narration — streaming SSE variant for typewriter effect
app.post('/api/dm/narrate-stream', async (c) => {
if (!c.env.AI) return c.json({ error: 'AI binding not available' }, 503);
try {
const body = await c.req.json<Record<string, unknown>>();
const characters = (body.characters as Array<Record<string, unknown>>) || [];
const context = String(body.context || '');
const action = String(body.action || '');
const history = (body.history as string[]) || [];
const scene = String(body.scene || '');
const personality = String(body.personality || 'theatrical');
const charDescriptions = characters.map((ch) => `${ch.name} — Level ${ch.level} ${ch.race} ${ch.class}`).join(', ');
const historyStr = history.length > 0 ? `\nRecent: ${history.slice(-5).join(' | ')}` : '';
const DM_PERSONALITIES: Record<string, string> = {
theatrical: 'theatrical, unpredictable, deeply immersive',
comedic: 'witty, absurd NPCs, cosmic irony',
grimdark: 'grim, scarce resources, every victory has cost',
tolkien: 'epic landscapes, ancient languages, mythic destiny',
noir: 'hardboiled, rain-slicked, trust nobody',
horror: 'slow dread, unreliable senses, clinical wrongness',
};
const style = DM_PERSONALITIES[personality] || DM_PERSONALITIES.theatrical;
const systemPrompt = `You are a ${style} D&D DM. 2-4 vivid sentences. Party: ${charDescriptions}.${scene ? ` Scene: ${scene}.` : ''}${historyStr}${context ? `\n${context}` : ''}`;
const stream = await aiChatStream(
aiEnv(c.env),
[{ role: 'system', content: systemPrompt }, { role: 'user', content: action || 'Set the scene.' }],
400,
);
return new Response(stream as ReadableStream, {
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' },
});
} catch (err) {
return c.json({ error: err instanceof Error ? err.message : 'Stream failed' }, 500);
}
});
// AI NPC dialogue — speak as a specific NPC in character
app.post('/api/dm/npc', async (c) => {
if (!c.env.AI) {
return c.json({ error: 'AI binding not available' }, 503);
}
const body = await c.req.json<Record<string, unknown>>();
const npcName = String(body.npcName || 'the stranger');
const npcRole = String(body.npcRole || 'a mysterious figure');
const npcPersonality = String(body.npcPersonality || '');
const playerMessage = String(body.playerMessage || '');
const playerName = String(body.playerName || 'Adventurer');
const playerClass = String(body.playerClass || '');
const scene = String(body.scene || '');
const roomId = String(body.roomId || '');
const clientHistory = (body.dialogueHistory as string[]) || [];
// NPC memory: load persistent conversation history from KV (per NPC per campaign)
let persistedMemory: string[] = [];
const memoryKey = roomId ? `npc-memory:${roomId}:${npcName.toLowerCase().replace(/\s+/g, '-')}` : '';
if (memoryKey && c.env.CAMPAIGNS) {
try {
const raw = (await c.env.CAMPAIGNS.get(memoryKey)) as string | null;
if (raw) persistedMemory = JSON.parse(raw) as string[];
} catch { /* ok */ }
}
// Merge: persisted memory + client-sent history (deduped, last 12 entries)
const allHistory = [...persistedMemory];
for (const line of clientHistory) {
if (!allHistory.includes(line)) allHistory.push(line);
}
const history = allHistory.slice(-12);
const historyStr = history.length > 0 ? `\nConversation history (${npcName} remembers all of this):\n${history.join('\n')}` : '';
const systemPrompt = `You are ${npcName}, ${npcRole} in a D&D 5e world. Stay completely in character.
YOUR PERSONALITY: ${npcPersonality || "Guarded but not hostile. You know things you don't share freely."}
RULES:
- Speak ONLY as ${npcName}. No narration, no stage directions, no quotation marks around your speech.
- 1-3 sentences. Terse is better than rambling. Leave things unsaid.
- Have an agenda. You want something from the player, even if it's just to be left alone.
- React to who is talking to you. A ${playerClass || 'stranger'} named ${playerName} is addressing you.
- If they're rude, you can refuse to help. If they're clever, reward it. If they threaten you, react realistically.
- Use speech patterns that fit your role — a scholar uses different words than a thief.
${scene ? `\nSetting: ${scene}` : ''}
${historyStr}`;
try {
const response = await aiText(c.env, [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: playerMessage || `${playerName} approaches you.` },
], 200);
// Save updated NPC memory to KV (persist conversation across sessions)
if (memoryKey && c.env.CAMPAIGNS && response.trim()) {
const npcSlug = npcName.toLowerCase().replace(/\s+/g, '-');
const updatedMemory = [...history, `${playerName}: ${playerMessage}`, `${npcName}: ${response.trim()}`].slice(-20);
c.env.CAMPAIGNS.put(memoryKey, JSON.stringify(updatedMemory)).catch(() => {});
// Update NPC memory index
if (roomId) {
const idxKey = `npc-memory-index:${roomId}`;
c.env.CAMPAIGNS.get(idxKey).then((raw) => {
const idx: string[] = raw ? JSON.parse(raw as string) : [];
if (!idx.includes(npcSlug)) { idx.push(npcSlug); c.env.CAMPAIGNS!.put(idxKey, JSON.stringify(idx)).catch(() => {}); }
}).catch(() => {});
}
}
return c.json({ dialogue: response.trim(), npcName, memoryLength: history.length });
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : 'NPC dialogue failed';
return c.json({ error: msg }, 500);
}
});
// AI backstory hooks — generates narrative connections between party members
app.post('/api/dm/backstory-hooks', async (c) => {
if (!c.env.AI) return c.json({ error: 'AI binding not available' }, 503);
try {
const body = await c.req.json<Record<string, unknown>>();
const characters = (body.characters as Array<Record<string, unknown>>) || [];
if (characters.length < 2) return c.json({ error: 'Need at least 2 characters' }, 400);
const charSummaries = characters.map((ch) => {
const parts = [`${ch.name} — Level ${ch.level} ${ch.race} ${ch.class} (${ch.background || 'Unknown'} background)`];
if (ch.personalityTraits) parts.push(`Personality: ${ch.personalityTraits}`);
if (ch.bonds) parts.push(`Bonds: ${ch.bonds}`);
if (ch.backstory) parts.push(`Backstory: ${String(ch.backstory).slice(0, 200)}`);
return parts.join('. ');
}).join('\n\n');
const prompt = `Given these D&D 5e party members:\n\n${charSummaries}\n\nGenerate 3-5 narrative hooks that connect these characters. Each hook should:\n- Link 2+ characters through shared history, conflicting goals, or complementary abilities\n- Be 1-2 sentences, evocative and specific\n- Reference their races, classes, backgrounds, or personality traits\n- Create dramatic tension or cooperative opportunity\n\nFormat: Return ONLY a JSON array of strings, each string being one hook. No other text.`;
const response = { response: await aiText(c.env, [
{ role: 'system', content: 'You are a creative D&D narrative designer. Return valid JSON only.' },
{ role: 'user', content: prompt },
]) };
const text = response?.response || '[]';
// Extract JSON array from response (LLM may wrap in markdown code fences)
const jsonMatch = text.match(/\[[\s\S]*\]/);
const hooks: string[] = jsonMatch ? JSON.parse(jsonMatch[0]) : [];
return c.json({ hooks });
} catch (err) {
const msg = err instanceof Error ? err.message : 'Backstory hooks generation failed';
return c.json({ error: msg }, 500);
}
});
// D&D 5e XP thresholds per character level (DMG p82)
const XP_THRESHOLDS_BY_LEVEL: Record<number, { easy: number; medium: number; hard: number; deadly: number }> = {
1: { easy: 25, medium: 50, hard: 75, deadly: 100 },
2: { easy: 50, medium: 100, hard: 150, deadly: 200 },
3: { easy: 75, medium: 150, hard: 225, deadly: 400 },
4: { easy: 125, medium: 250, hard: 375, deadly: 500 },
5: { easy: 250, medium: 500, hard: 750, deadly: 1100 },
6: { easy: 300, medium: 600, hard: 900, deadly: 1400 },
7: { easy: 350, medium: 750, hard: 1100, deadly: 1700 },
8: { easy: 450, medium: 900, hard: 1400, deadly: 2100 },
9: { easy: 550, medium: 1100, hard: 1600, deadly: 2400 },
10: { easy: 600, medium: 1200, hard: 1900, deadly: 2800 },
11: { easy: 800, medium: 1600, hard: 2400, deadly: 3600 },
12: { easy: 1000, medium: 2000, hard: 3000, deadly: 4500 },
13: { easy: 1100, medium: 2200, hard: 3400, deadly: 5100 },
14: { easy: 1250, medium: 2500, hard: 3800, deadly: 5700 },
15: { easy: 1400, medium: 2800, hard: 4300, deadly: 6400 },
16: { easy: 1600, medium: 3200, hard: 4800, deadly: 7200 },
17: { easy: 2000, medium: 3900, hard: 5900, deadly: 8800 },
18: { easy: 2100, medium: 4200, hard: 6300, deadly: 9500 },
19: { easy: 2400, medium: 4900, hard: 7300, deadly: 10900 },
20: { easy: 2800, medium: 5700, hard: 8500, deadly: 12700 },
};
// NPC memory management — DM views/clears NPC conversation memories
app.get('/api/npc-memory/:roomId', async (c) => {
if (!c.env.CAMPAIGNS) return c.json({ memories: [] });
try {
const roomId = c.req.param('roomId');
// Load NPC memory index (maintained alongside individual memories)
const indexRaw = (await c.env.CAMPAIGNS.get(`npc-memory-index:${roomId}`)) as string | null;
const npcNames: string[] = indexRaw ? JSON.parse(indexRaw) : [];
const memories: Array<{ npcName: string; lineCount: number; lastLine?: string }> = [];
for (const name of npcNames) {
const raw = (await c.env.CAMPAIGNS.get(`npc-memory:${roomId}:${name}`)) as string | null;
if (raw) {
const lines = JSON.parse(raw) as string[];
memories.push({ npcName: name, lineCount: lines.length, lastLine: lines[lines.length - 1] });
}
}
return c.json({ memories });
} catch { return c.json({ memories: [] }); }
});