@affectively/aeon-pages-runtime 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3257 @@
1
+ // src/router/types.ts
2
+ var DEFAULT_ROUTER_CONFIG = {
3
+ adapter: "heuristic",
4
+ speculation: {
5
+ enabled: true,
6
+ depth: 2,
7
+ prerenderTop: 1,
8
+ maxPrefetch: 5
9
+ },
10
+ personalization: {
11
+ featureGating: true,
12
+ emotionTheming: true,
13
+ componentOrdering: true,
14
+ densityAdaptation: true
15
+ }
16
+ };
17
+ var DEFAULT_ESI_CONFIG = {
18
+ enabled: false,
19
+ endpoint: process.env.ESI_ENDPOINT || "",
20
+ timeout: 5000,
21
+ defaultCacheTtl: 300,
22
+ maxConcurrent: 5,
23
+ warmupModels: ["llm"],
24
+ tierLimits: {
25
+ free: {
26
+ maxInferencesPerRequest: 2,
27
+ allowedModels: ["llm", "embed"],
28
+ maxTokens: 500
29
+ },
30
+ starter: {
31
+ maxInferencesPerRequest: 5,
32
+ allowedModels: ["llm", "embed", "classify"],
33
+ maxTokens: 1000
34
+ },
35
+ pro: {
36
+ maxInferencesPerRequest: 20,
37
+ allowedModels: ["llm", "embed", "classify", "vision", "tts"],
38
+ maxTokens: 4000
39
+ },
40
+ enterprise: {
41
+ maxInferencesPerRequest: 100,
42
+ allowedModels: ["llm", "embed", "classify", "vision", "tts", "stt", "custom"],
43
+ maxTokens: 32000
44
+ }
45
+ }
46
+ };
47
+ // src/router/esi-cyrano.ts
48
+ function esiContext(context, options = {}) {
49
+ const { emitExhaust = true, id } = options;
50
+ return {
51
+ id: id || `esi-context-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
52
+ params: {
53
+ model: "custom",
54
+ custom: {
55
+ type: "context-drop",
56
+ emitExhaust
57
+ }
58
+ },
59
+ content: {
60
+ type: "json",
61
+ value: JSON.stringify(context)
62
+ },
63
+ contextAware: true,
64
+ signals: ["emotion", "preferences", "history", "time", "device"]
65
+ };
66
+ }
67
+ function esiCyrano(config, options = {}) {
68
+ const {
69
+ intent,
70
+ tone = "warm",
71
+ trigger = "always",
72
+ fallback,
73
+ suggestTool,
74
+ suggestRoute,
75
+ autoAcceptNavigation = false,
76
+ priority = 1,
77
+ maxTriggersPerSession,
78
+ cooldownSeconds,
79
+ speak = false,
80
+ showCaption = true,
81
+ requiredTier
82
+ } = config;
83
+ const systemPrompt = buildCyranoSystemPrompt(intent, tone);
84
+ return {
85
+ id: `esi-cyrano-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
86
+ params: {
87
+ model: "llm",
88
+ system: systemPrompt,
89
+ temperature: 0.7,
90
+ maxTokens: 150,
91
+ fallback,
92
+ custom: {
93
+ type: "cyrano-whisper",
94
+ intent,
95
+ tone,
96
+ trigger,
97
+ suggestTool,
98
+ suggestRoute,
99
+ autoAcceptNavigation,
100
+ priority,
101
+ maxTriggersPerSession,
102
+ cooldownSeconds,
103
+ speak,
104
+ showCaption
105
+ },
106
+ ...options
107
+ },
108
+ content: {
109
+ type: "template",
110
+ value: buildCyranoPrompt(intent, trigger),
111
+ variables: {
112
+ intent,
113
+ tone,
114
+ trigger
115
+ }
116
+ },
117
+ contextAware: true,
118
+ signals: ["emotion", "preferences", "history", "time"],
119
+ requiredTier
120
+ };
121
+ }
122
+ function buildCyranoSystemPrompt(intent, tone) {
123
+ const toneGuide = {
124
+ warm: "Be warm, caring, and approachable. Use gentle language.",
125
+ calm: "Be calm, measured, and reassuring. Use a steady pace.",
126
+ encouraging: "Be supportive and uplifting. Celebrate small wins.",
127
+ playful: "Be light-hearted and fun. Use appropriate humor.",
128
+ professional: "Be clear and direct. Maintain professionalism.",
129
+ empathetic: "Show deep understanding. Validate feelings.",
130
+ neutral: "Be balanced and objective. Provide information."
131
+ };
132
+ const intentGuide = {
133
+ greeting: "Welcome the user. Make them feel at home.",
134
+ "proactive-check-in": "Check in gently. Ask how they are doing.",
135
+ "supportive-presence": "Simply acknowledge. Let them know you are here.",
136
+ "gentle-nudge": "Suggest an action softly. No pressure.",
137
+ "tool-suggestion": "Recommend a tool that might help.",
138
+ "navigation-hint": "Suggest exploring another area.",
139
+ intervention: "Step in supportively. Offer help.",
140
+ celebration: "Celebrate their progress. Be genuinely happy for them.",
141
+ reflection: "Invite them to reflect. Ask thoughtful questions.",
142
+ guidance: "Offer helpful guidance. Be a trusted advisor.",
143
+ farewell: "Wish them well. Leave the door open.",
144
+ custom: "Respond appropriately to the context."
145
+ };
146
+ return `You are Cyrano, an ambient AI companion. ${toneGuide[tone]} ${intentGuide[intent]}
147
+
148
+ Keep responses brief (1-2 sentences). Be natural and conversational.
149
+ Never start with "I" - use "You" or the situation as the subject.
150
+ Never say "As an AI" or similar phrases.
151
+ Respond to the emotional context provided.`;
152
+ }
153
+ function buildCyranoPrompt(intent, trigger) {
154
+ const prompts = {
155
+ greeting: "Generate a warm greeting based on the time of day and user context.",
156
+ "proactive-check-in": "Check in with the user based on their emotional state and behavior.",
157
+ "supportive-presence": "Acknowledge the user's presence and current activity.",
158
+ "gentle-nudge": "Gently suggest the user might benefit from a particular action.",
159
+ "tool-suggestion": "Suggest a specific tool that could help with the user's current state.",
160
+ "navigation-hint": "Suggest the user might want to explore a different area.",
161
+ intervention: "Offer supportive intervention based on detected stress or difficulty.",
162
+ celebration: "Celebrate the user's progress or achievement.",
163
+ reflection: "Invite the user to reflect on their current experience.",
164
+ guidance: "Offer helpful guidance for the user's current situation.",
165
+ farewell: "Say goodbye warmly, acknowledging the session.",
166
+ custom: "Respond appropriately to the context provided."
167
+ };
168
+ let prompt = prompts[intent] || prompts.custom;
169
+ if (trigger !== "always" && trigger !== "never") {
170
+ prompt += ` The trigger condition is: ${trigger}.`;
171
+ }
172
+ return prompt;
173
+ }
174
+ function esiHalo(config, options = {}) {
175
+ const {
176
+ observe,
177
+ window: window2 = "session",
178
+ action = "whisper-to-cyrano",
179
+ sensitivity = 0.5,
180
+ crisisLevel = false,
181
+ parameters = {}
182
+ } = config;
183
+ return {
184
+ id: `esi-halo-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
185
+ params: {
186
+ model: "custom",
187
+ custom: {
188
+ type: "halo-insight",
189
+ observe,
190
+ window: window2,
191
+ action,
192
+ sensitivity,
193
+ crisisLevel,
194
+ parameters
195
+ },
196
+ ...options
197
+ },
198
+ content: {
199
+ type: "json",
200
+ value: JSON.stringify({
201
+ observation: observe,
202
+ window: window2,
203
+ action,
204
+ sensitivity,
205
+ crisisLevel
206
+ })
207
+ },
208
+ contextAware: true,
209
+ signals: ["emotion", "history", "time"]
210
+ };
211
+ }
212
+ function evaluateTrigger(trigger, context, sessionContext) {
213
+ if (trigger === "always")
214
+ return true;
215
+ if (trigger === "never")
216
+ return false;
217
+ const [type, condition] = trigger.split(":");
218
+ switch (type) {
219
+ case "dwell": {
220
+ const match = condition?.match(/>(\d+)s/);
221
+ if (!match)
222
+ return false;
223
+ const threshold = parseInt(match[1], 10) * 1000;
224
+ const dwellTime = sessionContext?.behavior?.dwellTime || 0;
225
+ return dwellTime > threshold;
226
+ }
227
+ case "scroll": {
228
+ const match = condition?.match(/>(\d+\.?\d*)/);
229
+ if (!match)
230
+ return false;
231
+ const threshold = parseFloat(match[1]);
232
+ const scrollDepth = sessionContext?.behavior?.scrollDepth || 0;
233
+ return scrollDepth > threshold;
234
+ }
235
+ case "emotion": {
236
+ const targetEmotion = condition;
237
+ return sessionContext?.emotion?.primary === targetEmotion || context.emotionState?.primary === targetEmotion;
238
+ }
239
+ case "behavior": {
240
+ if (condition === "aimless") {
241
+ return sessionContext?.behavior?.isAimlessClicking === true;
242
+ }
243
+ if (condition === "hesitation") {
244
+ return sessionContext?.behavior?.hesitationDetected === true;
245
+ }
246
+ return false;
247
+ }
248
+ case "hrv": {
249
+ const match = condition?.match(/<(\d+)/);
250
+ if (!match)
251
+ return false;
252
+ const threshold = parseInt(match[1], 10);
253
+ const hrv = sessionContext?.biometric?.hrv || 100;
254
+ return hrv < threshold;
255
+ }
256
+ case "stress": {
257
+ const match = condition?.match(/>(\d+)/);
258
+ if (!match)
259
+ return false;
260
+ const threshold = parseInt(match[1], 10);
261
+ const stress = sessionContext?.biometric?.stressScore || 0;
262
+ return stress > threshold;
263
+ }
264
+ case "session": {
265
+ if (condition === "start") {
266
+ return context.isNewSession;
267
+ }
268
+ const idleMatch = condition?.match(/idle:(\d+)m/);
269
+ if (idleMatch) {
270
+ return false;
271
+ }
272
+ return false;
273
+ }
274
+ case "navigation": {
275
+ const targetRoute = condition?.replace("to:", "");
276
+ return sessionContext?.currentRoute === targetRoute;
277
+ }
278
+ case "time": {
279
+ const hour = context.localHour;
280
+ if (condition === "morning")
281
+ return hour >= 6 && hour < 12;
282
+ if (condition === "afternoon")
283
+ return hour >= 12 && hour < 18;
284
+ if (condition === "evening")
285
+ return hour >= 18 && hour < 22;
286
+ if (condition === "night")
287
+ return hour >= 22 || hour < 6;
288
+ return false;
289
+ }
290
+ default:
291
+ return false;
292
+ }
293
+ }
294
+ function createExhaustEntry(directive, result, type) {
295
+ return {
296
+ type,
297
+ timestamp: Date.now(),
298
+ content: {
299
+ directiveId: directive.id,
300
+ output: result.output,
301
+ model: result.model,
302
+ success: result.success,
303
+ latencyMs: result.latencyMs
304
+ },
305
+ visible: type === "cyrano" || type === "user",
306
+ source: directive.params.model
307
+ };
308
+ }
309
+ var CYRANO_TOOL_SUGGESTIONS = {
310
+ breathing: {
311
+ triggers: ["stress:>70", "hrv:<40", "emotion:anxious"],
312
+ tool: "breathing/4-7-8",
313
+ reason: "You seem stressed - a breathing exercise might help"
314
+ },
315
+ grounding: {
316
+ triggers: ["emotion:overwhelmed", "behavior:aimless"],
317
+ tool: "grounding/5-4-3-2-1",
318
+ reason: "A grounding exercise can help center you"
319
+ },
320
+ journaling: {
321
+ triggers: ["dwell:>120s", "emotion:reflective"],
322
+ tool: "journaling/freeform",
323
+ reason: "Would you like to write about what's on your mind?"
324
+ },
325
+ insights: {
326
+ triggers: ["navigation:to:/insights", "dwell:>60s"],
327
+ tool: "insights/dashboard",
328
+ reason: "Your recent patterns are ready to explore"
329
+ }
330
+ };
331
+ function getToolSuggestions(context, sessionContext) {
332
+ const suggestions = [];
333
+ for (const [, config] of Object.entries(CYRANO_TOOL_SUGGESTIONS)) {
334
+ for (const trigger of config.triggers) {
335
+ if (evaluateTrigger(trigger, context, sessionContext)) {
336
+ suggestions.push({
337
+ tool: config.tool,
338
+ reason: config.reason,
339
+ priority: trigger.startsWith("stress") || trigger.startsWith("hrv") ? 2 : 1
340
+ });
341
+ break;
342
+ }
343
+ }
344
+ }
345
+ return suggestions.sort((a, b) => b.priority - a.priority);
346
+ }
347
+
348
+ // src/router/esi.ts
349
+ var esiCache = new Map;
350
+ function getCacheKey(directive, context) {
351
+ const contextParts = directive.contextAware ? [
352
+ context.tier,
353
+ context.emotionState?.primary,
354
+ context.localHour
355
+ ].join(":") : "";
356
+ return directive.cacheKey || `esi:${directive.params.model}:${directive.content.value}:${contextParts}`;
357
+ }
358
+ function getCached(key) {
359
+ const entry = esiCache.get(key);
360
+ if (!entry)
361
+ return null;
362
+ if (Date.now() > entry.expiresAt) {
363
+ esiCache.delete(key);
364
+ return null;
365
+ }
366
+ return { ...entry.result, cached: true };
367
+ }
368
+ function setCache(key, result, ttl) {
369
+ if (ttl <= 0)
370
+ return;
371
+ esiCache.set(key, {
372
+ result,
373
+ expiresAt: Date.now() + ttl * 1000
374
+ });
375
+ }
376
+ function interpolatePrompt(content, context, signals = []) {
377
+ let prompt = content.value;
378
+ if (content.type === "template" && content.variables) {
379
+ for (const [key, value] of Object.entries(content.variables)) {
380
+ prompt = prompt.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), String(value));
381
+ }
382
+ }
383
+ if (signals.length > 0) {
384
+ const contextParts = [];
385
+ if (signals.includes("emotion") && context.emotionState) {
386
+ contextParts.push(`User emotion: ${context.emotionState.primary} ` + `(valence: ${context.emotionState.valence.toFixed(2)}, ` + `arousal: ${context.emotionState.arousal.toFixed(2)})`);
387
+ }
388
+ if (signals.includes("preferences") && Object.keys(context.preferences).length > 0) {
389
+ contextParts.push(`User preferences: ${JSON.stringify(context.preferences)}`);
390
+ }
391
+ if (signals.includes("history") && context.recentPages.length > 0) {
392
+ contextParts.push(`Recent pages: ${context.recentPages.slice(-5).join(", ")}`);
393
+ }
394
+ if (signals.includes("time")) {
395
+ contextParts.push(`Local time: ${context.localHour}:00, Timezone: ${context.timezone}`);
396
+ }
397
+ if (signals.includes("device")) {
398
+ contextParts.push(`Device: ${context.viewport.width}x${context.viewport.height}, ` + `Connection: ${context.connection}`);
399
+ }
400
+ if (contextParts.length > 0) {
401
+ prompt = `[Context]
402
+ ${contextParts.join(`
403
+ `)}
404
+
405
+ [Task]
406
+ ${prompt}`;
407
+ }
408
+ }
409
+ return prompt;
410
+ }
411
+ function checkTierAccess(directive, context, config) {
412
+ const tierLimits = config.tierLimits?.[context.tier];
413
+ if (!tierLimits) {
414
+ return { allowed: true };
415
+ }
416
+ if (!tierLimits.allowedModels.includes(directive.params.model)) {
417
+ return {
418
+ allowed: false,
419
+ reason: `Model '${directive.params.model}' not available for ${context.tier} tier`
420
+ };
421
+ }
422
+ if (directive.params.maxTokens && directive.params.maxTokens > tierLimits.maxTokens) {
423
+ return {
424
+ allowed: false,
425
+ reason: `Token limit ${directive.params.maxTokens} exceeds ${context.tier} tier max of ${tierLimits.maxTokens}`
426
+ };
427
+ }
428
+ return { allowed: true };
429
+ }
430
+
431
+ class EdgeWorkersESIProcessor {
432
+ name = "edge-workers";
433
+ config;
434
+ warmupPromise;
435
+ constructor(config = {}) {
436
+ this.config = {
437
+ enabled: config.enabled ?? false,
438
+ endpoint: config.endpoint || process.env.ESI_ENDPOINT || "",
439
+ timeout: config.timeout ?? 5000,
440
+ defaultCacheTtl: config.defaultCacheTtl ?? 300,
441
+ maxConcurrent: config.maxConcurrent ?? 5,
442
+ warmupModels: config.warmupModels,
443
+ tierLimits: config.tierLimits
444
+ };
445
+ }
446
+ async warmup() {
447
+ if (this.warmupPromise)
448
+ return this.warmupPromise;
449
+ this.warmupPromise = (async () => {
450
+ if (!this.config.warmupModels?.length)
451
+ return;
452
+ await Promise.all(this.config.warmupModels.map((model) => fetch(`${this.config.endpoint}/api/warmup`, {
453
+ method: "POST",
454
+ headers: { "Content-Type": "application/json" },
455
+ body: JSON.stringify({ model })
456
+ }).catch(() => {})));
457
+ })();
458
+ return this.warmupPromise;
459
+ }
460
+ isModelAvailable(model) {
461
+ return ["llm", "embed", "vision", "tts", "stt", "emotion", "classify", "custom"].includes(model);
462
+ }
463
+ async process(directive, context) {
464
+ const startTime = Date.now();
465
+ const cacheKey = getCacheKey(directive, context);
466
+ const cached = getCached(cacheKey);
467
+ if (cached) {
468
+ return cached;
469
+ }
470
+ const access = checkTierAccess(directive, context, this.config);
471
+ if (!access.allowed) {
472
+ return {
473
+ id: directive.id,
474
+ success: false,
475
+ error: access.reason,
476
+ latencyMs: Date.now() - startTime,
477
+ cached: false,
478
+ model: directive.params.model
479
+ };
480
+ }
481
+ const prompt = directive.contextAware ? interpolatePrompt(directive.content, context, directive.signals) : directive.content.value;
482
+ try {
483
+ const result = await this.callEdgeWorkers(directive, prompt);
484
+ const cacheTtl = directive.params.cacheTtl ?? this.config.defaultCacheTtl;
485
+ setCache(cacheKey, result, cacheTtl);
486
+ return {
487
+ ...result,
488
+ latencyMs: Date.now() - startTime
489
+ };
490
+ } catch (error) {
491
+ if (directive.params.fallback) {
492
+ return {
493
+ id: directive.id,
494
+ success: true,
495
+ output: directive.params.fallback,
496
+ latencyMs: Date.now() - startTime,
497
+ cached: false,
498
+ model: directive.params.model
499
+ };
500
+ }
501
+ return {
502
+ id: directive.id,
503
+ success: false,
504
+ error: error instanceof Error ? error.message : "Unknown error",
505
+ latencyMs: Date.now() - startTime,
506
+ cached: false,
507
+ model: directive.params.model
508
+ };
509
+ }
510
+ }
511
+ async processBatch(directives, context) {
512
+ const semaphore = new Semaphore(this.config.maxConcurrent);
513
+ return Promise.all(directives.map(async (directive) => {
514
+ await semaphore.acquire();
515
+ try {
516
+ return await this.process(directive, context);
517
+ } finally {
518
+ semaphore.release();
519
+ }
520
+ }));
521
+ }
522
+ async stream(directive, context, onChunk) {
523
+ const startTime = Date.now();
524
+ const access = checkTierAccess(directive, context, this.config);
525
+ if (!access.allowed) {
526
+ return {
527
+ id: directive.id,
528
+ success: false,
529
+ error: access.reason,
530
+ latencyMs: Date.now() - startTime,
531
+ cached: false,
532
+ model: directive.params.model
533
+ };
534
+ }
535
+ const prompt = directive.contextAware ? interpolatePrompt(directive.content, context, directive.signals) : directive.content.value;
536
+ try {
537
+ const response = await fetch(`${this.config.endpoint}/api/llm/stream`, {
538
+ method: "POST",
539
+ headers: { "Content-Type": "application/json" },
540
+ body: JSON.stringify({
541
+ input: prompt,
542
+ model: directive.params.variant,
543
+ options: {
544
+ temperature: directive.params.temperature,
545
+ max_tokens: directive.params.maxTokens,
546
+ stop: directive.params.stop,
547
+ top_p: directive.params.topP,
548
+ system: directive.params.system
549
+ }
550
+ }),
551
+ signal: AbortSignal.timeout(directive.params.timeout ?? this.config.timeout)
552
+ });
553
+ if (!response.ok) {
554
+ throw new Error(`Stream failed: ${response.status}`);
555
+ }
556
+ const reader = response.body?.getReader();
557
+ if (!reader) {
558
+ throw new Error("No response body");
559
+ }
560
+ const decoder = new TextDecoder;
561
+ let fullOutput = "";
562
+ while (true) {
563
+ const { done, value } = await reader.read();
564
+ if (done)
565
+ break;
566
+ const chunk = decoder.decode(value);
567
+ fullOutput += chunk;
568
+ onChunk(chunk);
569
+ }
570
+ return {
571
+ id: directive.id,
572
+ success: true,
573
+ output: fullOutput,
574
+ latencyMs: Date.now() - startTime,
575
+ cached: false,
576
+ model: directive.params.variant || directive.params.model
577
+ };
578
+ } catch (error) {
579
+ if (directive.params.fallback) {
580
+ onChunk(directive.params.fallback);
581
+ return {
582
+ id: directive.id,
583
+ success: true,
584
+ output: directive.params.fallback,
585
+ latencyMs: Date.now() - startTime,
586
+ cached: false,
587
+ model: directive.params.model
588
+ };
589
+ }
590
+ return {
591
+ id: directive.id,
592
+ success: false,
593
+ error: error instanceof Error ? error.message : "Stream failed",
594
+ latencyMs: Date.now() - startTime,
595
+ cached: false,
596
+ model: directive.params.model
597
+ };
598
+ }
599
+ }
600
+ async callEdgeWorkers(directive, prompt) {
601
+ const endpoint = this.getEndpointForModel(directive.params.model);
602
+ const response = await fetch(`${this.config.endpoint}${endpoint}`, {
603
+ method: "POST",
604
+ headers: { "Content-Type": "application/json" },
605
+ body: JSON.stringify(this.buildRequestBody(directive, prompt)),
606
+ signal: AbortSignal.timeout(directive.params.timeout ?? this.config.timeout)
607
+ });
608
+ if (!response.ok) {
609
+ const error = await response.text();
610
+ throw new Error(`ESI inference failed: ${response.status} - ${error}`);
611
+ }
612
+ const data = await response.json();
613
+ return this.parseResponse(directive, data);
614
+ }
615
+ getEndpointForModel(model) {
616
+ switch (model) {
617
+ case "llm":
618
+ return "/api/llm/infer";
619
+ case "embed":
620
+ return "/api/embed";
621
+ case "vision":
622
+ return "/api/vision";
623
+ case "tts":
624
+ return "/api/tts";
625
+ case "stt":
626
+ return "/api/stt";
627
+ case "emotion":
628
+ return "/api/emotion";
629
+ case "classify":
630
+ return "/api/classify";
631
+ case "custom":
632
+ return "/api/custom";
633
+ default:
634
+ return "/api/llm/infer";
635
+ }
636
+ }
637
+ buildRequestBody(directive, prompt) {
638
+ const { params, content } = directive;
639
+ const body = {
640
+ input: content.type === "base64" ? content.value : prompt,
641
+ model: params.variant
642
+ };
643
+ if (params.model === "llm") {
644
+ body.options = {
645
+ temperature: params.temperature,
646
+ max_tokens: params.maxTokens,
647
+ stop: params.stop,
648
+ top_p: params.topP,
649
+ frequency_penalty: params.frequencyPenalty,
650
+ presence_penalty: params.presencePenalty,
651
+ system: params.system
652
+ };
653
+ }
654
+ if (params.custom) {
655
+ body.custom = params.custom;
656
+ }
657
+ return body;
658
+ }
659
+ parseResponse(directive, data) {
660
+ const base = {
661
+ id: directive.id,
662
+ success: true,
663
+ latencyMs: 0,
664
+ cached: false,
665
+ model: String(data.model || directive.params.model)
666
+ };
667
+ switch (directive.params.model) {
668
+ case "embed":
669
+ return { ...base, embedding: data.embedding };
670
+ case "tts":
671
+ return { ...base, audio: data.audio };
672
+ default:
673
+ return {
674
+ ...base,
675
+ output: String(data.output || data.text || data.result || ""),
676
+ tokens: data.tokens
677
+ };
678
+ }
679
+ }
680
+ }
681
+
682
+ class Semaphore {
683
+ permits;
684
+ queue = [];
685
+ constructor(permits) {
686
+ this.permits = permits;
687
+ }
688
+ async acquire() {
689
+ if (this.permits > 0) {
690
+ this.permits--;
691
+ return;
692
+ }
693
+ return new Promise((resolve) => {
694
+ this.queue.push(resolve);
695
+ });
696
+ }
697
+ release() {
698
+ const next = this.queue.shift();
699
+ if (next) {
700
+ next();
701
+ } else {
702
+ this.permits++;
703
+ }
704
+ }
705
+ }
706
+ function esiInfer(prompt, options = {}) {
707
+ return {
708
+ id: `esi-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
709
+ params: {
710
+ model: "llm",
711
+ ...options
712
+ },
713
+ content: {
714
+ type: "text",
715
+ value: prompt
716
+ },
717
+ contextAware: options.system?.includes("{context}")
718
+ };
719
+ }
720
+ function esiEmbed(text) {
721
+ return {
722
+ id: `esi-embed-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
723
+ params: { model: "embed" },
724
+ content: { type: "text", value: text }
725
+ };
726
+ }
727
+ function esiEmotion(text, contextAware = true) {
728
+ return {
729
+ id: `esi-emotion-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
730
+ params: { model: "emotion" },
731
+ content: { type: "text", value: text },
732
+ contextAware,
733
+ signals: contextAware ? ["emotion", "history"] : undefined
734
+ };
735
+ }
736
+ function esiVision(base64Image, prompt, options = {}) {
737
+ return {
738
+ id: `esi-vision-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
739
+ params: {
740
+ model: "vision",
741
+ system: prompt,
742
+ ...options
743
+ },
744
+ content: { type: "base64", value: base64Image }
745
+ };
746
+ }
747
+ function esiWithContext(prompt, signals = ["emotion", "preferences", "time"], options = {}) {
748
+ return {
749
+ id: `esi-ctx-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
750
+ params: {
751
+ model: "llm",
752
+ ...options
753
+ },
754
+ content: { type: "text", value: prompt },
755
+ contextAware: true,
756
+ signals
757
+ };
758
+ }
759
+ // src/router/esi-react.tsx
760
+ import {
761
+ createContext,
762
+ useContext,
763
+ useEffect,
764
+ useState,
765
+ useCallback
766
+ } from "react";
767
+ import { jsxDEV } from "react/jsx-dev-runtime";
768
+ var ESIContext = createContext(null);
769
+ var ESIProvider = ({
770
+ children,
771
+ config,
772
+ userContext,
773
+ processor: customProcessor
774
+ }) => {
775
+ const [processor] = useState(() => customProcessor || new EdgeWorkersESIProcessor(config));
776
+ useEffect(() => {
777
+ processor.warmup?.();
778
+ }, [processor]);
779
+ const process2 = useCallback(async (directive) => {
780
+ if (!userContext) {
781
+ return {
782
+ id: directive.id,
783
+ success: false,
784
+ error: "No user context available",
785
+ latencyMs: 0,
786
+ cached: false,
787
+ model: directive.params.model
788
+ };
789
+ }
790
+ return processor.process(directive, userContext);
791
+ }, [processor, userContext]);
792
+ const processWithStream = useCallback(async (directive, onChunk) => {
793
+ if (!userContext) {
794
+ return {
795
+ id: directive.id,
796
+ success: false,
797
+ error: "No user context available",
798
+ latencyMs: 0,
799
+ cached: false,
800
+ model: directive.params.model
801
+ };
802
+ }
803
+ if (!processor.stream) {
804
+ return processor.process(directive, userContext);
805
+ }
806
+ return processor.stream(directive, userContext, onChunk);
807
+ }, [processor, userContext]);
808
+ return /* @__PURE__ */ jsxDEV(ESIContext.Provider, {
809
+ value: {
810
+ processor,
811
+ userContext: userContext || null,
812
+ enabled: config?.enabled ?? true,
813
+ process: process2,
814
+ processWithStream
815
+ },
816
+ children
817
+ }, undefined, false, undefined, this);
818
+ };
819
+ function useESI() {
820
+ const ctx = useContext(ESIContext);
821
+ if (!ctx) {
822
+ throw new Error("useESI must be used within an ESIProvider");
823
+ }
824
+ return ctx;
825
+ }
826
+ var ESIInfer = ({
827
+ children,
828
+ prompt,
829
+ model = "llm",
830
+ variant,
831
+ temperature,
832
+ maxTokens,
833
+ system,
834
+ stream = false,
835
+ fallback,
836
+ loading = "...",
837
+ contextAware = false,
838
+ signals,
839
+ cacheTtl,
840
+ render,
841
+ className,
842
+ onComplete,
843
+ onError
844
+ }) => {
845
+ const { process: process2, processWithStream, enabled } = useESI();
846
+ const [output, setOutput] = useState("");
847
+ const [isLoading, setIsLoading] = useState(true);
848
+ const [error, setError] = useState(null);
849
+ const promptText = prompt || (typeof children === "string" ? children : String(children || ""));
850
+ useEffect(() => {
851
+ if (!enabled) {
852
+ setOutput(typeof fallback === "string" ? fallback : "");
853
+ setIsLoading(false);
854
+ return;
855
+ }
856
+ const directive = contextAware ? esiWithContext(promptText, signals, {
857
+ model,
858
+ variant,
859
+ temperature,
860
+ maxTokens,
861
+ system,
862
+ cacheTtl,
863
+ fallback: typeof fallback === "string" ? fallback : undefined
864
+ }) : esiInfer(promptText, {
865
+ model,
866
+ variant,
867
+ temperature,
868
+ maxTokens,
869
+ system,
870
+ cacheTtl,
871
+ fallback: typeof fallback === "string" ? fallback : undefined
872
+ });
873
+ if (stream) {
874
+ setOutput("");
875
+ processWithStream(directive, (chunk) => {
876
+ setOutput((prev) => prev + chunk);
877
+ }).then((result) => {
878
+ setIsLoading(false);
879
+ if (!result.success) {
880
+ setError(result.error || "Inference failed");
881
+ onError?.(result.error || "Inference failed");
882
+ }
883
+ onComplete?.(result);
884
+ });
885
+ } else {
886
+ process2(directive).then((result) => {
887
+ setIsLoading(false);
888
+ if (result.success && result.output) {
889
+ setOutput(result.output);
890
+ } else {
891
+ setError(result.error || "Inference failed");
892
+ onError?.(result.error || "Inference failed");
893
+ }
894
+ onComplete?.(result);
895
+ });
896
+ }
897
+ }, [promptText, model, variant, temperature, maxTokens, system, contextAware, stream, enabled]);
898
+ if (isLoading && !stream) {
899
+ return /* @__PURE__ */ jsxDEV("span", {
900
+ className,
901
+ children: loading
902
+ }, undefined, false, undefined, this);
903
+ }
904
+ if (error && fallback) {
905
+ return /* @__PURE__ */ jsxDEV("span", {
906
+ className,
907
+ children: fallback
908
+ }, undefined, false, undefined, this);
909
+ }
910
+ if (render) {
911
+ return /* @__PURE__ */ jsxDEV("span", {
912
+ className,
913
+ children: render({
914
+ id: "",
915
+ success: !error,
916
+ output,
917
+ error: error || undefined,
918
+ latencyMs: 0,
919
+ cached: false,
920
+ model
921
+ })
922
+ }, undefined, false, undefined, this);
923
+ }
924
+ return /* @__PURE__ */ jsxDEV("span", {
925
+ className,
926
+ children: output || (isLoading ? loading : "")
927
+ }, undefined, false, undefined, this);
928
+ };
929
+ var ESIEmbed = ({ children, onComplete, onError }) => {
930
+ const { process: process2, enabled } = useESI();
931
+ const text = typeof children === "string" ? children : String(children || "");
932
+ useEffect(() => {
933
+ if (!enabled)
934
+ return;
935
+ const directive = esiEmbed(text);
936
+ process2(directive).then((result) => {
937
+ if (result.success && result.embedding) {
938
+ onComplete?.(result.embedding);
939
+ } else {
940
+ onError?.(result.error || "Embedding failed");
941
+ }
942
+ });
943
+ }, [text, enabled]);
944
+ return null;
945
+ };
946
+ var ESIEmotion = ({
947
+ children,
948
+ contextAware = true,
949
+ onComplete,
950
+ onError
951
+ }) => {
952
+ const { process: process2, enabled } = useESI();
953
+ const text = typeof children === "string" ? children : String(children || "");
954
+ useEffect(() => {
955
+ if (!enabled)
956
+ return;
957
+ const directive = esiEmotion(text, contextAware);
958
+ process2(directive).then((result) => {
959
+ if (result.success && result.output) {
960
+ try {
961
+ const parsed = JSON.parse(result.output);
962
+ onComplete?.(parsed);
963
+ } catch {
964
+ onComplete?.({ emotion: result.output, confidence: 1 });
965
+ }
966
+ } else {
967
+ onError?.(result.error || "Emotion detection failed");
968
+ }
969
+ });
970
+ }, [text, contextAware, enabled]);
971
+ return null;
972
+ };
973
+ var ESIVision = ({
974
+ src,
975
+ prompt,
976
+ fallback,
977
+ loading = "...",
978
+ className,
979
+ onComplete,
980
+ onError
981
+ }) => {
982
+ const { process: process2, enabled } = useESI();
983
+ const [output, setOutput] = useState("");
984
+ const [isLoading, setIsLoading] = useState(true);
985
+ const [error, setError] = useState(null);
986
+ useEffect(() => {
987
+ if (!enabled) {
988
+ setOutput(typeof fallback === "string" ? fallback : "");
989
+ setIsLoading(false);
990
+ return;
991
+ }
992
+ const directive = esiVision(src, prompt);
993
+ process2(directive).then((result) => {
994
+ setIsLoading(false);
995
+ if (result.success && result.output) {
996
+ setOutput(result.output);
997
+ } else {
998
+ setError(result.error || "Vision analysis failed");
999
+ onError?.(result.error || "Vision analysis failed");
1000
+ }
1001
+ onComplete?.(result);
1002
+ });
1003
+ }, [src, prompt, enabled]);
1004
+ if (isLoading) {
1005
+ return /* @__PURE__ */ jsxDEV("span", {
1006
+ className,
1007
+ children: loading
1008
+ }, undefined, false, undefined, this);
1009
+ }
1010
+ if (error && fallback) {
1011
+ return /* @__PURE__ */ jsxDEV("span", {
1012
+ className,
1013
+ children: fallback
1014
+ }, undefined, false, undefined, this);
1015
+ }
1016
+ return /* @__PURE__ */ jsxDEV("span", {
1017
+ className,
1018
+ children: output
1019
+ }, undefined, false, undefined, this);
1020
+ };
1021
+ function useESIInfer(options = {}) {
1022
+ const { process: process2, processWithStream, enabled } = useESI();
1023
+ const [result, setResult] = useState(null);
1024
+ const [isLoading, setIsLoading] = useState(false);
1025
+ const [error, setError] = useState(null);
1026
+ const run = useCallback(async (prompt) => {
1027
+ if (!enabled) {
1028
+ setError("ESI is disabled");
1029
+ return null;
1030
+ }
1031
+ setIsLoading(true);
1032
+ setError(null);
1033
+ const directive = options.contextAware ? esiWithContext(prompt, options.signals, {
1034
+ model: options.model,
1035
+ variant: options.variant,
1036
+ temperature: options.temperature,
1037
+ maxTokens: options.maxTokens,
1038
+ system: options.system,
1039
+ cacheTtl: options.cacheTtl
1040
+ }) : esiInfer(prompt, {
1041
+ model: options.model,
1042
+ variant: options.variant,
1043
+ temperature: options.temperature,
1044
+ maxTokens: options.maxTokens,
1045
+ system: options.system,
1046
+ cacheTtl: options.cacheTtl
1047
+ });
1048
+ try {
1049
+ let inferenceResult;
1050
+ if (options.stream) {
1051
+ let output = "";
1052
+ inferenceResult = await processWithStream(directive, (chunk) => {
1053
+ output += chunk;
1054
+ setResult((prev) => ({
1055
+ ...prev,
1056
+ output
1057
+ }));
1058
+ });
1059
+ } else {
1060
+ inferenceResult = await process2(directive);
1061
+ }
1062
+ setResult(inferenceResult);
1063
+ setIsLoading(false);
1064
+ if (!inferenceResult.success) {
1065
+ setError(inferenceResult.error || "Inference failed");
1066
+ }
1067
+ options.onComplete?.(inferenceResult);
1068
+ return inferenceResult;
1069
+ } catch (err) {
1070
+ const errorMsg = err instanceof Error ? err.message : "Unknown error";
1071
+ setError(errorMsg);
1072
+ setIsLoading(false);
1073
+ options.onError?.(errorMsg);
1074
+ return null;
1075
+ }
1076
+ }, [process2, processWithStream, enabled, options]);
1077
+ const reset = useCallback(() => {
1078
+ setResult(null);
1079
+ setError(null);
1080
+ setIsLoading(false);
1081
+ }, []);
1082
+ return { run, result, isLoading, error, reset };
1083
+ }
1084
+ var DEFAULT_ESI_STATE = {
1085
+ userTier: "free",
1086
+ emotionState: null,
1087
+ preferences: {
1088
+ theme: "auto",
1089
+ reducedMotion: false
1090
+ },
1091
+ localHour: new Date().getHours(),
1092
+ timezone: "UTC",
1093
+ features: {
1094
+ aiInference: true,
1095
+ emotionTracking: true,
1096
+ collaboration: false,
1097
+ advancedInsights: false,
1098
+ customThemes: false,
1099
+ voiceSynthesis: false,
1100
+ imageAnalysis: false
1101
+ },
1102
+ isNewSession: true,
1103
+ recentPages: [],
1104
+ viewport: { width: 1920, height: 1080 },
1105
+ connection: "4g"
1106
+ };
1107
+ function useGlobalESIState() {
1108
+ const [state, setState] = useState(() => {
1109
+ if (typeof window !== "undefined" && window.__AEON_ESI_STATE__) {
1110
+ return window.__AEON_ESI_STATE__;
1111
+ }
1112
+ return DEFAULT_ESI_STATE;
1113
+ });
1114
+ useEffect(() => {
1115
+ if (typeof window !== "undefined" && window.__AEON_ESI_STATE__?.subscribe) {
1116
+ const unsubscribe = window.__AEON_ESI_STATE__.subscribe((newState) => {
1117
+ setState(newState);
1118
+ });
1119
+ return unsubscribe;
1120
+ }
1121
+ }, []);
1122
+ return state;
1123
+ }
1124
+ function useESIFeature(feature) {
1125
+ const { features } = useGlobalESIState();
1126
+ return features[feature] ?? false;
1127
+ }
1128
+ function useESITier() {
1129
+ const { userTier } = useGlobalESIState();
1130
+ return userTier;
1131
+ }
1132
+ function useESIEmotionState() {
1133
+ const { emotionState } = useGlobalESIState();
1134
+ return emotionState;
1135
+ }
1136
+ function useESIPreferences() {
1137
+ const { preferences } = useGlobalESIState();
1138
+ return preferences;
1139
+ }
1140
+ function updateGlobalESIState(partial) {
1141
+ if (typeof window !== "undefined" && window.__AEON_ESI_STATE__?.update) {
1142
+ window.__AEON_ESI_STATE__.update(partial);
1143
+ } else if (typeof window !== "undefined" && window.__AEON_ESI_STATE__) {
1144
+ Object.assign(window.__AEON_ESI_STATE__, partial);
1145
+ }
1146
+ }
1147
+ var ESI = {
1148
+ Provider: ESIProvider,
1149
+ Infer: ESIInfer,
1150
+ Embed: ESIEmbed,
1151
+ Emotion: ESIEmotion,
1152
+ Vision: ESIVision
1153
+ };
1154
+ // src/router/heuristic-adapter.ts
1155
+ var DEFAULT_CONFIG = {
1156
+ tierFeatures: {
1157
+ free: {},
1158
+ starter: {},
1159
+ pro: {},
1160
+ enterprise: {}
1161
+ },
1162
+ defaultAccent: "#336699",
1163
+ signals: {},
1164
+ defaultPaths: ["/"],
1165
+ maxSpeculationPaths: 5
1166
+ };
1167
+ function defaultDeriveTheme(context) {
1168
+ if (context.preferences.theme) {
1169
+ return context.preferences.theme;
1170
+ }
1171
+ const hour = context.localHour;
1172
+ const isNight = hour >= 20 || hour < 6;
1173
+ const isEvening = hour >= 18 && hour < 20;
1174
+ if (isNight) {
1175
+ return "dark";
1176
+ }
1177
+ if (isEvening) {
1178
+ return "auto";
1179
+ }
1180
+ return "light";
1181
+ }
1182
+ function determineDensity(context) {
1183
+ if (context.preferences.density) {
1184
+ return context.preferences.density;
1185
+ }
1186
+ const { width, height } = context.viewport;
1187
+ if (width < 768) {
1188
+ return "compact";
1189
+ }
1190
+ if (width >= 1440 && height >= 900) {
1191
+ return "comfortable";
1192
+ }
1193
+ return "normal";
1194
+ }
1195
+ function buildTransitionMatrix(history) {
1196
+ const matrix = {};
1197
+ for (let i = 0;i < history.length - 1; i++) {
1198
+ const from = history[i];
1199
+ const to = history[i + 1];
1200
+ if (!matrix[from]) {
1201
+ matrix[from] = {};
1202
+ }
1203
+ matrix[from][to] = (matrix[from][to] || 0) + 1;
1204
+ }
1205
+ for (const from of Object.keys(matrix)) {
1206
+ const total = Object.values(matrix[from]).reduce((a, b) => a + b, 0);
1207
+ for (const to of Object.keys(matrix[from])) {
1208
+ matrix[from][to] /= total;
1209
+ }
1210
+ }
1211
+ return matrix;
1212
+ }
1213
+ function defaultPredictNavigation(currentPath, context, defaultPaths, topN) {
1214
+ const history = context.recentPages;
1215
+ if (history.length >= 3) {
1216
+ const matrix = buildTransitionMatrix(history);
1217
+ const transitions = matrix[currentPath];
1218
+ if (transitions) {
1219
+ const sorted = Object.entries(transitions).sort(([, a], [, b]) => b - a).slice(0, topN).map(([path]) => path);
1220
+ if (sorted.length > 0) {
1221
+ return sorted;
1222
+ }
1223
+ }
1224
+ }
1225
+ return defaultPaths.filter((p) => p !== currentPath).slice(0, topN);
1226
+ }
1227
+ function defaultScoreRelevance(node, context) {
1228
+ let score = 50;
1229
+ if (node.requiredTier) {
1230
+ const tierOrder = ["free", "starter", "pro", "enterprise"];
1231
+ const requiredIndex = tierOrder.indexOf(node.requiredTier);
1232
+ const userIndex = tierOrder.indexOf(context.tier);
1233
+ if (userIndex < requiredIndex) {
1234
+ return 0;
1235
+ }
1236
+ score += 10;
1237
+ }
1238
+ if (node.relevanceSignals) {
1239
+ for (const signal of node.relevanceSignals) {
1240
+ if (signal.startsWith("recentPage:")) {
1241
+ const page = signal.slice("recentPage:".length);
1242
+ if (context.recentPages.includes(page)) {
1243
+ score += 20;
1244
+ }
1245
+ }
1246
+ if (signal.startsWith("timeOfDay:")) {
1247
+ const timeRange = signal.slice("timeOfDay:".length);
1248
+ const hour = context.localHour;
1249
+ if (timeRange === "morning" && hour >= 5 && hour < 12)
1250
+ score += 15;
1251
+ if (timeRange === "afternoon" && hour >= 12 && hour < 17)
1252
+ score += 15;
1253
+ if (timeRange === "evening" && hour >= 17 && hour < 21)
1254
+ score += 15;
1255
+ if (timeRange === "night" && (hour >= 21 || hour < 5))
1256
+ score += 15;
1257
+ }
1258
+ if (signal.startsWith("preference:")) {
1259
+ const pref = signal.slice("preference:".length);
1260
+ if (context.preferences[pref]) {
1261
+ score += 20;
1262
+ }
1263
+ }
1264
+ if (signal.startsWith("tier:")) {
1265
+ const requiredTier = signal.slice("tier:".length);
1266
+ const tierOrder = ["free", "starter", "pro", "enterprise"];
1267
+ if (tierOrder.indexOf(context.tier) >= tierOrder.indexOf(requiredTier)) {
1268
+ score += 15;
1269
+ }
1270
+ }
1271
+ }
1272
+ }
1273
+ if (node.defaultHidden) {
1274
+ score -= 30;
1275
+ }
1276
+ return Math.max(0, Math.min(100, score));
1277
+ }
1278
+ function orderComponentsByRelevance(tree, context, scoreRelevance) {
1279
+ const scored = [];
1280
+ tree.nodes.forEach((node, id) => {
1281
+ scored.push({
1282
+ id,
1283
+ score: scoreRelevance(node, context)
1284
+ });
1285
+ });
1286
+ return scored.sort((a, b) => b.score - a.score).map((s) => s.id);
1287
+ }
1288
+ function findHiddenComponents(tree, context, scoreRelevance) {
1289
+ const hidden = [];
1290
+ tree.nodes.forEach((node, id) => {
1291
+ const score = scoreRelevance(node, context);
1292
+ if (score === 0) {
1293
+ hidden.push(id);
1294
+ }
1295
+ });
1296
+ return hidden;
1297
+ }
1298
+ function computeSkeletonHints(route, context, tree) {
1299
+ let layout = "custom";
1300
+ if (route === "/" || route.includes("dashboard")) {
1301
+ layout = "dashboard";
1302
+ } else if (route.includes("chat") || route.includes("message")) {
1303
+ layout = "chat";
1304
+ } else if (route.includes("setting") || route.includes("config")) {
1305
+ layout = "settings";
1306
+ } else if (route.includes("tool")) {
1307
+ layout = "tools";
1308
+ }
1309
+ const baseHeight = context.viewport.height;
1310
+ const contentMultiplier = tree.nodes.size > 10 ? 1.5 : 1;
1311
+ const estimatedHeight = Math.round(baseHeight * contentMultiplier);
1312
+ const sections = tree.getChildren(tree.rootId).map((child, i) => ({
1313
+ id: child.id,
1314
+ height: Math.round(estimatedHeight / (tree.nodes.size || 1)),
1315
+ priority: i + 1
1316
+ }));
1317
+ return {
1318
+ layout,
1319
+ estimatedHeight,
1320
+ sections
1321
+ };
1322
+ }
1323
+ function getPrefetchDepth(context) {
1324
+ switch (context.connection) {
1325
+ case "fast":
1326
+ case "4g":
1327
+ return { prefetch: 5, prerender: 1 };
1328
+ case "3g":
1329
+ return { prefetch: 3, prerender: 0 };
1330
+ case "2g":
1331
+ return { prefetch: 1, prerender: 0 };
1332
+ case "slow-2g":
1333
+ return { prefetch: 0, prerender: 0 };
1334
+ default:
1335
+ return { prefetch: 3, prerender: 0 };
1336
+ }
1337
+ }
1338
+
1339
+ class HeuristicAdapter {
1340
+ name = "heuristic";
1341
+ config;
1342
+ constructor(config = {}) {
1343
+ this.config = {
1344
+ ...DEFAULT_CONFIG,
1345
+ ...config,
1346
+ tierFeatures: config.tierFeatures ?? DEFAULT_CONFIG.tierFeatures,
1347
+ signals: config.signals ?? DEFAULT_CONFIG.signals
1348
+ };
1349
+ }
1350
+ async route(path, context, tree) {
1351
+ const startTime = Date.now();
1352
+ const sessionId = this.generateSessionId(path, context);
1353
+ const featureFlags = { ...this.config.tierFeatures[context.tier] };
1354
+ const theme = this.config.signals.deriveTheme ? this.config.signals.deriveTheme(context) : defaultDeriveTheme(context);
1355
+ const accent = this.config.signals.deriveAccent ? this.config.signals.deriveAccent(context) : this.config.defaultAccent;
1356
+ const density = determineDensity(context);
1357
+ const scoreRelevance = this.config.signals.scoreRelevance ?? defaultScoreRelevance;
1358
+ const componentOrder = orderComponentsByRelevance(tree, context, scoreRelevance);
1359
+ const hiddenComponents = findHiddenComponents(tree, context, scoreRelevance);
1360
+ const predictions = this.config.signals.predictNavigation ? this.config.signals.predictNavigation(path, context) : defaultPredictNavigation(path, context, this.config.defaultPaths, this.config.maxSpeculationPaths);
1361
+ const { prefetch: prefetchDepth, prerender: prerenderCount } = getPrefetchDepth(context);
1362
+ const prefetch = predictions.slice(0, prefetchDepth);
1363
+ const prerender = predictions.slice(0, prerenderCount);
1364
+ const skeleton = computeSkeletonHints(path, context, tree);
1365
+ return {
1366
+ route: path,
1367
+ sessionId,
1368
+ componentOrder,
1369
+ hiddenComponents,
1370
+ featureFlags,
1371
+ theme,
1372
+ accent,
1373
+ density,
1374
+ prefetch,
1375
+ prerender,
1376
+ skeleton,
1377
+ routedAt: startTime,
1378
+ routerName: this.name,
1379
+ confidence: 0.85
1380
+ };
1381
+ }
1382
+ async speculate(currentPath, context) {
1383
+ return this.config.signals.predictNavigation ? this.config.signals.predictNavigation(currentPath, context) : defaultPredictNavigation(currentPath, context, this.config.defaultPaths, this.config.maxSpeculationPaths);
1384
+ }
1385
+ personalizeTree(tree, decision) {
1386
+ const cloned = tree.clone();
1387
+ if (decision.hiddenComponents) {
1388
+ for (const id of decision.hiddenComponents) {
1389
+ const node = cloned.getNode(id);
1390
+ if (node) {
1391
+ node.defaultHidden = true;
1392
+ }
1393
+ }
1394
+ }
1395
+ return cloned;
1396
+ }
1397
+ emotionToAccent(emotionState) {
1398
+ if (this.config.signals.deriveAccent) {
1399
+ return this.config.signals.deriveAccent({
1400
+ emotionState,
1401
+ tier: "free",
1402
+ recentPages: [],
1403
+ dwellTimes: new Map,
1404
+ clickPatterns: [],
1405
+ preferences: {},
1406
+ viewport: { width: 0, height: 0 },
1407
+ connection: "fast",
1408
+ reducedMotion: false,
1409
+ localHour: 12,
1410
+ timezone: "UTC",
1411
+ isNewSession: true
1412
+ });
1413
+ }
1414
+ return this.config.defaultAccent;
1415
+ }
1416
+ generateSessionId(path, context) {
1417
+ const base = path.replace(/^\/|\/$/g, "").replace(/\//g, "-") || "index";
1418
+ const userId = context.userId || "anon";
1419
+ const sessionPrefix = context.sessionId || Date.now().toString(36);
1420
+ return `${base}-${userId.slice(0, 8)}-${sessionPrefix.slice(0, 8)}`;
1421
+ }
1422
+ }
1423
+ // src/router/context-extractor.ts
1424
+ function parseCookies(cookieHeader) {
1425
+ if (!cookieHeader)
1426
+ return {};
1427
+ return cookieHeader.split(";").reduce((acc, cookie) => {
1428
+ const [key, value] = cookie.trim().split("=");
1429
+ if (key && value) {
1430
+ acc[key] = decodeURIComponent(value);
1431
+ }
1432
+ return acc;
1433
+ }, {});
1434
+ }
1435
+ function parseJSON(value, fallback) {
1436
+ if (!value)
1437
+ return fallback;
1438
+ try {
1439
+ return JSON.parse(value);
1440
+ } catch {
1441
+ return fallback;
1442
+ }
1443
+ }
1444
+ function extractViewport(request) {
1445
+ const headers = request.headers;
1446
+ const viewportWidth = headers.get("sec-ch-viewport-width");
1447
+ const viewportHeight = headers.get("sec-ch-viewport-height");
1448
+ const dpr = headers.get("sec-ch-dpr");
1449
+ if (viewportWidth && viewportHeight) {
1450
+ return {
1451
+ width: parseInt(viewportWidth, 10),
1452
+ height: parseInt(viewportHeight, 10),
1453
+ devicePixelRatio: dpr ? parseFloat(dpr) : undefined
1454
+ };
1455
+ }
1456
+ const xViewport = headers.get("x-viewport");
1457
+ if (xViewport) {
1458
+ const [width, height, devicePixelRatio] = xViewport.split(",").map(Number);
1459
+ return { width: width || 1920, height: height || 1080, devicePixelRatio };
1460
+ }
1461
+ return { width: 1920, height: 1080 };
1462
+ }
1463
+ function extractConnection(request) {
1464
+ const headers = request.headers;
1465
+ const downlink = headers.get("downlink");
1466
+ const rtt = headers.get("rtt");
1467
+ const ect = headers.get("ect");
1468
+ if (ect) {
1469
+ switch (ect) {
1470
+ case "4g":
1471
+ return "fast";
1472
+ case "3g":
1473
+ return "3g";
1474
+ case "2g":
1475
+ return "2g";
1476
+ case "slow-2g":
1477
+ return "slow-2g";
1478
+ }
1479
+ }
1480
+ if (downlink) {
1481
+ const mbps = parseFloat(downlink);
1482
+ if (mbps >= 10)
1483
+ return "fast";
1484
+ if (mbps >= 2)
1485
+ return "4g";
1486
+ if (mbps >= 0.5)
1487
+ return "3g";
1488
+ if (mbps >= 0.1)
1489
+ return "2g";
1490
+ return "slow-2g";
1491
+ }
1492
+ if (rtt) {
1493
+ const ms = parseInt(rtt, 10);
1494
+ if (ms < 50)
1495
+ return "fast";
1496
+ if (ms < 100)
1497
+ return "4g";
1498
+ if (ms < 300)
1499
+ return "3g";
1500
+ if (ms < 700)
1501
+ return "2g";
1502
+ return "slow-2g";
1503
+ }
1504
+ return "4g";
1505
+ }
1506
+ function extractReducedMotion(request) {
1507
+ const prefersReducedMotion = request.headers.get("sec-ch-prefers-reduced-motion");
1508
+ return prefersReducedMotion === "reduce";
1509
+ }
1510
+ function extractTimeContext(request) {
1511
+ const headers = request.headers;
1512
+ const xTimezone = headers.get("x-timezone");
1513
+ const xLocalHour = headers.get("x-local-hour");
1514
+ const cfTimezone = request.cf?.timezone;
1515
+ const timezone = xTimezone || cfTimezone || "UTC";
1516
+ const localHour = xLocalHour ? parseInt(xLocalHour, 10) : new Date().getUTCHours();
1517
+ return { timezone, localHour };
1518
+ }
1519
+ function extractIdentity(cookies, request) {
1520
+ const userId = cookies["user_id"] || request.headers.get("x-user-id") || undefined;
1521
+ const tierCookie = cookies["user_tier"];
1522
+ const tierHeader = request.headers.get("x-user-tier");
1523
+ const tier = tierCookie || tierHeader || "free";
1524
+ return { userId, tier };
1525
+ }
1526
+ function extractNavigationHistory(cookies) {
1527
+ const recentPages = parseJSON(cookies["recent_pages"], []);
1528
+ const dwellTimesObj = parseJSON(cookies["dwell_times"], {});
1529
+ const clickPatterns = parseJSON(cookies["click_patterns"], []);
1530
+ return {
1531
+ recentPages,
1532
+ dwellTimes: new Map(Object.entries(dwellTimesObj)),
1533
+ clickPatterns
1534
+ };
1535
+ }
1536
+ function extractEmotionState(cookies, request) {
1537
+ const xEmotion = request.headers.get("x-emotion-state");
1538
+ if (xEmotion) {
1539
+ return parseJSON(xEmotion, undefined);
1540
+ }
1541
+ const emotionCookie = cookies["emotion_state"];
1542
+ if (emotionCookie) {
1543
+ return parseJSON(emotionCookie, undefined);
1544
+ }
1545
+ return;
1546
+ }
1547
+ function extractPreferences(cookies) {
1548
+ return parseJSON(cookies["user_preferences"], {});
1549
+ }
1550
+ function extractSessionInfo(cookies) {
1551
+ const sessionId = cookies["session_id"];
1552
+ const sessionStarted = cookies["session_started"];
1553
+ return {
1554
+ sessionId,
1555
+ isNewSession: !sessionId,
1556
+ sessionStartedAt: sessionStarted ? new Date(sessionStarted) : undefined
1557
+ };
1558
+ }
1559
+ async function extractUserContext(request, options = {}) {
1560
+ const cookies = parseCookies(request.headers.get("cookie"));
1561
+ const viewport = extractViewport(request);
1562
+ const connection = extractConnection(request);
1563
+ const reducedMotion = extractReducedMotion(request);
1564
+ const { timezone, localHour } = extractTimeContext(request);
1565
+ const { userId, tier: initialTier } = extractIdentity(cookies, request);
1566
+ const { recentPages, dwellTimes, clickPatterns } = extractNavigationHistory(cookies);
1567
+ const preferences = extractPreferences(cookies);
1568
+ const { sessionId, isNewSession, sessionStartedAt } = extractSessionInfo(cookies);
1569
+ let tier = initialTier;
1570
+ if (options.resolveUserTier && userId) {
1571
+ try {
1572
+ tier = await options.resolveUserTier(userId);
1573
+ } catch {}
1574
+ }
1575
+ let emotionState = extractEmotionState(cookies, request);
1576
+ if (!emotionState && options.detectEmotion) {
1577
+ try {
1578
+ emotionState = await options.detectEmotion(request);
1579
+ } catch {}
1580
+ }
1581
+ let context = {
1582
+ userId,
1583
+ tier,
1584
+ recentPages,
1585
+ dwellTimes,
1586
+ clickPatterns,
1587
+ emotionState,
1588
+ preferences,
1589
+ viewport,
1590
+ connection,
1591
+ reducedMotion,
1592
+ localHour,
1593
+ timezone,
1594
+ sessionId,
1595
+ isNewSession,
1596
+ sessionStartedAt
1597
+ };
1598
+ if (options.enrich) {
1599
+ context = await options.enrich(context, request);
1600
+ }
1601
+ return context;
1602
+ }
1603
+ function createContextMiddleware(options = {}) {
1604
+ return async (request) => {
1605
+ return extractUserContext(request, options);
1606
+ };
1607
+ }
1608
+ function setContextCookies(response, context, currentPath) {
1609
+ const headers = new Headers(response.headers);
1610
+ const recentPages = [...context.recentPages.slice(-9), currentPath];
1611
+ headers.append("Set-Cookie", `recent_pages=${encodeURIComponent(JSON.stringify(recentPages))}; Path=/; Max-Age=604800; SameSite=Lax`);
1612
+ if (context.isNewSession) {
1613
+ const sessionId = `sess_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
1614
+ headers.append("Set-Cookie", `session_id=${sessionId}; Path=/; Max-Age=86400; SameSite=Lax`);
1615
+ headers.append("Set-Cookie", `session_started=${new Date().toISOString()}; Path=/; Max-Age=86400; SameSite=Lax`);
1616
+ }
1617
+ return new Response(response.body, {
1618
+ status: response.status,
1619
+ statusText: response.statusText,
1620
+ headers
1621
+ });
1622
+ }
1623
+ function addSpeculationHeaders(response, prefetch, prerender) {
1624
+ const headers = new Headers(response.headers);
1625
+ if (prefetch.length > 0) {
1626
+ const linkHeader = prefetch.map((path) => `<${path}>; rel=prefetch`).join(", ");
1627
+ headers.append("Link", linkHeader);
1628
+ }
1629
+ if (prerender.length > 0) {
1630
+ headers.set("X-Prerender-Hints", prerender.join(","));
1631
+ }
1632
+ return new Response(response.body, {
1633
+ status: response.status,
1634
+ statusText: response.statusText,
1635
+ headers
1636
+ });
1637
+ }
1638
+ function serializeToESIState(context) {
1639
+ const tierFeatures = {
1640
+ free: {
1641
+ aiInference: true,
1642
+ emotionTracking: true,
1643
+ collaboration: false,
1644
+ advancedInsights: false,
1645
+ customThemes: false,
1646
+ voiceSynthesis: false,
1647
+ imageAnalysis: false
1648
+ },
1649
+ starter: {
1650
+ aiInference: true,
1651
+ emotionTracking: true,
1652
+ collaboration: false,
1653
+ advancedInsights: true,
1654
+ customThemes: true,
1655
+ voiceSynthesis: false,
1656
+ imageAnalysis: false
1657
+ },
1658
+ pro: {
1659
+ aiInference: true,
1660
+ emotionTracking: true,
1661
+ collaboration: true,
1662
+ advancedInsights: true,
1663
+ customThemes: true,
1664
+ voiceSynthesis: true,
1665
+ imageAnalysis: true
1666
+ },
1667
+ enterprise: {
1668
+ aiInference: true,
1669
+ emotionTracking: true,
1670
+ collaboration: true,
1671
+ advancedInsights: true,
1672
+ customThemes: true,
1673
+ voiceSynthesis: true,
1674
+ imageAnalysis: true
1675
+ }
1676
+ };
1677
+ return {
1678
+ userTier: context.tier,
1679
+ emotionState: context.emotionState ? {
1680
+ primary: context.emotionState.primary,
1681
+ valence: context.emotionState.valence,
1682
+ arousal: context.emotionState.arousal,
1683
+ confidence: context.emotionState.confidence
1684
+ } : undefined,
1685
+ preferences: {
1686
+ theme: context.preferences.theme,
1687
+ reducedMotion: context.reducedMotion,
1688
+ language: context.preferences.language
1689
+ },
1690
+ sessionId: context.sessionId,
1691
+ localHour: context.localHour,
1692
+ timezone: context.timezone,
1693
+ features: tierFeatures[context.tier],
1694
+ userId: context.userId,
1695
+ isNewSession: context.isNewSession,
1696
+ recentPages: context.recentPages.slice(-10),
1697
+ viewport: {
1698
+ width: context.viewport.width,
1699
+ height: context.viewport.height
1700
+ },
1701
+ connection: context.connection
1702
+ };
1703
+ }
1704
+ function generateESIStateScript(esiState) {
1705
+ const stateJson = JSON.stringify(esiState);
1706
+ return `<script>window.__AEON_ESI_STATE__=${stateJson};</script>`;
1707
+ }
1708
+ function generateESIStateScriptFromContext(context) {
1709
+ const esiState = serializeToESIState(context);
1710
+ return generateESIStateScript(esiState);
1711
+ }
1712
+ // src/router/speculation.ts
1713
+ function supportsSpeculationRules() {
1714
+ if (typeof document === "undefined")
1715
+ return false;
1716
+ return "supports" in HTMLScriptElement && HTMLScriptElement.supports?.("speculationrules");
1717
+ }
1718
+ function supportsLinkPrefetch() {
1719
+ if (typeof document === "undefined")
1720
+ return false;
1721
+ const link = document.createElement("link");
1722
+ return link.relList?.supports?.("prefetch") ?? false;
1723
+ }
1724
+ function addSpeculationRules(prefetch, prerender) {
1725
+ if (!supportsSpeculationRules())
1726
+ return null;
1727
+ const rules = {};
1728
+ if (prefetch.length > 0) {
1729
+ rules.prefetch = [{ urls: prefetch }];
1730
+ }
1731
+ if (prerender.length > 0) {
1732
+ rules.prerender = [{ urls: prerender }];
1733
+ }
1734
+ if (Object.keys(rules).length === 0)
1735
+ return null;
1736
+ const script = document.createElement("script");
1737
+ script.type = "speculationrules";
1738
+ script.textContent = JSON.stringify(rules);
1739
+ document.head.appendChild(script);
1740
+ return script;
1741
+ }
1742
+ function removeSpeculationRules(script) {
1743
+ script.remove();
1744
+ }
1745
+ function linkPrefetch(path) {
1746
+ if (!supportsLinkPrefetch())
1747
+ return null;
1748
+ const existing = document.querySelector(`link[rel="prefetch"][href="${path}"]`);
1749
+ if (existing)
1750
+ return existing;
1751
+ const link = document.createElement("link");
1752
+ link.rel = "prefetch";
1753
+ link.href = path;
1754
+ document.head.appendChild(link);
1755
+ return link;
1756
+ }
1757
+ function removePrefetch(link) {
1758
+ link.remove();
1759
+ }
1760
+
1761
+ class SpeculationManager {
1762
+ options;
1763
+ state;
1764
+ observers = new Map;
1765
+ hoverTimers = new Map;
1766
+ speculationScript = null;
1767
+ prefetchLinks = new Map;
1768
+ constructor(options = {}) {
1769
+ this.options = {
1770
+ maxPrefetch: options.maxPrefetch ?? 5,
1771
+ maxPrerender: options.maxPrerender ?? 1,
1772
+ hoverDelay: options.hoverDelay ?? 100,
1773
+ prefetchOnVisible: options.prefetchOnVisible ?? true,
1774
+ visibilityThreshold: options.visibilityThreshold ?? 0.1,
1775
+ cacheDuration: options.cacheDuration ?? 5 * 60 * 1000,
1776
+ onSpeculate: options.onSpeculate ?? (() => {})
1777
+ };
1778
+ this.state = {
1779
+ prefetched: new Set,
1780
+ prerendered: new Set,
1781
+ pending: new Set
1782
+ };
1783
+ }
1784
+ initFromHints(prefetch = [], prerender = []) {
1785
+ const newPrefetch = prefetch.filter((p) => !this.state.prefetched.has(p) && !this.state.prerendered.has(p)).slice(0, this.options.maxPrefetch);
1786
+ const newPrerender = prerender.filter((p) => !this.state.prerendered.has(p)).slice(0, this.options.maxPrerender);
1787
+ if (supportsSpeculationRules()) {
1788
+ this.speculationScript = addSpeculationRules(newPrefetch, newPrerender);
1789
+ newPrefetch.forEach((p) => {
1790
+ this.state.prefetched.add(p);
1791
+ this.options.onSpeculate(p, "prefetch");
1792
+ });
1793
+ newPrerender.forEach((p) => {
1794
+ this.state.prerendered.add(p);
1795
+ this.options.onSpeculate(p, "prerender");
1796
+ });
1797
+ } else {
1798
+ newPrefetch.forEach((path) => {
1799
+ const link = linkPrefetch(path);
1800
+ if (link) {
1801
+ this.prefetchLinks.set(path, link);
1802
+ this.state.prefetched.add(path);
1803
+ this.options.onSpeculate(path, "prefetch");
1804
+ }
1805
+ });
1806
+ }
1807
+ }
1808
+ prefetch(path) {
1809
+ if (this.state.prefetched.has(path) || this.state.prerendered.has(path)) {
1810
+ return false;
1811
+ }
1812
+ if (this.state.prefetched.size >= this.options.maxPrefetch) {
1813
+ return false;
1814
+ }
1815
+ if (supportsSpeculationRules()) {
1816
+ const allPrefetch = [...this.state.prefetched, path];
1817
+ const allPrerender = [...this.state.prerendered];
1818
+ if (this.speculationScript) {
1819
+ removeSpeculationRules(this.speculationScript);
1820
+ }
1821
+ this.speculationScript = addSpeculationRules(allPrefetch, allPrerender);
1822
+ } else {
1823
+ const link = linkPrefetch(path);
1824
+ if (link) {
1825
+ this.prefetchLinks.set(path, link);
1826
+ }
1827
+ }
1828
+ this.state.prefetched.add(path);
1829
+ this.options.onSpeculate(path, "prefetch");
1830
+ return true;
1831
+ }
1832
+ watchHover(element) {
1833
+ const path = new URL(element.href, window.location.href).pathname;
1834
+ const handleMouseEnter = () => {
1835
+ if (this.state.prefetched.has(path) || this.state.pending.has(path)) {
1836
+ return;
1837
+ }
1838
+ this.state.pending.add(path);
1839
+ const timer = setTimeout(() => {
1840
+ this.prefetch(path);
1841
+ this.state.pending.delete(path);
1842
+ }, this.options.hoverDelay);
1843
+ this.hoverTimers.set(element, timer);
1844
+ };
1845
+ const handleMouseLeave = () => {
1846
+ const timer = this.hoverTimers.get(element);
1847
+ if (timer) {
1848
+ clearTimeout(timer);
1849
+ this.hoverTimers.delete(element);
1850
+ }
1851
+ this.state.pending.delete(path);
1852
+ };
1853
+ element.addEventListener("mouseenter", handleMouseEnter);
1854
+ element.addEventListener("mouseleave", handleMouseLeave);
1855
+ return () => {
1856
+ element.removeEventListener("mouseenter", handleMouseEnter);
1857
+ element.removeEventListener("mouseleave", handleMouseLeave);
1858
+ handleMouseLeave();
1859
+ };
1860
+ }
1861
+ watchVisible(element) {
1862
+ if (!this.options.prefetchOnVisible) {
1863
+ return () => {};
1864
+ }
1865
+ const path = new URL(element.href, window.location.href).pathname;
1866
+ const observer = new IntersectionObserver((entries) => {
1867
+ entries.forEach((entry) => {
1868
+ if (entry.isIntersecting) {
1869
+ this.prefetch(path);
1870
+ observer.disconnect();
1871
+ this.observers.delete(element);
1872
+ }
1873
+ });
1874
+ }, { threshold: this.options.visibilityThreshold });
1875
+ observer.observe(element);
1876
+ this.observers.set(element, observer);
1877
+ return () => {
1878
+ observer.disconnect();
1879
+ this.observers.delete(element);
1880
+ };
1881
+ }
1882
+ watchAllLinks() {
1883
+ const links = document.querySelectorAll('a[href^="/"]');
1884
+ const cleanups = [];
1885
+ links.forEach((link) => {
1886
+ if (link instanceof HTMLAnchorElement) {
1887
+ cleanups.push(this.watchHover(link));
1888
+ cleanups.push(this.watchVisible(link));
1889
+ }
1890
+ });
1891
+ return () => {
1892
+ cleanups.forEach((cleanup) => cleanup());
1893
+ };
1894
+ }
1895
+ clear() {
1896
+ if (this.speculationScript) {
1897
+ removeSpeculationRules(this.speculationScript);
1898
+ this.speculationScript = null;
1899
+ }
1900
+ this.prefetchLinks.forEach((link) => removePrefetch(link));
1901
+ this.prefetchLinks.clear();
1902
+ this.observers.forEach((observer) => observer.disconnect());
1903
+ this.observers.clear();
1904
+ this.hoverTimers.forEach((timer) => clearTimeout(timer));
1905
+ this.hoverTimers.clear();
1906
+ this.state.prefetched.clear();
1907
+ this.state.prerendered.clear();
1908
+ this.state.pending.clear();
1909
+ }
1910
+ getState() {
1911
+ return {
1912
+ prefetched: new Set(this.state.prefetched),
1913
+ prerendered: new Set(this.state.prerendered),
1914
+ pending: new Set(this.state.pending)
1915
+ };
1916
+ }
1917
+ }
1918
+ function createSpeculationHook(useState2, useEffect2, useRef) {
1919
+ return function useSpeculation(options = {}) {
1920
+ const managerRef = useRef(null);
1921
+ const [state, setState] = useState2({
1922
+ prefetched: new Set,
1923
+ prerendered: new Set,
1924
+ pending: new Set
1925
+ });
1926
+ useEffect2(() => {
1927
+ managerRef.current = new SpeculationManager({
1928
+ ...options,
1929
+ onSpeculate: (path, type) => {
1930
+ options.onSpeculate?.(path, type);
1931
+ setState(managerRef.current.getState());
1932
+ }
1933
+ });
1934
+ const cleanup = managerRef.current.watchAllLinks();
1935
+ return () => {
1936
+ cleanup();
1937
+ managerRef.current?.clear();
1938
+ };
1939
+ }, []);
1940
+ return {
1941
+ state,
1942
+ prefetch: (path) => managerRef.current?.prefetch(path),
1943
+ initFromHints: (prefetch, prerender) => managerRef.current?.initFromHints(prefetch, prerender),
1944
+ clear: () => managerRef.current?.clear()
1945
+ };
1946
+ };
1947
+ }
1948
+ function autoInitSpeculation() {
1949
+ if (typeof window === "undefined")
1950
+ return null;
1951
+ const hints = window.__AEON_SPECULATION__;
1952
+ const manager = new SpeculationManager;
1953
+ if (hints) {
1954
+ manager.initFromHints(hints.prefetch || [], hints.prerender || []);
1955
+ }
1956
+ manager.watchAllLinks();
1957
+ return manager;
1958
+ }
1959
+ // src/router/esi-control.ts
1960
+ function generateSchemaPrompt(schema) {
1961
+ const schemaDescription = describeZodSchema(schema);
1962
+ return `
1963
+
1964
+ Respond with valid JSON matching this schema:
1965
+ ${schemaDescription}
1966
+
1967
+ Output ONLY the JSON, no markdown, no explanation.`;
1968
+ }
1969
+ function describeZodSchema(schema) {
1970
+ const def = schema._def;
1971
+ if (def.typeName === "ZodObject") {
1972
+ const shape = def.shape;
1973
+ const fields = Object.entries(shape).map(([key, fieldSchema]) => {
1974
+ const fieldDef = fieldSchema._def;
1975
+ return ` "${key}": ${describeZodType(fieldDef)}`;
1976
+ });
1977
+ return `{
1978
+ ${fields.join(`,
1979
+ `)}
1980
+ }`;
1981
+ }
1982
+ return describeZodType(def);
1983
+ }
1984
+ function describeZodType(def) {
1985
+ const typeName = def.typeName;
1986
+ switch (typeName) {
1987
+ case "ZodString":
1988
+ return "string";
1989
+ case "ZodNumber":
1990
+ return "number";
1991
+ case "ZodBoolean":
1992
+ return "boolean";
1993
+ case "ZodArray":
1994
+ const innerType = def.type;
1995
+ return `array of ${describeZodType(innerType._def)}`;
1996
+ case "ZodEnum":
1997
+ const values = def.values;
1998
+ return `one of: ${values.map((v) => `"${v}"`).join(" | ")}`;
1999
+ case "ZodLiteral":
2000
+ return JSON.stringify(def.value);
2001
+ case "ZodOptional":
2002
+ const optionalType = def.innerType;
2003
+ return `${describeZodType(optionalType._def)} (optional)`;
2004
+ case "ZodNullable":
2005
+ const nullableType = def.innerType;
2006
+ return `${describeZodType(nullableType._def)} or null`;
2007
+ case "ZodObject":
2008
+ return "object";
2009
+ default:
2010
+ return "any";
2011
+ }
2012
+ }
2013
+ function parseWithSchema(output, schema) {
2014
+ let jsonStr = output.trim();
2015
+ if (jsonStr.startsWith("```")) {
2016
+ const match = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);
2017
+ if (match) {
2018
+ jsonStr = match[1].trim();
2019
+ }
2020
+ }
2021
+ let parsed;
2022
+ try {
2023
+ parsed = JSON.parse(jsonStr);
2024
+ } catch (e) {
2025
+ const jsonMatch = jsonStr.match(/\{[\s\S]*\}/);
2026
+ if (jsonMatch) {
2027
+ try {
2028
+ parsed = JSON.parse(jsonMatch[0]);
2029
+ } catch {
2030
+ return {
2031
+ success: false,
2032
+ errors: [`Failed to parse JSON: ${e instanceof Error ? e.message : "Unknown error"}`]
2033
+ };
2034
+ }
2035
+ } else {
2036
+ return {
2037
+ success: false,
2038
+ errors: [`No valid JSON found in output`]
2039
+ };
2040
+ }
2041
+ }
2042
+ const result = schema.safeParse(parsed);
2043
+ if (result.success) {
2044
+ return { success: true, data: result.data };
2045
+ }
2046
+ return {
2047
+ success: false,
2048
+ errors: result.error.errors.map((e) => `${e.path.join(".")}: ${e.message}`)
2049
+ };
2050
+ }
2051
+ function createControlProcessor(processESI) {
2052
+ return {
2053
+ async processWithSchema(prompt, schema, params, context) {
2054
+ const fullPrompt = prompt + generateSchemaPrompt(schema);
2055
+ const directive = {
2056
+ id: `esi-schema-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
2057
+ params: {
2058
+ model: "llm",
2059
+ ...params
2060
+ },
2061
+ content: {
2062
+ type: "text",
2063
+ value: fullPrompt
2064
+ }
2065
+ };
2066
+ const result = await processESI(directive, context);
2067
+ if (!result.success || !result.output) {
2068
+ return {
2069
+ ...result,
2070
+ validationErrors: result.error ? [result.error] : ["No output"]
2071
+ };
2072
+ }
2073
+ const parseResult = parseWithSchema(result.output, schema);
2074
+ if (parseResult.success) {
2075
+ return {
2076
+ ...result,
2077
+ data: parseResult.data,
2078
+ rawOutput: result.output
2079
+ };
2080
+ }
2081
+ return {
2082
+ ...result,
2083
+ rawOutput: result.output,
2084
+ validationErrors: parseResult.errors
2085
+ };
2086
+ },
2087
+ async processIf(directive, context) {
2088
+ const schemaResult = await this.processWithSchema(directive.prompt, directive.schema, directive.params || {}, context);
2089
+ let conditionMet = false;
2090
+ if (schemaResult.data !== undefined) {
2091
+ try {
2092
+ conditionMet = directive.when(schemaResult.data, context);
2093
+ } catch (e) {
2094
+ conditionMet = false;
2095
+ }
2096
+ }
2097
+ return {
2098
+ id: directive.id,
2099
+ conditionMet,
2100
+ data: schemaResult.data,
2101
+ inferenceResult: schemaResult
2102
+ };
2103
+ },
2104
+ async processMatch(directive, context) {
2105
+ const schemaResult = await this.processWithSchema(directive.prompt, directive.schema, directive.params || {}, context);
2106
+ let matchedCase;
2107
+ if (schemaResult.data !== undefined) {
2108
+ for (const caseItem of directive.cases) {
2109
+ try {
2110
+ if (caseItem.match(schemaResult.data, context)) {
2111
+ matchedCase = caseItem.id;
2112
+ break;
2113
+ }
2114
+ } catch {}
2115
+ }
2116
+ if (!matchedCase && directive.defaultCase) {
2117
+ matchedCase = directive.defaultCase;
2118
+ }
2119
+ }
2120
+ return {
2121
+ id: directive.id,
2122
+ matchedCase,
2123
+ data: schemaResult.data,
2124
+ inferenceResult: schemaResult
2125
+ };
2126
+ }
2127
+ };
2128
+ }
2129
+ function esiIf(prompt, schema, when, options = {}) {
2130
+ return {
2131
+ id: `esi-if-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
2132
+ prompt,
2133
+ schema,
2134
+ when,
2135
+ params: options
2136
+ };
2137
+ }
2138
+ function esiMatch(prompt, schema, cases, defaultCase, options = {}) {
2139
+ return {
2140
+ id: `esi-match-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
2141
+ prompt,
2142
+ schema,
2143
+ cases,
2144
+ defaultCase,
2145
+ params: options
2146
+ };
2147
+ }
2148
+ // src/router/esi-control-react.tsx
2149
+ import {
2150
+ createContext as createContext2,
2151
+ useContext as useContext2,
2152
+ useEffect as useEffect2,
2153
+ useState as useState2,
2154
+ useCallback as useCallback2,
2155
+ useMemo,
2156
+ Children,
2157
+ isValidElement
2158
+ } from "react";
2159
+ import { jsxDEV as jsxDEV2, Fragment } from "react/jsx-dev-runtime";
2160
+ var PresenceContext = createContext2(null);
2161
+ function usePresenceForESI() {
2162
+ const ctx = useContext2(PresenceContext);
2163
+ return ctx || { users: [], localUser: null };
2164
+ }
2165
+ function ESIStructured({
2166
+ children,
2167
+ prompt,
2168
+ schema,
2169
+ render,
2170
+ fallback,
2171
+ loading = "...",
2172
+ retryOnFail = false,
2173
+ maxRetries = 2,
2174
+ temperature,
2175
+ maxTokens,
2176
+ cacheTtl,
2177
+ onSuccess,
2178
+ onValidationError,
2179
+ onError,
2180
+ className
2181
+ }) {
2182
+ const { process: process2, enabled } = useESI();
2183
+ const [result, setResult] = useState2(null);
2184
+ const [isLoading, setIsLoading] = useState2(true);
2185
+ const [retryCount, setRetryCount] = useState2(0);
2186
+ const promptText = prompt || (typeof children === "string" ? children : String(children || ""));
2187
+ const fullPrompt = promptText + generateSchemaPrompt(schema);
2188
+ useEffect2(() => {
2189
+ if (!enabled) {
2190
+ setIsLoading(false);
2191
+ return;
2192
+ }
2193
+ async function runInference() {
2194
+ setIsLoading(true);
2195
+ const directive = {
2196
+ id: `esi-structured-${Date.now()}`,
2197
+ params: {
2198
+ model: "llm",
2199
+ temperature,
2200
+ maxTokens,
2201
+ cacheTtl
2202
+ },
2203
+ content: {
2204
+ type: "text",
2205
+ value: fullPrompt
2206
+ }
2207
+ };
2208
+ const inferenceResult = await process2(directive);
2209
+ if (!inferenceResult.success || !inferenceResult.output) {
2210
+ setResult({
2211
+ ...inferenceResult,
2212
+ validationErrors: [inferenceResult.error || "No output"]
2213
+ });
2214
+ onError?.(inferenceResult.error || "Inference failed");
2215
+ setIsLoading(false);
2216
+ return;
2217
+ }
2218
+ const parseResult = parseWithSchema(inferenceResult.output, schema);
2219
+ if (parseResult.success) {
2220
+ const schemaResult = {
2221
+ ...inferenceResult,
2222
+ data: parseResult.data,
2223
+ rawOutput: inferenceResult.output
2224
+ };
2225
+ setResult(schemaResult);
2226
+ onSuccess?.(parseResult.data);
2227
+ } else {
2228
+ if (retryOnFail && retryCount < maxRetries) {
2229
+ setRetryCount((c) => c + 1);
2230
+ } else {
2231
+ const schemaResult = {
2232
+ ...inferenceResult,
2233
+ rawOutput: inferenceResult.output,
2234
+ validationErrors: parseResult.errors
2235
+ };
2236
+ setResult(schemaResult);
2237
+ onValidationError?.(parseResult.errors, inferenceResult.output);
2238
+ }
2239
+ }
2240
+ setIsLoading(false);
2241
+ }
2242
+ runInference();
2243
+ }, [fullPrompt, enabled, retryCount]);
2244
+ if (isLoading) {
2245
+ return /* @__PURE__ */ jsxDEV2("span", {
2246
+ className,
2247
+ children: loading
2248
+ }, undefined, false, undefined, this);
2249
+ }
2250
+ if (!result?.data) {
2251
+ return /* @__PURE__ */ jsxDEV2("span", {
2252
+ className,
2253
+ children: fallback
2254
+ }, undefined, false, undefined, this);
2255
+ }
2256
+ if (render) {
2257
+ return /* @__PURE__ */ jsxDEV2("span", {
2258
+ className,
2259
+ children: render(result.data, {
2260
+ cached: result.cached,
2261
+ latencyMs: result.latencyMs
2262
+ })
2263
+ }, undefined, false, undefined, this);
2264
+ }
2265
+ return /* @__PURE__ */ jsxDEV2("span", {
2266
+ className,
2267
+ children: JSON.stringify(result.data)
2268
+ }, undefined, false, undefined, this);
2269
+ }
2270
+ function ESIIf({
2271
+ children,
2272
+ prompt,
2273
+ schema,
2274
+ when,
2275
+ then: thenContent,
2276
+ else: elseContent,
2277
+ loading = null,
2278
+ temperature,
2279
+ cacheTtl,
2280
+ onEvaluate,
2281
+ className
2282
+ }) {
2283
+ const [conditionMet, setConditionMet] = useState2(null);
2284
+ const [data, setData] = useState2(null);
2285
+ const handleSuccess = useCallback2((result) => {
2286
+ setData(result);
2287
+ try {
2288
+ const met = when(result, {});
2289
+ setConditionMet(met);
2290
+ onEvaluate?.(result, met);
2291
+ } catch {
2292
+ setConditionMet(false);
2293
+ }
2294
+ }, [when, onEvaluate]);
2295
+ return /* @__PURE__ */ jsxDEV2("span", {
2296
+ className,
2297
+ children: [
2298
+ /* @__PURE__ */ jsxDEV2(ESIStructured, {
2299
+ prompt,
2300
+ schema,
2301
+ temperature,
2302
+ cacheTtl,
2303
+ loading,
2304
+ onSuccess: handleSuccess,
2305
+ render: () => null,
2306
+ children
2307
+ }, undefined, false, undefined, this),
2308
+ conditionMet === true && thenContent,
2309
+ conditionMet === false && elseContent
2310
+ ]
2311
+ }, undefined, true, undefined, this);
2312
+ }
2313
+ function ESICase({ children }) {
2314
+ return /* @__PURE__ */ jsxDEV2(Fragment, {
2315
+ children
2316
+ }, undefined, false, undefined, this);
2317
+ }
2318
+ function ESIDefault({ children }) {
2319
+ return /* @__PURE__ */ jsxDEV2(Fragment, {
2320
+ children
2321
+ }, undefined, false, undefined, this);
2322
+ }
2323
+ function ESIMatch({
2324
+ children,
2325
+ prompt,
2326
+ schema,
2327
+ loading = null,
2328
+ temperature,
2329
+ cacheTtl,
2330
+ onMatch,
2331
+ className
2332
+ }) {
2333
+ const [matchedIndex, setMatchedIndex] = useState2(null);
2334
+ const [data, setData] = useState2(null);
2335
+ const { cases, defaultCase, promptFromChildren } = useMemo(() => {
2336
+ const cases2 = [];
2337
+ let defaultCase2 = null;
2338
+ let promptFromChildren2 = "";
2339
+ Children.forEach(children, (child) => {
2340
+ if (!isValidElement(child)) {
2341
+ if (typeof child === "string") {
2342
+ promptFromChildren2 += child;
2343
+ }
2344
+ return;
2345
+ }
2346
+ if (child.type === ESICase) {
2347
+ const props = child.props;
2348
+ cases2.push({
2349
+ match: props.match,
2350
+ content: props.children
2351
+ });
2352
+ } else if (child.type === ESIDefault) {
2353
+ defaultCase2 = child.props.children;
2354
+ }
2355
+ });
2356
+ return { cases: cases2, defaultCase: defaultCase2, promptFromChildren: promptFromChildren2 };
2357
+ }, [children]);
2358
+ const handleSuccess = useCallback2((result) => {
2359
+ setData(result);
2360
+ for (let i = 0;i < cases.length; i++) {
2361
+ try {
2362
+ if (cases[i].match(result, {})) {
2363
+ setMatchedIndex(i);
2364
+ onMatch?.(result, i);
2365
+ return;
2366
+ }
2367
+ } catch {}
2368
+ }
2369
+ setMatchedIndex(-1);
2370
+ onMatch?.(result, -1);
2371
+ }, [cases, onMatch]);
2372
+ const finalPrompt = prompt || promptFromChildren;
2373
+ return /* @__PURE__ */ jsxDEV2("span", {
2374
+ className,
2375
+ children: [
2376
+ /* @__PURE__ */ jsxDEV2(ESIStructured, {
2377
+ prompt: finalPrompt,
2378
+ schema,
2379
+ temperature,
2380
+ cacheTtl,
2381
+ loading,
2382
+ onSuccess: handleSuccess,
2383
+ render: () => null
2384
+ }, undefined, false, undefined, this),
2385
+ matchedIndex !== null && matchedIndex >= 0 && cases[matchedIndex]?.content,
2386
+ matchedIndex === -1 && defaultCase
2387
+ ]
2388
+ }, undefined, true, undefined, this);
2389
+ }
2390
+ function defaultDescribeUsers(users) {
2391
+ if (users.length === 0)
2392
+ return "No other users are viewing this content.";
2393
+ if (users.length === 1)
2394
+ return `1 user is viewing: ${describeUser(users[0])}`;
2395
+ const roles = [...new Set(users.map((u) => u.role).filter(Boolean))];
2396
+ const roleStr = roles.length > 0 ? ` with roles: ${roles.join(", ")}` : "";
2397
+ return `${users.length} users are viewing${roleStr}:
2398
+ ${users.map(describeUser).join(`
2399
+ `)}`;
2400
+ }
2401
+ function describeUser(user) {
2402
+ const parts = [user.name || user.userId];
2403
+ if (user.role)
2404
+ parts.push(`(${user.role})`);
2405
+ if (user.status)
2406
+ parts.push(`[${user.status}]`);
2407
+ return `- ${parts.join(" ")}`;
2408
+ }
2409
+ function ESICollaborative({
2410
+ children,
2411
+ prompt,
2412
+ schema,
2413
+ render,
2414
+ fallback,
2415
+ loading = "...",
2416
+ describeUsers = defaultDescribeUsers,
2417
+ reactToPresenceChange = true,
2418
+ presenceDebounce = 2000,
2419
+ temperature,
2420
+ maxTokens,
2421
+ cacheTtl,
2422
+ onSuccess,
2423
+ className
2424
+ }) {
2425
+ const presence = usePresenceForESI();
2426
+ const [debouncedUsers, setDebouncedUsers] = useState2(presence.users);
2427
+ const [result, setResult] = useState2(null);
2428
+ useEffect2(() => {
2429
+ if (!reactToPresenceChange)
2430
+ return;
2431
+ const timer = setTimeout(() => {
2432
+ setDebouncedUsers(presence.users);
2433
+ }, presenceDebounce);
2434
+ return () => clearTimeout(timer);
2435
+ }, [presence.users, reactToPresenceChange, presenceDebounce]);
2436
+ const basePrompt = prompt || (typeof children === "string" ? children : String(children || ""));
2437
+ const presenceDescription = describeUsers(debouncedUsers);
2438
+ const collaborativePrompt = `[Audience Context]
2439
+ ${presenceDescription}
2440
+
2441
+ [Task]
2442
+ ${basePrompt}
2443
+
2444
+ Consider ALL viewers when generating your response. The content should be relevant and appropriate for everyone currently viewing.`;
2445
+ const handleSuccess = useCallback2((data) => {
2446
+ setResult(data);
2447
+ onSuccess?.(data, debouncedUsers);
2448
+ }, [debouncedUsers, onSuccess]);
2449
+ return /* @__PURE__ */ jsxDEV2(ESIStructured, {
2450
+ prompt: collaborativePrompt,
2451
+ schema,
2452
+ temperature,
2453
+ maxTokens,
2454
+ cacheTtl,
2455
+ loading,
2456
+ fallback,
2457
+ onSuccess: handleSuccess,
2458
+ className,
2459
+ render: (data, meta) => {
2460
+ if (render) {
2461
+ return render(data, debouncedUsers);
2462
+ }
2463
+ return JSON.stringify(data);
2464
+ }
2465
+ }, undefined, false, undefined, this);
2466
+ }
2467
+ function ESIReflect({
2468
+ children,
2469
+ prompt,
2470
+ schema,
2471
+ until,
2472
+ maxIterations = 3,
2473
+ render,
2474
+ showProgress = false,
2475
+ fallback,
2476
+ loading = "...",
2477
+ onIteration,
2478
+ onComplete,
2479
+ className
2480
+ }) {
2481
+ const { process: process2, enabled } = useESI();
2482
+ const [currentResult, setCurrentResult] = useState2(null);
2483
+ const [iteration, setIteration] = useState2(0);
2484
+ const [isComplete, setIsComplete] = useState2(false);
2485
+ const [isLoading, setIsLoading] = useState2(true);
2486
+ const basePrompt = prompt || (typeof children === "string" ? children : String(children || ""));
2487
+ useEffect2(() => {
2488
+ if (!enabled) {
2489
+ setIsLoading(false);
2490
+ return;
2491
+ }
2492
+ async function runReflection() {
2493
+ setIsLoading(true);
2494
+ let currentIteration = 0;
2495
+ let lastResult = null;
2496
+ let previousAttempts = [];
2497
+ while (currentIteration < maxIterations) {
2498
+ let reflectionPrompt = basePrompt;
2499
+ if (currentIteration > 0 && lastResult) {
2500
+ reflectionPrompt = `[Previous Attempt ${currentIteration}]
2501
+ ${JSON.stringify(lastResult)}
2502
+
2503
+ [Reflection]
2504
+ The previous attempt did not meet the quality threshold. Please improve upon it.
2505
+
2506
+ [Original Task]
2507
+ ${basePrompt}`;
2508
+ }
2509
+ const fullPrompt = reflectionPrompt + generateSchemaPrompt(schema);
2510
+ const directive = {
2511
+ id: `esi-reflect-${Date.now()}-${currentIteration}`,
2512
+ params: { model: "llm" },
2513
+ content: { type: "text", value: fullPrompt }
2514
+ };
2515
+ const result = await process2(directive);
2516
+ if (!result.success || !result.output) {
2517
+ break;
2518
+ }
2519
+ const parseResult = parseWithSchema(result.output, schema);
2520
+ if (!parseResult.success) {
2521
+ currentIteration++;
2522
+ continue;
2523
+ }
2524
+ lastResult = parseResult.data;
2525
+ setCurrentResult(parseResult.data);
2526
+ setIteration(currentIteration + 1);
2527
+ onIteration?.(parseResult.data, currentIteration + 1);
2528
+ if (until(parseResult.data, currentIteration + 1)) {
2529
+ setIsComplete(true);
2530
+ onComplete?.(parseResult.data, currentIteration + 1);
2531
+ break;
2532
+ }
2533
+ previousAttempts.push(result.output);
2534
+ currentIteration++;
2535
+ }
2536
+ if (!isComplete && lastResult) {
2537
+ setIsComplete(true);
2538
+ onComplete?.(lastResult, currentIteration);
2539
+ }
2540
+ setIsLoading(false);
2541
+ }
2542
+ runReflection();
2543
+ }, [basePrompt, enabled, maxIterations]);
2544
+ if (isLoading) {
2545
+ if (showProgress && currentResult) {
2546
+ return /* @__PURE__ */ jsxDEV2("span", {
2547
+ className,
2548
+ children: [
2549
+ render ? render(currentResult, iteration) : JSON.stringify(currentResult),
2550
+ /* @__PURE__ */ jsxDEV2("span", {
2551
+ children: [
2552
+ " (refining... iteration ",
2553
+ iteration,
2554
+ ")"
2555
+ ]
2556
+ }, undefined, true, undefined, this)
2557
+ ]
2558
+ }, undefined, true, undefined, this);
2559
+ }
2560
+ return /* @__PURE__ */ jsxDEV2("span", {
2561
+ className,
2562
+ children: loading
2563
+ }, undefined, false, undefined, this);
2564
+ }
2565
+ if (!currentResult) {
2566
+ return /* @__PURE__ */ jsxDEV2("span", {
2567
+ className,
2568
+ children: fallback
2569
+ }, undefined, false, undefined, this);
2570
+ }
2571
+ if (render) {
2572
+ return /* @__PURE__ */ jsxDEV2("span", {
2573
+ className,
2574
+ children: render(currentResult, iteration)
2575
+ }, undefined, false, undefined, this);
2576
+ }
2577
+ return /* @__PURE__ */ jsxDEV2("span", {
2578
+ className,
2579
+ children: JSON.stringify(currentResult)
2580
+ }, undefined, false, undefined, this);
2581
+ }
2582
+ function ESIOptimize({
2583
+ children,
2584
+ prompt,
2585
+ schema,
2586
+ criteria = ["clarity", "relevance", "completeness", "conciseness"],
2587
+ targetQuality = 0.85,
2588
+ maxRounds = 3,
2589
+ onlyWhenAlone = true,
2590
+ render,
2591
+ fallback,
2592
+ loading = "...",
2593
+ onImprove,
2594
+ onOptimized,
2595
+ className
2596
+ }) {
2597
+ const { process: process2, enabled } = useESI();
2598
+ const presence = usePresenceForESI();
2599
+ const [result, setResult] = useState2(null);
2600
+ const [meta, setMeta] = useState2({
2601
+ rounds: 0,
2602
+ quality: 0,
2603
+ improvements: [],
2604
+ wasOptimized: false
2605
+ });
2606
+ const [isLoading, setIsLoading] = useState2(true);
2607
+ const basePrompt = prompt || (typeof children === "string" ? children : String(children || ""));
2608
+ const shouldOptimize = !onlyWhenAlone || presence.users.length <= 1;
2609
+ useEffect2(() => {
2610
+ if (!enabled) {
2611
+ setIsLoading(false);
2612
+ return;
2613
+ }
2614
+ async function runOptimization() {
2615
+ setIsLoading(true);
2616
+ const criteriaList = criteria.join(", ");
2617
+ const firstPassPrompt = `${basePrompt}
2618
+
2619
+ After generating your response, assess its quality on these criteria: ${criteriaList}
2620
+
2621
+ ${generateSchemaPrompt(schema)}
2622
+
2623
+ Additionally, include a self-assessment in this format:
2624
+ {
2625
+ "result": <your response matching the schema above>,
2626
+ "selfAssessment": {
2627
+ "quality": <0-1 score>,
2628
+ "strengths": [<list of strengths>],
2629
+ "weaknesses": [<list of weaknesses>],
2630
+ "improvementSuggestions": [<specific improvements>]
2631
+ }
2632
+ }`;
2633
+ let currentResult = null;
2634
+ let currentQuality = 0;
2635
+ let round = 0;
2636
+ let improvements = [];
2637
+ let lastWeaknesses = [];
2638
+ const firstResult = await process2({
2639
+ id: `esi-optimize-${Date.now()}-0`,
2640
+ params: { model: "llm" },
2641
+ content: { type: "text", value: firstPassPrompt }
2642
+ });
2643
+ if (!firstResult.success || !firstResult.output) {
2644
+ setIsLoading(false);
2645
+ return;
2646
+ }
2647
+ try {
2648
+ const parsed = JSON.parse(extractJson(firstResult.output));
2649
+ const validated = schema.safeParse(parsed.result);
2650
+ if (validated.success) {
2651
+ currentResult = validated.data;
2652
+ currentQuality = parsed.selfAssessment?.quality || 0.5;
2653
+ lastWeaknesses = parsed.selfAssessment?.weaknesses || [];
2654
+ round = 1;
2655
+ setResult(currentResult);
2656
+ setMeta({
2657
+ rounds: 1,
2658
+ quality: currentQuality,
2659
+ improvements: [],
2660
+ wasOptimized: false
2661
+ });
2662
+ onImprove?.(currentResult, 1, currentQuality);
2663
+ }
2664
+ } catch {
2665
+ const parseResult = parseWithSchema(firstResult.output, schema);
2666
+ if (parseResult.success) {
2667
+ currentResult = parseResult.data;
2668
+ currentQuality = 0.6;
2669
+ round = 1;
2670
+ setResult(currentResult);
2671
+ } else {
2672
+ setIsLoading(false);
2673
+ return;
2674
+ }
2675
+ }
2676
+ if (shouldOptimize && currentQuality < targetQuality) {
2677
+ while (round < maxRounds && currentQuality < targetQuality) {
2678
+ const optimizePrompt = `You previously generated this response:
2679
+ ${JSON.stringify(currentResult)}
2680
+
2681
+ Quality score: ${currentQuality.toFixed(2)}
2682
+ Weaknesses identified: ${lastWeaknesses.join(", ") || "none specified"}
2683
+
2684
+ Please improve the response, focusing on: ${criteriaList}
2685
+ Address the weaknesses and aim for a quality score above ${targetQuality}.
2686
+
2687
+ ${generateSchemaPrompt(schema)}
2688
+
2689
+ Include your improved self-assessment:
2690
+ {
2691
+ "result": <improved response>,
2692
+ "selfAssessment": {
2693
+ "quality": <0-1 score>,
2694
+ "strengths": [...],
2695
+ "weaknesses": [...],
2696
+ "improvementSuggestions": [...]
2697
+ },
2698
+ "improvementsMade": [<what you improved>]
2699
+ }`;
2700
+ const improvedResult = await process2({
2701
+ id: `esi-optimize-${Date.now()}-${round}`,
2702
+ params: { model: "llm" },
2703
+ content: { type: "text", value: optimizePrompt }
2704
+ });
2705
+ if (!improvedResult.success || !improvedResult.output) {
2706
+ break;
2707
+ }
2708
+ try {
2709
+ const parsed = JSON.parse(extractJson(improvedResult.output));
2710
+ const validated = schema.safeParse(parsed.result);
2711
+ if (validated.success) {
2712
+ const newQuality = parsed.selfAssessment?.quality || currentQuality;
2713
+ if (newQuality > currentQuality) {
2714
+ currentResult = validated.data;
2715
+ currentQuality = newQuality;
2716
+ lastWeaknesses = parsed.selfAssessment?.weaknesses || [];
2717
+ if (parsed.improvementsMade) {
2718
+ improvements.push(...parsed.improvementsMade);
2719
+ }
2720
+ setResult(currentResult);
2721
+ setMeta({
2722
+ rounds: round + 1,
2723
+ quality: currentQuality,
2724
+ improvements,
2725
+ wasOptimized: true
2726
+ });
2727
+ onImprove?.(currentResult, round + 1, currentQuality);
2728
+ }
2729
+ }
2730
+ } catch {}
2731
+ round++;
2732
+ }
2733
+ }
2734
+ if (currentResult) {
2735
+ setMeta((prev) => ({
2736
+ ...prev,
2737
+ rounds: round,
2738
+ quality: currentQuality,
2739
+ wasOptimized: round > 1
2740
+ }));
2741
+ onOptimized?.(currentResult, round, currentQuality);
2742
+ }
2743
+ setIsLoading(false);
2744
+ }
2745
+ runOptimization();
2746
+ }, [basePrompt, enabled, shouldOptimize, targetQuality, maxRounds]);
2747
+ if (isLoading) {
2748
+ return /* @__PURE__ */ jsxDEV2("span", {
2749
+ className,
2750
+ children: loading
2751
+ }, undefined, false, undefined, this);
2752
+ }
2753
+ if (!result) {
2754
+ return /* @__PURE__ */ jsxDEV2("span", {
2755
+ className,
2756
+ children: fallback
2757
+ }, undefined, false, undefined, this);
2758
+ }
2759
+ if (render) {
2760
+ return /* @__PURE__ */ jsxDEV2("span", {
2761
+ className,
2762
+ children: render(result, meta)
2763
+ }, undefined, false, undefined, this);
2764
+ }
2765
+ return /* @__PURE__ */ jsxDEV2("span", {
2766
+ className,
2767
+ children: JSON.stringify(result)
2768
+ }, undefined, false, undefined, this);
2769
+ }
2770
+ function extractJson(str) {
2771
+ let cleaned = str.trim();
2772
+ if (cleaned.startsWith("```")) {
2773
+ const match = cleaned.match(/```(?:json)?\s*([\s\S]*?)```/);
2774
+ if (match)
2775
+ cleaned = match[1].trim();
2776
+ }
2777
+ const jsonMatch = cleaned.match(/\{[\s\S]*\}/);
2778
+ if (jsonMatch)
2779
+ return jsonMatch[0];
2780
+ return cleaned;
2781
+ }
2782
+ function ESIAuto({
2783
+ children,
2784
+ prompt,
2785
+ schema,
2786
+ render,
2787
+ collaborativeThreshold = 2,
2788
+ optimizeSettings,
2789
+ fallback,
2790
+ loading,
2791
+ className
2792
+ }) {
2793
+ const presence = usePresenceForESI();
2794
+ const userCount = presence.users.length;
2795
+ const mode = userCount >= collaborativeThreshold ? "collaborative" : userCount === 1 ? "optimized" : "basic";
2796
+ if (mode === "collaborative") {
2797
+ return /* @__PURE__ */ jsxDEV2(ESICollaborative, {
2798
+ prompt,
2799
+ schema,
2800
+ fallback,
2801
+ loading,
2802
+ className,
2803
+ render: render ? (data) => render(data, "collaborative") : undefined,
2804
+ children
2805
+ }, undefined, false, undefined, this);
2806
+ }
2807
+ if (mode === "optimized") {
2808
+ return /* @__PURE__ */ jsxDEV2(ESIOptimize, {
2809
+ prompt,
2810
+ schema,
2811
+ criteria: optimizeSettings?.criteria,
2812
+ targetQuality: optimizeSettings?.targetQuality,
2813
+ maxRounds: optimizeSettings?.maxRounds,
2814
+ fallback,
2815
+ loading,
2816
+ className,
2817
+ render: render ? (data) => render(data, "optimized") : undefined,
2818
+ children
2819
+ }, undefined, false, undefined, this);
2820
+ }
2821
+ return /* @__PURE__ */ jsxDEV2(ESIStructured, {
2822
+ prompt,
2823
+ schema,
2824
+ fallback,
2825
+ loading,
2826
+ className,
2827
+ render: render ? (data) => render(data, "basic") : undefined,
2828
+ children
2829
+ }, undefined, false, undefined, this);
2830
+ }
2831
+ function ESIShow({
2832
+ condition,
2833
+ children,
2834
+ fallback = null,
2835
+ loading = null,
2836
+ cacheTtl,
2837
+ onEvaluate,
2838
+ className
2839
+ }) {
2840
+ const [show, setShow] = useState2(null);
2841
+ const boolSchema = {
2842
+ safeParse: (val) => {
2843
+ if (typeof val === "boolean")
2844
+ return { success: true, data: val };
2845
+ if (typeof val === "string") {
2846
+ const lower = val.toLowerCase().trim();
2847
+ if (lower === "true" || lower === "yes" || lower === "1")
2848
+ return { success: true, data: true };
2849
+ if (lower === "false" || lower === "no" || lower === "0")
2850
+ return { success: true, data: false };
2851
+ }
2852
+ if (typeof val === "object" && val !== null && "result" in val) {
2853
+ return { success: true, data: Boolean(val.result) };
2854
+ }
2855
+ return { success: false, error: "Not a boolean" };
2856
+ }
2857
+ };
2858
+ return /* @__PURE__ */ jsxDEV2("span", {
2859
+ className,
2860
+ children: [
2861
+ /* @__PURE__ */ jsxDEV2(ESIStructured, {
2862
+ prompt: `Evaluate this condition and respond with only "true" or "false": ${condition}`,
2863
+ schema: boolSchema,
2864
+ cacheTtl,
2865
+ loading,
2866
+ onSuccess: (result) => {
2867
+ setShow(result);
2868
+ onEvaluate?.(result);
2869
+ },
2870
+ render: () => null
2871
+ }, undefined, false, undefined, this),
2872
+ show === true && children,
2873
+ show === false && fallback
2874
+ ]
2875
+ }, undefined, true, undefined, this);
2876
+ }
2877
+ function ESIHide({
2878
+ condition,
2879
+ children,
2880
+ loading = null,
2881
+ cacheTtl,
2882
+ className
2883
+ }) {
2884
+ return /* @__PURE__ */ jsxDEV2(ESIShow, {
2885
+ condition,
2886
+ fallback: children,
2887
+ loading,
2888
+ cacheTtl,
2889
+ className,
2890
+ children: null
2891
+ }, undefined, false, undefined, this);
2892
+ }
2893
+ function ESIWhen({ condition, children, loading, cacheTtl, className }) {
2894
+ return /* @__PURE__ */ jsxDEV2(ESIShow, {
2895
+ condition,
2896
+ loading,
2897
+ cacheTtl,
2898
+ className,
2899
+ children
2900
+ }, undefined, false, undefined, this);
2901
+ }
2902
+ function ESIUnless({ condition, children, loading, cacheTtl, className }) {
2903
+ return /* @__PURE__ */ jsxDEV2(ESIHide, {
2904
+ condition,
2905
+ loading,
2906
+ cacheTtl,
2907
+ className,
2908
+ children
2909
+ }, undefined, false, undefined, this);
2910
+ }
2911
+ var TIER_LEVELS = { free: 0, starter: 1, pro: 2, enterprise: 3 };
2912
+ function ESITierGate({ minTier, children, fallback = null, className }) {
2913
+ const [hasAccess, setHasAccess] = useState2(null);
2914
+ useEffect2(() => {
2915
+ const state = typeof window !== "undefined" && window.__AEON_ESI_STATE__ || {};
2916
+ const userTier = state.userTier || "free";
2917
+ const userLevel = TIER_LEVELS[userTier] ?? 0;
2918
+ const requiredLevel = TIER_LEVELS[minTier] ?? 0;
2919
+ setHasAccess(userLevel >= requiredLevel);
2920
+ }, [minTier]);
2921
+ if (hasAccess === null)
2922
+ return /* @__PURE__ */ jsxDEV2("span", {
2923
+ className
2924
+ }, undefined, false, undefined, this);
2925
+ return /* @__PURE__ */ jsxDEV2("span", {
2926
+ className,
2927
+ children: hasAccess ? children : fallback
2928
+ }, undefined, false, undefined, this);
2929
+ }
2930
+ function ESIEmotionGate({
2931
+ allow,
2932
+ block,
2933
+ valenceRange,
2934
+ arousalRange,
2935
+ children,
2936
+ fallback = null,
2937
+ className
2938
+ }) {
2939
+ const [hasAccess, setHasAccess] = useState2(null);
2940
+ useEffect2(() => {
2941
+ const state = typeof window !== "undefined" && window.__AEON_ESI_STATE__ || {};
2942
+ const emotion = state.emotionState || {};
2943
+ let access = true;
2944
+ if (allow && allow.length > 0 && emotion.primary) {
2945
+ access = access && allow.includes(emotion.primary);
2946
+ }
2947
+ if (block && block.length > 0 && emotion.primary) {
2948
+ access = access && !block.includes(emotion.primary);
2949
+ }
2950
+ if (valenceRange && emotion.valence !== undefined) {
2951
+ access = access && emotion.valence >= valenceRange[0] && emotion.valence <= valenceRange[1];
2952
+ }
2953
+ if (arousalRange && emotion.arousal !== undefined) {
2954
+ access = access && emotion.arousal >= arousalRange[0] && emotion.arousal <= arousalRange[1];
2955
+ }
2956
+ setHasAccess(access);
2957
+ }, [allow, block, valenceRange, arousalRange]);
2958
+ if (hasAccess === null)
2959
+ return /* @__PURE__ */ jsxDEV2("span", {
2960
+ className
2961
+ }, undefined, false, undefined, this);
2962
+ return /* @__PURE__ */ jsxDEV2("span", {
2963
+ className,
2964
+ children: hasAccess ? children : fallback
2965
+ }, undefined, false, undefined, this);
2966
+ }
2967
+ function ESITimeGate({
2968
+ after,
2969
+ before,
2970
+ days,
2971
+ children,
2972
+ fallback = null,
2973
+ className
2974
+ }) {
2975
+ const [inRange, setInRange] = useState2(null);
2976
+ useEffect2(() => {
2977
+ const now = new Date;
2978
+ const hour = now.getHours();
2979
+ const day = now.getDay();
2980
+ let access = true;
2981
+ if (after !== undefined)
2982
+ access = access && hour >= after;
2983
+ if (before !== undefined)
2984
+ access = access && hour < before;
2985
+ if (days && days.length > 0)
2986
+ access = access && days.includes(day);
2987
+ setInRange(access);
2988
+ }, [after, before, days]);
2989
+ if (inRange === null)
2990
+ return /* @__PURE__ */ jsxDEV2("span", {
2991
+ className
2992
+ }, undefined, false, undefined, this);
2993
+ return /* @__PURE__ */ jsxDEV2("span", {
2994
+ className,
2995
+ children: inRange ? children : fallback
2996
+ }, undefined, false, undefined, this);
2997
+ }
2998
+ function ESIABTest({
2999
+ name,
3000
+ variants,
3001
+ selectionPrompt,
3002
+ random = false,
3003
+ onSelect,
3004
+ loading = null,
3005
+ className
3006
+ }) {
3007
+ const [selectedVariant, setSelectedVariant] = useState2(null);
3008
+ const variantKeys = Object.keys(variants);
3009
+ useEffect2(() => {
3010
+ if (random || !selectionPrompt) {
3011
+ const selected = variantKeys[Math.floor(Math.random() * variantKeys.length)];
3012
+ setSelectedVariant(selected);
3013
+ onSelect?.(selected);
3014
+ }
3015
+ }, [random, selectionPrompt]);
3016
+ if (random || !selectionPrompt) {
3017
+ if (!selectedVariant)
3018
+ return /* @__PURE__ */ jsxDEV2("span", {
3019
+ className,
3020
+ children: loading
3021
+ }, undefined, false, undefined, this);
3022
+ return /* @__PURE__ */ jsxDEV2("span", {
3023
+ className,
3024
+ children: variants[selectedVariant]
3025
+ }, undefined, false, undefined, this);
3026
+ }
3027
+ const variantSchema = {
3028
+ safeParse: (val) => {
3029
+ const str = String(val).trim();
3030
+ if (variantKeys.includes(str))
3031
+ return { success: true, data: str };
3032
+ for (const key of variantKeys) {
3033
+ if (str.toLowerCase().includes(key.toLowerCase())) {
3034
+ return { success: true, data: key };
3035
+ }
3036
+ }
3037
+ return { success: false, error: "Invalid variant" };
3038
+ }
3039
+ };
3040
+ return /* @__PURE__ */ jsxDEV2("span", {
3041
+ className,
3042
+ children: [
3043
+ /* @__PURE__ */ jsxDEV2(ESIStructured, {
3044
+ prompt: `${selectionPrompt}
3045
+
3046
+ Available variants: ${variantKeys.join(", ")}
3047
+
3048
+ Respond with only the variant name.`,
3049
+ schema: variantSchema,
3050
+ loading,
3051
+ onSuccess: (selected) => {
3052
+ setSelectedVariant(selected);
3053
+ onSelect?.(selected);
3054
+ },
3055
+ render: () => null
3056
+ }, undefined, false, undefined, this),
3057
+ selectedVariant && variants[selectedVariant]
3058
+ ]
3059
+ }, undefined, true, undefined, this);
3060
+ }
3061
+ function ESIForEach({
3062
+ prompt,
3063
+ itemSchema,
3064
+ render,
3065
+ maxItems = 10,
3066
+ empty = null,
3067
+ loading = "...",
3068
+ as: Wrapper = "div",
3069
+ className
3070
+ }) {
3071
+ const [items, setItems] = useState2([]);
3072
+ const [isLoading, setIsLoading] = useState2(true);
3073
+ const arraySchema = {
3074
+ safeParse: (val) => {
3075
+ try {
3076
+ let arr;
3077
+ if (Array.isArray(val)) {
3078
+ arr = val;
3079
+ } else if (typeof val === "string") {
3080
+ arr = JSON.parse(val);
3081
+ } else if (typeof val === "object" && val !== null && "items" in val) {
3082
+ arr = val.items;
3083
+ } else {
3084
+ return { success: false, error: "Not an array" };
3085
+ }
3086
+ const validItems = [];
3087
+ for (const item of arr.slice(0, maxItems)) {
3088
+ const result = itemSchema.safeParse(item);
3089
+ if (result.success) {
3090
+ validItems.push(result.data);
3091
+ }
3092
+ }
3093
+ return { success: true, data: validItems };
3094
+ } catch {
3095
+ return { success: false, error: "Parse error" };
3096
+ }
3097
+ }
3098
+ };
3099
+ return /* @__PURE__ */ jsxDEV2(ESIStructured, {
3100
+ prompt: `${prompt}
3101
+
3102
+ Respond with a JSON array of items (max ${maxItems}).`,
3103
+ schema: arraySchema,
3104
+ loading,
3105
+ fallback: empty,
3106
+ className,
3107
+ onSuccess: (result) => {
3108
+ setItems(result);
3109
+ setIsLoading(false);
3110
+ },
3111
+ render: (data) => {
3112
+ if (data.length === 0)
3113
+ return /* @__PURE__ */ jsxDEV2(Fragment, {
3114
+ children: empty
3115
+ }, undefined, false, undefined, this);
3116
+ return /* @__PURE__ */ jsxDEV2(Wrapper, {
3117
+ className,
3118
+ children: data.map((item, i) => render(item, i))
3119
+ }, undefined, false, undefined, this);
3120
+ }
3121
+ }, undefined, false, undefined, this);
3122
+ }
3123
+ function ESIFirst({
3124
+ context,
3125
+ children,
3126
+ fallback = null,
3127
+ loading = null,
3128
+ className
3129
+ }) {
3130
+ return /* @__PURE__ */ jsxDEV2("span", {
3131
+ className,
3132
+ children
3133
+ }, undefined, false, undefined, this);
3134
+ }
3135
+ function ESIClamp({
3136
+ prompt,
3137
+ min,
3138
+ max,
3139
+ render,
3140
+ defaultValue,
3141
+ loading = "...",
3142
+ className
3143
+ }) {
3144
+ const numSchema = {
3145
+ safeParse: (val) => {
3146
+ let num;
3147
+ if (typeof val === "number") {
3148
+ num = val;
3149
+ } else if (typeof val === "string") {
3150
+ num = parseFloat(val);
3151
+ } else if (typeof val === "object" && val !== null && "value" in val) {
3152
+ num = Number(val.value);
3153
+ } else {
3154
+ return { success: false, error: "Not a number" };
3155
+ }
3156
+ if (isNaN(num))
3157
+ return { success: false, error: "NaN" };
3158
+ return { success: true, data: Math.max(min, Math.min(max, num)) };
3159
+ }
3160
+ };
3161
+ return /* @__PURE__ */ jsxDEV2(ESIStructured, {
3162
+ prompt: `${prompt}
3163
+
3164
+ Respond with a number between ${min} and ${max}.`,
3165
+ schema: numSchema,
3166
+ loading,
3167
+ fallback: defaultValue !== undefined ? render(defaultValue) : null,
3168
+ className,
3169
+ render: (value) => render(value)
3170
+ }, undefined, false, undefined, this);
3171
+ }
3172
+ function ESISelect({
3173
+ prompt,
3174
+ options,
3175
+ render,
3176
+ defaultOption,
3177
+ loading = "...",
3178
+ onSelect,
3179
+ className
3180
+ }) {
3181
+ const optionSchema = {
3182
+ safeParse: (val) => {
3183
+ const str = String(val).trim().toLowerCase();
3184
+ const match = options.find((o) => o.toLowerCase() === str);
3185
+ if (match)
3186
+ return { success: true, data: match };
3187
+ const partial = options.find((o) => str.includes(o.toLowerCase()) || o.toLowerCase().includes(str));
3188
+ if (partial)
3189
+ return { success: true, data: partial };
3190
+ return { success: false, error: "No match" };
3191
+ }
3192
+ };
3193
+ return /* @__PURE__ */ jsxDEV2(ESIStructured, {
3194
+ prompt: `${prompt}
3195
+
3196
+ Options: ${options.join(", ")}
3197
+
3198
+ Respond with only one of the options.`,
3199
+ schema: optionSchema,
3200
+ loading,
3201
+ fallback: defaultOption ? render(defaultOption) : null,
3202
+ className,
3203
+ onSuccess: onSelect,
3204
+ render: (selected) => render(selected)
3205
+ }, undefined, false, undefined, this);
3206
+ }
3207
+ var DEFAULT_THRESHOLDS = [
3208
+ { value: 0.2, label: "very low" },
3209
+ { value: 0.4, label: "low" },
3210
+ { value: 0.6, label: "moderate" },
3211
+ { value: 0.8, label: "high" },
3212
+ { value: 1, label: "very high" }
3213
+ ];
3214
+ function ESIScore({
3215
+ prompt,
3216
+ render,
3217
+ thresholds = DEFAULT_THRESHOLDS,
3218
+ loading = "...",
3219
+ className
3220
+ }) {
3221
+ return /* @__PURE__ */ jsxDEV2(ESIClamp, {
3222
+ prompt,
3223
+ min: 0,
3224
+ max: 1,
3225
+ loading,
3226
+ className,
3227
+ render: (score) => {
3228
+ const label = thresholds.find((t) => score <= t.value)?.label || "unknown";
3229
+ return render(score, label);
3230
+ }
3231
+ }, undefined, false, undefined, this);
3232
+ }
3233
+ var ESIControl = {
3234
+ Structured: ESIStructured,
3235
+ If: ESIIf,
3236
+ Show: ESIShow,
3237
+ Hide: ESIHide,
3238
+ When: ESIWhen,
3239
+ Unless: ESIUnless,
3240
+ Match: ESIMatch,
3241
+ Case: ESICase,
3242
+ Default: ESIDefault,
3243
+ First: ESIFirst,
3244
+ TierGate: ESITierGate,
3245
+ EmotionGate: ESIEmotionGate,
3246
+ TimeGate: ESITimeGate,
3247
+ ForEach: ESIForEach,
3248
+ Select: ESISelect,
3249
+ ABTest: ESIABTest,
3250
+ Clamp: ESIClamp,
3251
+ Score: ESIScore,
3252
+ Collaborative: ESICollaborative,
3253
+ Reflect: ESIReflect,
3254
+ Optimize: ESIOptimize,
3255
+ Auto: ESIAuto
3256
+ };
3257
+ export { DEFAULT_ROUTER_CONFIG, DEFAULT_ESI_CONFIG, esiContext, esiCyrano, esiHalo, evaluateTrigger, createExhaustEntry, CYRANO_TOOL_SUGGESTIONS, getToolSuggestions, EdgeWorkersESIProcessor, esiInfer, esiEmbed, esiEmotion, esiVision, esiWithContext, ESIProvider, useESI, ESIInfer, ESIEmbed, ESIEmotion, ESIVision, useESIInfer, useGlobalESIState, useESIFeature, useESITier, useESIEmotionState, useESIPreferences, updateGlobalESIState, ESI, HeuristicAdapter, extractUserContext, createContextMiddleware, setContextCookies, addSpeculationHeaders, serializeToESIState, generateESIStateScript, generateESIStateScriptFromContext, supportsSpeculationRules, supportsLinkPrefetch, SpeculationManager, createSpeculationHook, autoInitSpeculation, generateSchemaPrompt, parseWithSchema, createControlProcessor, esiIf, esiMatch, ESIStructured, ESIIf, ESICase, ESIDefault, ESIMatch, ESICollaborative, ESIReflect, ESIOptimize, ESIAuto, ESIShow, ESIHide, ESIWhen, ESIUnless, ESITierGate, ESIEmotionGate, ESITimeGate, ESIABTest, ESIForEach, ESIFirst, ESIClamp, ESISelect, ESIScore, ESIControl };