-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_worker.bundle
More file actions
1638 lines (1618 loc) · 54.2 KB
/
_worker.bundle
File metadata and controls
1638 lines (1618 loc) · 54.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
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
------formdata-undici-094990745100
Content-Disposition: form-data; name="metadata"
{"main_module":"functionsWorker-0.35070945937962517.js"}
------formdata-undici-094990745100
Content-Disposition: form-data; name="functionsWorker-0.35070945937962517.js"; filename="functionsWorker-0.35070945937962517.js"
Content-Type: application/javascript+module
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// api/archive.ts
async function onRequestGet(context) {
const { request, env } = context;
const url = new URL(request.url);
const page = parseInt(url.searchParams.get("page") || "1");
const limit = Math.min(parseInt(url.searchParams.get("limit") || "20"), 100);
const offset = (page - 1) * limit;
try {
const countResult = await env.DB.prepare(
"SELECT COUNT(*) as total FROM comics"
).first();
const total = countResult.total || 0;
const comics = await env.DB.prepare(
"SELECT day, prompt, model_a, model_b, r2_key_a, r2_key_b, created_at FROM comics ORDER BY day DESC LIMIT ? OFFSET ?"
).bind(limit, offset).all();
const days = comics.results.map((c) => c.day);
let voteResults = [];
if (days.length > 0) {
const votesQuery = await env.DB.prepare(
`SELECT day, variant, COUNT(*) as count FROM votes WHERE day IN (${days.map(() => "?").join(",")}) GROUP BY day, variant`
).bind(...days).all();
voteResults = votesQuery.results;
}
const items = comics.results.map((comic) => {
const dayVotes = voteResults.filter((v) => v.day === comic.day);
const votesA = dayVotes.find((v) => v.variant === "a")?.count || 0;
const votesB = dayVotes.find((v) => v.variant === "b")?.count || 0;
return {
day: comic.day,
title: comic.prompt,
models: {
a: comic.model_a,
b: comic.model_b
},
votes: {
a: votesA,
b: votesB
},
created: new Date(comic.created_at * 1e3).toISOString()
};
});
return Response.json({
page,
limit,
total,
totalPages: Math.ceil(total / limit),
items
});
} catch (err) {
console.error("Error fetching archive:", err);
return Response.json({
error: err.message || "Failed to fetch archive"
}, { status: 500 });
}
}
var init_archive = __esm({
"api/archive.ts"() {
"use strict";
init_functionsRoutes_0_692898257009851();
__name(onRequestGet, "onRequestGet");
}
});
// lib/encoding.ts
function arrayBufferToBase64(buffer) {
const bytes = new Uint8Array(buffer);
let binary = "";
const chunkSize = 32768;
for (let i = 0; i < bytes.length; i += chunkSize) {
const chunk = bytes.subarray(i, i + chunkSize);
binary += String.fromCharCode(...chunk);
}
return btoa(binary);
}
function base64ToArrayBuffer(base64) {
const binary = atob(base64.replace(/^data:[^;]+;base64,/, ""));
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i += 1) {
bytes[i] = binary.charCodeAt(i);
}
return bytes.buffer;
}
function normalizeContentType(key, fallback = "image/png") {
if (key.endsWith(".svg")) return "image/svg+xml";
if (key.endsWith(".jpg") || key.endsWith(".jpeg")) return "image/jpeg";
if (key.endsWith(".webp")) return "image/webp";
if (key.endsWith(".png")) return "image/png";
return fallback;
}
var init_encoding = __esm({
"lib/encoding.ts"() {
"use strict";
init_functionsRoutes_0_692898257009851();
__name(arrayBufferToBase64, "arrayBufferToBase64");
__name(base64ToArrayBuffer, "base64ToArrayBuffer");
__name(normalizeContentType, "normalizeContentType");
}
});
// api/day.ts
async function onRequestGet2(context) {
const { request, env } = context;
const url = new URL(request.url);
const day = url.searchParams.get("day");
if (!day || !/^\d{4}-\d{2}-\d{2}$/.test(day)) {
return Response.json({
error: "Invalid day. Use YYYY-MM-DD format."
}, { status: 400 });
}
try {
const comic = await env.DB.prepare(
"SELECT * FROM comics WHERE day = ?"
).bind(day).first();
if (!comic) {
return Response.json({
error: "No comic found for requested day",
day
}, { status: 404 });
}
const votes = await env.DB.prepare(
"SELECT variant, COUNT(*) as count FROM votes WHERE day = ? GROUP BY variant"
).bind(day).all();
const votesA = votes.results.find((v) => v.variant === "a")?.count || 0;
const votesB = votes.results.find((v) => v.variant === "b")?.count || 0;
const fileA = await env.COMICS_BUCKET.get(comic.r2_key_a);
const fileB = await env.COMICS_BUCKET.get(comic.r2_key_b);
if (!fileA || !fileB) {
return Response.json({
error: "Comic images not found",
day
}, { status: 500 });
}
const imageA = await fileA.arrayBuffer();
const imageB = await fileB.arrayBuffer();
const typeA = fileA.httpMetadata?.contentType || normalizeContentType(comic.r2_key_a);
const typeB = fileB.httpMetadata?.contentType || normalizeContentType(comic.r2_key_b);
return Response.json({
day,
title: comic.prompt,
variants: {
a: {
model: comic.model_a,
imageUrl: `data:${typeA};base64,${arrayBufferToBase64(imageA)}`,
votes: votesA,
script: comic.script_a
},
b: {
model: comic.model_b,
imageUrl: `data:${typeB};base64,${arrayBufferToBase64(imageB)}`,
votes: votesB,
script: comic.script_b
}
}
});
} catch (err) {
console.error("Error fetching day comic:", err);
return Response.json({
error: err.message || "Internal server error"
}, { status: 500 });
}
}
var init_day = __esm({
"api/day.ts"() {
"use strict";
init_functionsRoutes_0_692898257009851();
init_encoding();
__name(onRequestGet2, "onRequestGet");
}
});
// api/push-key.ts
async function onRequestGet3(context) {
const { env } = context;
const publicKey = env.VAPID_PUBLIC_KEY;
if (!publicKey) {
return Response.json({
error: "Push notifications are not configured on this environment"
}, { status: 404 });
}
return Response.json({ publicKey });
}
var init_push_key = __esm({
"api/push-key.ts"() {
"use strict";
init_functionsRoutes_0_692898257009851();
__name(onRequestGet3, "onRequestGet");
}
});
// api/subscribe.ts
async function onRequestPost(context) {
const { request, env } = context;
try {
const body = await request.json();
if (!body.endpoint || !body.keys?.p256dh || !body.keys?.auth) {
return Response.json({
error: "Invalid subscription data"
}, { status: 400 });
}
await env.DB.prepare(
"INSERT OR REPLACE INTO push_subscriptions (endpoint, p256dh, auth, created_at) VALUES (?, ?, ?, ?)"
).bind(
body.endpoint,
body.keys.p256dh,
body.keys.auth,
Math.floor(Date.now() / 1e3)
).run();
return Response.json({
success: true,
message: "Subscribed to daily comic notifications"
});
} catch (err) {
console.error("Error subscribing:", err);
return Response.json({
error: err.message || "Failed to subscribe"
}, { status: 500 });
}
}
async function onRequestDelete(context) {
const { request, env } = context;
try {
const body = await request.json();
if (!body.endpoint) {
return Response.json({
error: "Endpoint required"
}, { status: 400 });
}
await env.DB.prepare(
"DELETE FROM push_subscriptions WHERE endpoint = ?"
).bind(body.endpoint).run();
return Response.json({
success: true,
message: "Unsubscribed from notifications"
});
} catch (err) {
console.error("Error unsubscribing:", err);
return Response.json({
error: err.message || "Failed to unsubscribe"
}, { status: 500 });
}
}
var init_subscribe = __esm({
"api/subscribe.ts"() {
"use strict";
init_functionsRoutes_0_692898257009851();
__name(onRequestPost, "onRequestPost");
__name(onRequestDelete, "onRequestDelete");
}
});
// ../cast/characters.json
var characters_default;
var init_characters = __esm({
"../cast/characters.json"() {
characters_default = [
{
id: "robot",
name: "LLM Robot",
role: "probabilistic stick-figure robot",
description: "Square robot head with short antenna, expressive dot eyes, concise deadpan delivery.",
voice: "Technical, probabilistic, occasionally overconfident.",
visual_traits: [
"square head",
"single antenna",
"minimal stick body"
],
sample_image: "/cast/samples/robot.svg"
},
{
id: "engineer",
name: "Engineer",
role: "straight-man human developer",
description: "Standard stick figure with round head, neutral expression, practical posture.",
voice: "Curious, direct, often confused by the robot.",
visual_traits: [
"round head",
"plain stick body"
],
sample_image: "/cast/samples/engineer.svg"
},
{
id: "simon",
name: "Simon (BOFH)",
role: "system administrator",
description: "Stick figure with dark sunglasses and a coffee mug, slightly smug stance.",
voice: "Dry, sharp, one-line punchlines.",
visual_traits: [
"black sunglasses",
"coffee mug",
"deadpan posture"
],
sample_image: "/cast/samples/simon.svg"
},
{
id: "founder",
name: "Startup Founder",
role: "AI hype character",
description: "Animated stick figure gesturing with a marker near a fake growth chart.",
voice: "Buzzword-heavy, sales-pitch cadence.",
visual_traits: [
"energetic arm pose",
"simple trend arrow sketch"
],
sample_image: "/cast/samples/founder.svg"
},
{
id: "cat",
name: "The Cat",
role: "chaotic wildcard",
description: "Tiny line-drawn cat with upright tail and inconsistent gaze direction.",
voice: "No dialogue; visual chaos.",
visual_traits: [
"small triangular ears",
"upright tail",
"tiny silhouette"
],
sample_image: "/cast/samples/cat.svg"
}
];
}
});
// lib/cast.ts
function pickCharacters(rand, count) {
const pool = [...CAST];
const selected = [];
const max = Math.max(1, Math.min(count, pool.length));
for (let i = 0; i < max; i += 1) {
const idx = Math.floor(rand() * pool.length);
selected.push(pool[idx]);
pool.splice(idx, 1);
}
return selected;
}
var CAST;
var init_cast = __esm({
"lib/cast.ts"() {
"use strict";
init_functionsRoutes_0_692898257009851();
init_characters();
CAST = characters_default;
__name(pickCharacters, "pickCharacters");
}
});
// lib/agentic-comic-workflow.ts
var agentic_comic_workflow_exports = {};
__export(agentic_comic_workflow_exports, {
previewAgenticPromptPlan: () => previewAgenticPromptPlan,
runAgenticComicWorkflow: () => runAgenticComicWorkflow
});
async function previewAgenticPromptPlan(env, options) {
const workflowLog = [];
const plan = await buildComicPlan(env, options, workflowLog);
return {
...plan,
workflow_log: workflowLog
};
}
async function runAgenticComicWorkflow(env, options) {
const workflowLog = [];
const plan = await buildComicPlan(env, options, workflowLog);
const modelA = env.IMAGE_MODEL_A || DEFAULT_IMAGE_MODEL_A;
const modelB = env.IMAGE_MODEL_B || DEFAULT_IMAGE_MODEL_B;
const random = createSeededRng(hashToUInt32(`${plan.day}:${plan.run_id}:image-seeds`));
const seedA = randomInt(random, 1, 2147483600);
const seedB = randomInt(random, 1, 2147483600);
const variantA = await generateImageVariant(env, modelA, plan.prompt_a, seedA, workflowLog, "variant-a");
const variantB = await generateImageVariant(env, modelB, plan.prompt_b, seedB, workflowLog, "variant-b", modelA);
const imageKeyA = `comics/${plan.day}/a.png`;
const imageKeyB = `comics/${plan.day}/b.png`;
const artifactPrefix = `artifacts/${plan.day}/${plan.run_id}`;
await Promise.all([
env.COMICS_BUCKET.put(imageKeyA, variantA.image, { httpMetadata: { contentType: "image/png" } }),
env.COMICS_BUCKET.put(imageKeyB, variantB.image, { httpMetadata: { contentType: "image/png" } }),
env.COMICS_BUCKET.put(`${artifactPrefix}/workflow-log.json`, JSON.stringify(workflowLog, null, 2), { httpMetadata: { contentType: "application/json" } }),
env.COMICS_BUCKET.put(`${artifactPrefix}/cast.json`, JSON.stringify(plan.cast, null, 2), { httpMetadata: { contentType: "application/json" } }),
env.COMICS_BUCKET.put(`${artifactPrefix}/topics.json`, JSON.stringify(plan.topic_candidates, null, 2), { httpMetadata: { contentType: "application/json" } }),
env.COMICS_BUCKET.put(`${artifactPrefix}/prompt-a.txt`, plan.prompt_a, { httpMetadata: { contentType: "text/plain; charset=utf-8" } }),
env.COMICS_BUCKET.put(`${artifactPrefix}/prompt-b.txt`, plan.prompt_b, { httpMetadata: { contentType: "text/plain; charset=utf-8" } })
]);
workflowLog.push(makeStep("persist-artifacts", "ok", `Saved images and workflow artifacts to ${artifactPrefix}.`));
const scriptA = {
run_id: plan.run_id,
panel_count: plan.panel_count,
character_count: plan.character_count,
cast_ids: plan.cast.map((item) => item.id),
topic_candidates: plan.topic_candidates,
selected_topic: plan.selected_topic,
prompt: plan.prompt_a,
seed: seedA,
model: variantA.model
};
const scriptB = {
run_id: plan.run_id,
panel_count: plan.panel_count,
character_count: plan.character_count,
cast_ids: plan.cast.map((item) => item.id),
topic_candidates: plan.topic_candidates,
selected_topic: plan.selected_topic,
prompt: plan.prompt_b,
seed: seedB,
model: variantB.model
};
await env.DB.prepare(
"INSERT OR REPLACE INTO comics (day, prompt, model_a, model_b, r2_key_a, r2_key_b, script_a, script_b, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
).bind(
plan.day,
plan.title,
variantA.model,
variantB.model,
imageKeyA,
imageKeyB,
JSON.stringify(scriptA),
JSON.stringify(scriptB),
Math.floor(Date.now() / 1e3)
).run();
await env.DB.prepare(
`INSERT OR REPLACE INTO workflow_runs (
run_id, day, trigger, panel_count, character_count, cast_json, topics_json, selected_topic,
prompt_a, prompt_b, model_a, model_b, image_key_a, image_key_b, artifact_log_key, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
).bind(
plan.run_id,
plan.day,
options.trigger,
plan.panel_count,
plan.character_count,
JSON.stringify(plan.cast),
JSON.stringify(plan.topic_candidates),
plan.selected_topic,
plan.prompt_a,
plan.prompt_b,
variantA.model,
variantB.model,
imageKeyA,
imageKeyB,
`${artifactPrefix}/workflow-log.json`,
Math.floor(Date.now() / 1e3)
).run();
workflowLog.push(makeStep("persist-database", "ok", "Stored comic metadata and workflow run in D1."));
return {
day: plan.day,
run_id: plan.run_id,
title: plan.title,
panel_count: plan.panel_count,
character_count: plan.character_count,
cast: plan.cast,
topic_candidates: plan.topic_candidates,
selected_topic: plan.selected_topic,
model_a: variantA.model,
model_b: variantB.model,
prompt_a: plan.prompt_a,
prompt_b: plan.prompt_b,
image_key_a: imageKeyA,
image_key_b: imageKeyB,
artifact_keys: {
log: `${artifactPrefix}/workflow-log.json`,
cast: `${artifactPrefix}/cast.json`,
topics: `${artifactPrefix}/topics.json`,
prompt_a: `${artifactPrefix}/prompt-a.txt`,
prompt_b: `${artifactPrefix}/prompt-b.txt`
},
script_a: scriptA,
script_b: scriptB,
workflow_log: workflowLog
};
}
async function buildComicPlan(env, options, workflowLog) {
const now = Date.now();
const runId = `${options.day}-${now}-${Math.floor(Math.random() * 1e6)}`;
const random = createSeededRng(hashToUInt32(`${options.day}:${runId}`));
const panelCount = randomInt(random, 1, 4);
const maxCharacters = Math.min(4, CAST.length);
const characterCount = randomInt(random, 1, maxCharacters);
const chosenCast = pickCharacters(random, characterCount);
workflowLog.push(makeStep("sample-structure", "ok", `Selected ${panelCount} panel(s), ${characterCount} character(s).`));
const topicCandidates = await suggestTopics(env, chosenCast, panelCount, random, workflowLog);
const selectedTopic = options.force_topic || topicCandidates[randomInt(random, 0, topicCandidates.length - 1)];
const title = makeComicTitle(selectedTopic);
const promptBase = buildStandardPrompt({
panelCount,
cast: chosenCast,
topic: selectedTopic
});
const promptA = `${promptBase}
Variant directive: prioritize crisp panel readability and dry technical humor.`;
const promptB = `${promptBase}
Variant directive: prioritize absurd BOFH energy and unexpected visual punchline.`;
workflowLog.push(makeStep("build-prompts", "ok", "Built standard image generation prompts for both variants."));
return {
day: options.day,
run_id: runId,
title,
panel_count: panelCount,
character_count: characterCount,
cast: chosenCast,
topic_candidates: topicCandidates,
selected_topic: selectedTopic,
prompt_a: promptA,
prompt_b: promptB
};
}
async function suggestTopics(env, cast, panelCount, random, workflowLog) {
if (!env.AI) {
const fallback2 = pickFallbackTopics(random, cast);
workflowLog.push(makeStep("suggest-topics", "ok", "AI binding unavailable, used deterministic fallback topics."));
return fallback2;
}
const model = env.TOPIC_MODEL || DEFAULT_TOPIC_MODEL;
const systemPrompt = 'You are a technical humor prompt planner. Return JSON only: {"topics":["...", "...", "..."]}';
const userPrompt = [
`Create 3 concise comic topic candidates for an xkcd-style technical comic.`,
`Panel count: ${panelCount}`,
`Cast: ${cast.map((c) => `${c.name} (${c.role})`).join(", ")}`,
`Rules: each topic must be specific, practical, and under 12 words.`
].join("\n");
try {
const response = await env.AI.run(model, {
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userPrompt }
],
max_tokens: 350,
temperature: 0.8
});
const raw = response?.response || JSON.stringify(response);
const parsed = parseJsonFromText(raw);
const topics = Array.isArray(parsed?.topics) ? parsed.topics.map((topic) => String(topic).trim()).filter(Boolean).slice(0, 3) : [];
if (topics.length === 3) {
workflowLog.push(makeStep("suggest-topics", "ok", `Generated topic candidates using ${model}.`));
return topics;
}
} catch (err) {
workflowLog.push(makeStep("suggest-topics", "error", `Topic generation failed on ${model}: ${err.message || String(err)}`));
}
const fallback = pickFallbackTopics(random, cast);
workflowLog.push(makeStep("suggest-topics-fallback", "ok", "Used deterministic fallback topics."));
return fallback;
}
function pickFallbackTopics(random, cast) {
const pool = [...FALLBACK_TOPICS];
const selected = [];
while (selected.length < 3 && pool.length > 0) {
const idx = Math.floor(random() * pool.length);
selected.push(pool[idx]);
pool.splice(idx, 1);
}
if (selected.length < 3) {
while (selected.length < 3) {
selected.push(`unexpected ${cast[0]?.name || "robot"} behavior in production`);
}
}
return selected;
}
async function generateImageVariant(env, model, prompt, seed, workflowLog, stepName, fallbackModel) {
if (!env.AI) {
throw new Error("Workers AI binding is required for graphic generation.");
}
try {
const image = await generateImageWithModel(env.AI, model, prompt, seed);
workflowLog.push(makeStep(stepName, "ok", `Generated image with ${model} (seed ${seed}).`));
return { image, model };
} catch (err) {
if (!fallbackModel) {
workflowLog.push(makeStep(stepName, "error", `Image generation failed on ${model}: ${err.message || String(err)}`));
throw err;
}
const fallbackImage = await generateImageWithModel(env.AI, fallbackModel, prompt, seed + 99);
const fallbackName = `${fallbackModel} (fallback for ${model})`;
workflowLog.push(makeStep(stepName, "ok", `Model ${model} failed, used fallback ${fallbackName}.`));
return { image: fallbackImage, model: fallbackName };
}
}
async function generateImageWithModel(ai, model, prompt, seed) {
const payload = {
prompt,
negative_prompt: NEGATIVE_PROMPT,
seed
};
if (model.includes("stable-diffusion-xl-lightning")) {
payload.width = 1344;
payload.height = 768;
payload.num_steps = 8;
payload.guidance = 4.5;
} else {
payload.width = 1344;
payload.height = 768;
payload.num_steps = 6;
}
const result = await ai.run(model, payload);
return normalizeImageOutput(result);
}
async function normalizeImageOutput(output) {
if (!output) {
throw new Error("Model returned empty image payload.");
}
if (output instanceof ArrayBuffer) return output;
if (ArrayBuffer.isView(output)) return output.buffer.slice(output.byteOffset, output.byteOffset + output.byteLength);
if (output instanceof ReadableStream) return new Response(output).arrayBuffer();
if (typeof output === "string") return base64ToArrayBuffer(output);
if (output.image) return base64ToArrayBuffer(output.image);
if (output.result?.image) return base64ToArrayBuffer(output.result.image);
if (typeof output.b64_json === "string") return base64ToArrayBuffer(output.b64_json);
throw new Error("Unsupported image output shape from Workers AI.");
}
function buildStandardPrompt(input) {
const castLines = input.cast.map((char, idx) => `${idx + 1}. ${char.name} (${char.role})
Description: ${char.description}
Visual cues: ${char.visual_traits.join(", ")}
Sample reference: ${char.sample_image}`).join("\n");
return [
"Create a graphic webcomic image, not plain text output.",
"Style: xkcd-inspired minimal black-and-white line art, hand-drawn stick figures, technical humor.",
`Layout: exactly ${input.panelCount} panels in one horizontal strip with visible panel borders.`,
"Each panel should contain concise speech or thought bubbles as part of the drawing.",
`Topic: ${input.topic}`,
"Characters to include:",
castLines,
"Scene requirements:",
"- Keep the robot internal monologue in a cloud-like thought bubble with monospace look.",
"- Keep Simon deadpan if Simon is present.",
"- Keep backgrounds minimal and technical (whiteboard, terminal, server rack hints).",
"- No full-color illustration; monochrome or near-monochrome only.",
"- No captions outside panels.",
"- No watermark, logo, signature, or unrelated text."
].join("\n");
}
function makeComicTitle(topic) {
const trimmed = topic.trim();
const clean = trimmed.charAt(0).toUpperCase() + trimmed.slice(1);
return `LLM DOES NOT COMPUTE: ${clean}`;
}
function makeStep(step, status, detail) {
const now = (/* @__PURE__ */ new Date()).toISOString();
return {
step,
status,
started_at: now,
completed_at: now,
detail
};
}
function createSeededRng(seed) {
let t = seed >>> 0;
return () => {
t += 1831565813;
let x = Math.imul(t ^ t >>> 15, t | 1);
x ^= x + Math.imul(x ^ x >>> 7, x | 61);
return ((x ^ x >>> 14) >>> 0) / 4294967296;
};
}
function randomInt(rand, min, max) {
return Math.floor(rand() * (max - min + 1)) + min;
}
function hashToUInt32(input) {
let h = 2166136261;
for (let i = 0; i < input.length; i += 1) {
h ^= input.charCodeAt(i);
h = Math.imul(h, 16777619);
}
return h >>> 0;
}
function parseJsonFromText(raw) {
try {
return JSON.parse(raw);
} catch {
const match2 = raw.match(/\{[\s\S]*\}/);
if (!match2) return null;
try {
return JSON.parse(match2[0]);
} catch {
return null;
}
}
}
var DEFAULT_IMAGE_MODEL_A, DEFAULT_IMAGE_MODEL_B, DEFAULT_TOPIC_MODEL, FALLBACK_TOPICS, NEGATIVE_PROMPT;
var init_agentic_comic_workflow = __esm({
"lib/agentic-comic-workflow.ts"() {
"use strict";
init_functionsRoutes_0_692898257009851();
init_cast();
init_encoding();
DEFAULT_IMAGE_MODEL_A = "@cf/bytedance/stable-diffusion-xl-lightning";
DEFAULT_IMAGE_MODEL_B = "@cf/black-forest-labs/flux-1-schnell";
DEFAULT_TOPIC_MODEL = "@cf/meta/llama-3.1-8b-instruct";
FALLBACK_TOPICS = [
"prompt injection incident in production",
"Kubernetes deployment rollback panic",
"Cloudflare cache key confusion",
"zero-downtime deploy that was not zero downtime",
"hallucinated source citations in incident report",
"DNS propagation waiting game",
"mysterious authentication timeout after lunch",
"cost optimization meeting that increases costs",
"SRE on-call handoff gone sideways",
"passive aggressive status page update"
];
NEGATIVE_PROMPT = [
"photo realistic",
"3d render",
"oil painting",
"high saturation",
"blurry",
"extra limbs",
"text wall",
"watermark",
"logo",
"signature"
].join(", ");
__name(previewAgenticPromptPlan, "previewAgenticPromptPlan");
__name(runAgenticComicWorkflow, "runAgenticComicWorkflow");
__name(buildComicPlan, "buildComicPlan");
__name(suggestTopics, "suggestTopics");
__name(pickFallbackTopics, "pickFallbackTopics");
__name(generateImageVariant, "generateImageVariant");
__name(generateImageWithModel, "generateImageWithModel");
__name(normalizeImageOutput, "normalizeImageOutput");
__name(buildStandardPrompt, "buildStandardPrompt");
__name(makeComicTitle, "makeComicTitle");
__name(makeStep, "makeStep");
__name(createSeededRng, "createSeededRng");
__name(randomInt, "randomInt");
__name(hashToUInt32, "hashToUInt32");
__name(parseJsonFromText, "parseJsonFromText");
}
});
// api/test-generate.ts
async function onRequestPost2(context) {
const { env, request } = context;
if (!env.TEST_SECRET) {
return Response.json({
error: "TEST_SECRET is not configured for this environment"
}, { status: 503 });
}
const authHeader = request.headers.get("Authorization");
const expectedAuth = `Bearer ${env.TEST_SECRET}`;
if (authHeader !== expectedAuth) {
return Response.json({
error: "Unauthorized",
hint: "Set Authorization header: Bearer <TEST_SECRET>"
}, { status: 401 });
}
try {
const { runAgenticComicWorkflow: runAgenticComicWorkflow2, previewAgenticPromptPlan: previewAgenticPromptPlan2 } = await Promise.resolve().then(() => (init_agentic_comic_workflow(), agentic_comic_workflow_exports));
const reqUrl = new URL(request.url);
const body = await tryParseJson(request) || {};
const day = String(body.day || reqUrl.searchParams.get("day") || (/* @__PURE__ */ new Date()).toISOString().split("T")[0]);
const force = String(body.force || reqUrl.searchParams.get("force") || "0") === "1";
const dryRun = String(body.dry_run || reqUrl.searchParams.get("dry_run") || "0") === "1";
const forceTopic = String(body.topic || reqUrl.searchParams.get("topic") || "").trim() || void 0;
const keyA = `comics/${day}/a.png`;
const keyB = `comics/${day}/b.png`;
const legacyKeyA = `comics/${day}/a.svg`;
const legacyKeyB = `comics/${day}/b.svg`;
const [existingA, existingB, existingLegacyA, existingLegacyB] = await Promise.all([
env.COMICS_BUCKET.head(keyA),
env.COMICS_BUCKET.head(keyB),
env.COMICS_BUCKET.head(legacyKeyA),
env.COMICS_BUCKET.head(legacyKeyB)
]);
if (!force && (existingA || existingB || existingLegacyA || existingLegacyB)) {
return Response.json({
error: "Comic object already exists for today",
day,
hint: "Use force=1 to overwrite metadata with a new run for the same day"
}, { status: 409 });
}
if (dryRun) {
const plan = await previewAgenticPromptPlan2(env, {
day,
force_topic: forceTopic,
trigger: "manual"
});
return Response.json({
success: true,
dry_run: true,
day,
message: "Generated agentic prompt plan without image generation.",
plan
});
}
const result = await runAgenticComicWorkflow2(env, {
day,
force_topic: forceTopic,
trigger: "manual"
});
return Response.json({
success: true,
day,
title: result.title,
run_id: result.run_id,
panel_count: result.panel_count,
character_count: result.character_count,
topic_candidates: result.topic_candidates,
selected_topic: result.selected_topic,
cast: result.cast,
models: {
a: result.model_a,
b: result.model_b
},
r2_keys: {
a: result.image_key_a,
b: result.image_key_b
},
artifact_keys: result.artifact_keys,
workflow_log: result.workflow_log,
message: "Graphic comic generated successfully via agentic workflow. Visit /api/today to see it."
});
} catch (err) {
console.error("Test generation failed:", err);
return Response.json({
error: err.message || "Generation failed",
stack: err.stack,
hint: "Check logs with: wrangler pages deployment tail"
}, { status: 500 });
}
}
async function onRequestGet4(context) {
return Response.json({
message: "Agentic graphic comic generation endpoint",
method: "POST",
auth: "Authorization: Bearer <TEST_SECRET>",
examples: [
'curl -X POST -H "Authorization: Bearer <TEST_SECRET>" https://your-site.com/api/test-generate',
`curl -X POST -H "Authorization: Bearer <TEST_SECRET>" -H "Content-Type: application/json" -d '{"topic":"cache invalidation incident","force":"1"}' https://your-site.com/api/test-generate`,
`curl -X POST -H "Authorization: Bearer <TEST_SECRET>" -H "Content-Type: application/json" -d '{"dry_run":"1"}' https://your-site.com/api/test-generate`
]
});
}
async function tryParseJson(request) {
try {
if (request.headers.get("Content-Type")?.includes("application/json")) {
return await request.json();
}
return null;
} catch {
return null;
}
}
var init_test_generate = __esm({
"api/test-generate.ts"() {
"use strict";
init_functionsRoutes_0_692898257009851();
__name(onRequestPost2, "onRequestPost");
__name(onRequestGet4, "onRequestGet");
__name(tryParseJson, "tryParseJson");
}
});
// api/today.ts
async function onRequestGet5(context) {
const { env } = context;
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
try {
let comic = await env.DB.prepare(
"SELECT * FROM comics WHERE day = ?"
).bind(today).first();
if (!comic) {
comic = await env.DB.prepare(
"SELECT * FROM comics ORDER BY day DESC LIMIT 1"
).first();
if (!comic) {
return Response.json({
error: "No comics available yet",
day: today
}, { status: 404 });
}
}
const comicDay = comic.day;
const votes = await env.DB.prepare(
"SELECT variant, COUNT(*) as count FROM votes WHERE day = ? GROUP BY variant"
).bind(comicDay).all();
const votesA = votes.results.find((v) => v.variant === "a")?.count || 0;
const votesB = votes.results.find((v) => v.variant === "b")?.count || 0;
const urlA = await env.COMICS_BUCKET.get(comic.r2_key_a);
const urlB = await env.COMICS_BUCKET.get(comic.r2_key_b);
if (!urlA || !urlB) {
return Response.json({
error: "Comic images not found",
day: comicDay
}, { status: 500 });
}
const imageA = await urlA.arrayBuffer();
const imageB = await urlB.arrayBuffer();
const typeA = urlA.httpMetadata?.contentType || normalizeContentType(comic.r2_key_a);
const typeB = urlB.httpMetadata?.contentType || normalizeContentType(comic.r2_key_b);
return Response.json({
day: comicDay,
title: comic.prompt,
variants: {
a: {
model: comic.model_a,
imageUrl: `data:${typeA};base64,${arrayBufferToBase64(imageA)}`,
votes: votesA,
script: comic.script_a
},
b: {
model: comic.model_b,
imageUrl: `data:${typeB};base64,${arrayBufferToBase64(imageB)}`,
votes: votesB,
script: comic.script_b
}
}
});
} catch (err) {
console.error("Error fetching today's comic:", err);
return Response.json({
error: err.message || "Internal server error"
}, { status: 500 });
}
}
var init_today = __esm({
"api/today.ts"() {
"use strict";
init_functionsRoutes_0_692898257009851();
init_encoding();
__name(onRequestGet5, "onRequestGet");
}
});
// api/vote.ts
async function onRequestPost3(context) {
const { request, env } = context;
try {
const body = await request.json();
if (!body.day || !body.variant || !["a", "b"].includes(body.variant)) {
return Response.json({
error: "Invalid request. Provide day and variant (a or b)"
}, { status: 400 });
}
const ip = request.headers.get("CF-Connecting-IP") || "unknown";
const ua = request.headers.get("User-Agent") || "";
const voterHash = await hashString(`${ip}:${ua}:${body.day}`);
const result = await env.DB.prepare(
"INSERT OR REPLACE INTO votes (day, variant, voter_hash, created_at) VALUES (?, ?, ?, ?)"
).bind(
body.day,
body.variant,
voterHash,
Math.floor(Date.now() / 1e3)
).run();
const votes = await env.DB.prepare(
"SELECT variant, COUNT(*) as count FROM votes WHERE day = ? GROUP BY variant"
).bind(body.day).all();
const votesA = votes.results.find((v) => v.variant === "a")?.count || 0;
const votesB = votes.results.find((v) => v.variant === "b")?.count || 0;
return Response.json({
success: true,
votes: { a: votesA, b: votesB }
});
} catch (err) {
console.error("Error recording vote:", err);
return Response.json({
error: err.message || "Failed to record vote"
}, { status: 500 });
}
}
async function hashString(str) {
const encoder = new TextEncoder();
const data = encoder.encode(str);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
}
var init_vote = __esm({
"api/vote.ts"() {
"use strict";
init_functionsRoutes_0_692898257009851();
__name(onRequestPost3, "onRequestPost");
__name(hashString, "hashString");
}
});
// api/workflow.ts
async function onRequestGet6(context) {
const { request, env } = context;
const url = new URL(request.url);
const day = url.searchParams.get("day");
const includeArtifacts = url.searchParams.get("include_artifacts") === "1";