@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,3285 @@
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 as createContext2,
762
+ useContext as useContext2,
763
+ useEffect as useEffect2,
764
+ useState as useState2,
765
+ useCallback as useCallback2
766
+ } from "react";
767
+
768
+ // src/router/esi-control-react.tsx
769
+ import {
770
+ createContext,
771
+ useContext,
772
+ useEffect,
773
+ useState,
774
+ useCallback,
775
+ useMemo,
776
+ Children,
777
+ isValidElement
778
+ } from "react";
779
+
780
+ // src/router/esi-control.ts
781
+ function generateSchemaPrompt(schema) {
782
+ const schemaDescription = describeZodSchema(schema);
783
+ return `
784
+
785
+ Respond with valid JSON matching this schema:
786
+ ${schemaDescription}
787
+
788
+ Output ONLY the JSON, no markdown, no explanation.`;
789
+ }
790
+ function describeZodSchema(schema) {
791
+ const def = schema._def;
792
+ if (def.typeName === "ZodObject") {
793
+ const shape = def.shape;
794
+ const fields = Object.entries(shape).map(([key, fieldSchema]) => {
795
+ const fieldDef = fieldSchema._def;
796
+ return ` "${key}": ${describeZodType(fieldDef)}`;
797
+ });
798
+ return `{
799
+ ${fields.join(`,
800
+ `)}
801
+ }`;
802
+ }
803
+ return describeZodType(def);
804
+ }
805
+ function describeZodType(def) {
806
+ const typeName = def.typeName;
807
+ switch (typeName) {
808
+ case "ZodString":
809
+ return "string";
810
+ case "ZodNumber":
811
+ return "number";
812
+ case "ZodBoolean":
813
+ return "boolean";
814
+ case "ZodArray":
815
+ const innerType = def.type;
816
+ return `array of ${describeZodType(innerType._def)}`;
817
+ case "ZodEnum":
818
+ const values = def.values;
819
+ return `one of: ${values.map((v) => `"${v}"`).join(" | ")}`;
820
+ case "ZodLiteral":
821
+ return JSON.stringify(def.value);
822
+ case "ZodOptional":
823
+ const optionalType = def.innerType;
824
+ return `${describeZodType(optionalType._def)} (optional)`;
825
+ case "ZodNullable":
826
+ const nullableType = def.innerType;
827
+ return `${describeZodType(nullableType._def)} or null`;
828
+ case "ZodObject":
829
+ return "object";
830
+ default:
831
+ return "any";
832
+ }
833
+ }
834
+ function parseWithSchema(output, schema) {
835
+ let jsonStr = output.trim();
836
+ if (jsonStr.startsWith("```")) {
837
+ const match = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);
838
+ if (match) {
839
+ jsonStr = match[1].trim();
840
+ }
841
+ }
842
+ let parsed;
843
+ try {
844
+ parsed = JSON.parse(jsonStr);
845
+ } catch (e) {
846
+ const jsonMatch = jsonStr.match(/\{[\s\S]*\}/);
847
+ if (jsonMatch) {
848
+ try {
849
+ parsed = JSON.parse(jsonMatch[0]);
850
+ } catch {
851
+ return {
852
+ success: false,
853
+ errors: [`Failed to parse JSON: ${e instanceof Error ? e.message : "Unknown error"}`]
854
+ };
855
+ }
856
+ } else {
857
+ return {
858
+ success: false,
859
+ errors: [`No valid JSON found in output`]
860
+ };
861
+ }
862
+ }
863
+ const result = schema.safeParse(parsed);
864
+ if (result.success) {
865
+ return { success: true, data: result.data };
866
+ }
867
+ return {
868
+ success: false,
869
+ errors: result.error.errors.map((e) => `${e.path.join(".")}: ${e.message}`)
870
+ };
871
+ }
872
+ function createControlProcessor(processESI) {
873
+ return {
874
+ async processWithSchema(prompt, schema, params, context) {
875
+ const fullPrompt = prompt + generateSchemaPrompt(schema);
876
+ const directive = {
877
+ id: `esi-schema-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
878
+ params: {
879
+ model: "llm",
880
+ ...params
881
+ },
882
+ content: {
883
+ type: "text",
884
+ value: fullPrompt
885
+ }
886
+ };
887
+ const result = await processESI(directive, context);
888
+ if (!result.success || !result.output) {
889
+ return {
890
+ ...result,
891
+ validationErrors: result.error ? [result.error] : ["No output"]
892
+ };
893
+ }
894
+ const parseResult = parseWithSchema(result.output, schema);
895
+ if (parseResult.success) {
896
+ return {
897
+ ...result,
898
+ data: parseResult.data,
899
+ rawOutput: result.output
900
+ };
901
+ }
902
+ return {
903
+ ...result,
904
+ rawOutput: result.output,
905
+ validationErrors: parseResult.errors
906
+ };
907
+ },
908
+ async processIf(directive, context) {
909
+ const schemaResult = await this.processWithSchema(directive.prompt, directive.schema, directive.params || {}, context);
910
+ let conditionMet = false;
911
+ if (schemaResult.data !== undefined) {
912
+ try {
913
+ conditionMet = directive.when(schemaResult.data, context);
914
+ } catch (e) {
915
+ conditionMet = false;
916
+ }
917
+ }
918
+ return {
919
+ id: directive.id,
920
+ conditionMet,
921
+ data: schemaResult.data,
922
+ inferenceResult: schemaResult
923
+ };
924
+ },
925
+ async processMatch(directive, context) {
926
+ const schemaResult = await this.processWithSchema(directive.prompt, directive.schema, directive.params || {}, context);
927
+ let matchedCase;
928
+ if (schemaResult.data !== undefined) {
929
+ for (const caseItem of directive.cases) {
930
+ try {
931
+ if (caseItem.match(schemaResult.data, context)) {
932
+ matchedCase = caseItem.id;
933
+ break;
934
+ }
935
+ } catch {}
936
+ }
937
+ if (!matchedCase && directive.defaultCase) {
938
+ matchedCase = directive.defaultCase;
939
+ }
940
+ }
941
+ return {
942
+ id: directive.id,
943
+ matchedCase,
944
+ data: schemaResult.data,
945
+ inferenceResult: schemaResult
946
+ };
947
+ }
948
+ };
949
+ }
950
+ function esiIf(prompt, schema, when, options = {}) {
951
+ return {
952
+ id: `esi-if-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
953
+ prompt,
954
+ schema,
955
+ when,
956
+ params: options
957
+ };
958
+ }
959
+ function esiMatch(prompt, schema, cases, defaultCase, options = {}) {
960
+ return {
961
+ id: `esi-match-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
962
+ prompt,
963
+ schema,
964
+ cases,
965
+ defaultCase,
966
+ params: options
967
+ };
968
+ }
969
+
970
+ // src/router/esi-control-react.tsx
971
+ import { jsxDEV, Fragment } from "react/jsx-dev-runtime";
972
+ var PresenceContext = createContext(null);
973
+ function usePresenceForESI() {
974
+ const ctx = useContext(PresenceContext);
975
+ return ctx || { users: [], localUser: null };
976
+ }
977
+ function ESIStructured({
978
+ children,
979
+ prompt,
980
+ schema,
981
+ render,
982
+ fallback,
983
+ loading = "...",
984
+ retryOnFail = false,
985
+ maxRetries = 2,
986
+ temperature,
987
+ maxTokens,
988
+ cacheTtl,
989
+ onSuccess,
990
+ onValidationError,
991
+ onError,
992
+ className
993
+ }) {
994
+ const { process: process2, enabled } = useESI();
995
+ const [result, setResult] = useState(null);
996
+ const [isLoading, setIsLoading] = useState(true);
997
+ const [retryCount, setRetryCount] = useState(0);
998
+ const promptText = prompt || (typeof children === "string" ? children : String(children || ""));
999
+ const fullPrompt = promptText + generateSchemaPrompt(schema);
1000
+ useEffect(() => {
1001
+ if (!enabled) {
1002
+ setIsLoading(false);
1003
+ return;
1004
+ }
1005
+ async function runInference() {
1006
+ setIsLoading(true);
1007
+ const directive = {
1008
+ id: `esi-structured-${Date.now()}`,
1009
+ params: {
1010
+ model: "llm",
1011
+ temperature,
1012
+ maxTokens,
1013
+ cacheTtl
1014
+ },
1015
+ content: {
1016
+ type: "text",
1017
+ value: fullPrompt
1018
+ }
1019
+ };
1020
+ const inferenceResult = await process2(directive);
1021
+ if (!inferenceResult.success || !inferenceResult.output) {
1022
+ setResult({
1023
+ ...inferenceResult,
1024
+ validationErrors: [inferenceResult.error || "No output"]
1025
+ });
1026
+ onError?.(inferenceResult.error || "Inference failed");
1027
+ setIsLoading(false);
1028
+ return;
1029
+ }
1030
+ const parseResult = parseWithSchema(inferenceResult.output, schema);
1031
+ if (parseResult.success) {
1032
+ const schemaResult = {
1033
+ ...inferenceResult,
1034
+ data: parseResult.data,
1035
+ rawOutput: inferenceResult.output
1036
+ };
1037
+ setResult(schemaResult);
1038
+ onSuccess?.(parseResult.data);
1039
+ } else {
1040
+ if (retryOnFail && retryCount < maxRetries) {
1041
+ setRetryCount((c) => c + 1);
1042
+ } else {
1043
+ const schemaResult = {
1044
+ ...inferenceResult,
1045
+ rawOutput: inferenceResult.output,
1046
+ validationErrors: parseResult.errors
1047
+ };
1048
+ setResult(schemaResult);
1049
+ onValidationError?.(parseResult.errors, inferenceResult.output);
1050
+ }
1051
+ }
1052
+ setIsLoading(false);
1053
+ }
1054
+ runInference();
1055
+ }, [fullPrompt, enabled, retryCount]);
1056
+ if (isLoading) {
1057
+ return /* @__PURE__ */ jsxDEV("span", {
1058
+ className,
1059
+ children: loading
1060
+ }, undefined, false, undefined, this);
1061
+ }
1062
+ if (!result?.data) {
1063
+ return /* @__PURE__ */ jsxDEV("span", {
1064
+ className,
1065
+ children: fallback
1066
+ }, undefined, false, undefined, this);
1067
+ }
1068
+ if (render) {
1069
+ return /* @__PURE__ */ jsxDEV("span", {
1070
+ className,
1071
+ children: render(result.data, {
1072
+ cached: result.cached,
1073
+ latencyMs: result.latencyMs
1074
+ })
1075
+ }, undefined, false, undefined, this);
1076
+ }
1077
+ return /* @__PURE__ */ jsxDEV("span", {
1078
+ className,
1079
+ children: JSON.stringify(result.data)
1080
+ }, undefined, false, undefined, this);
1081
+ }
1082
+ function ESIIf({
1083
+ children,
1084
+ prompt,
1085
+ schema,
1086
+ when,
1087
+ then: thenContent,
1088
+ else: elseContent,
1089
+ loading = null,
1090
+ temperature,
1091
+ cacheTtl,
1092
+ onEvaluate,
1093
+ className
1094
+ }) {
1095
+ const [conditionMet, setConditionMet] = useState(null);
1096
+ const [data, setData] = useState(null);
1097
+ const handleSuccess = useCallback((result) => {
1098
+ setData(result);
1099
+ try {
1100
+ const met = when(result, {});
1101
+ setConditionMet(met);
1102
+ onEvaluate?.(result, met);
1103
+ } catch {
1104
+ setConditionMet(false);
1105
+ }
1106
+ }, [when, onEvaluate]);
1107
+ return /* @__PURE__ */ jsxDEV("span", {
1108
+ className,
1109
+ children: [
1110
+ /* @__PURE__ */ jsxDEV(ESIStructured, {
1111
+ prompt,
1112
+ schema,
1113
+ temperature,
1114
+ cacheTtl,
1115
+ loading,
1116
+ onSuccess: handleSuccess,
1117
+ render: () => null,
1118
+ children
1119
+ }, undefined, false, undefined, this),
1120
+ conditionMet === true && thenContent,
1121
+ conditionMet === false && elseContent
1122
+ ]
1123
+ }, undefined, true, undefined, this);
1124
+ }
1125
+ function ESICase({ children }) {
1126
+ return /* @__PURE__ */ jsxDEV(Fragment, {
1127
+ children
1128
+ }, undefined, false, undefined, this);
1129
+ }
1130
+ function ESIDefault({ children }) {
1131
+ return /* @__PURE__ */ jsxDEV(Fragment, {
1132
+ children
1133
+ }, undefined, false, undefined, this);
1134
+ }
1135
+ function ESIMatch({
1136
+ children,
1137
+ prompt,
1138
+ schema,
1139
+ loading = null,
1140
+ temperature,
1141
+ cacheTtl,
1142
+ onMatch,
1143
+ className
1144
+ }) {
1145
+ const [matchedIndex, setMatchedIndex] = useState(null);
1146
+ const [data, setData] = useState(null);
1147
+ const { cases, defaultCase, promptFromChildren } = useMemo(() => {
1148
+ const cases2 = [];
1149
+ let defaultCase2 = null;
1150
+ let promptFromChildren2 = "";
1151
+ Children.forEach(children, (child) => {
1152
+ if (!isValidElement(child)) {
1153
+ if (typeof child === "string") {
1154
+ promptFromChildren2 += child;
1155
+ }
1156
+ return;
1157
+ }
1158
+ if (child.type === ESICase) {
1159
+ const props = child.props;
1160
+ cases2.push({
1161
+ match: props.match,
1162
+ content: props.children
1163
+ });
1164
+ } else if (child.type === ESIDefault) {
1165
+ defaultCase2 = child.props.children;
1166
+ }
1167
+ });
1168
+ return { cases: cases2, defaultCase: defaultCase2, promptFromChildren: promptFromChildren2 };
1169
+ }, [children]);
1170
+ const handleSuccess = useCallback((result) => {
1171
+ setData(result);
1172
+ for (let i = 0;i < cases.length; i++) {
1173
+ try {
1174
+ if (cases[i].match(result, {})) {
1175
+ setMatchedIndex(i);
1176
+ onMatch?.(result, i);
1177
+ return;
1178
+ }
1179
+ } catch {}
1180
+ }
1181
+ setMatchedIndex(-1);
1182
+ onMatch?.(result, -1);
1183
+ }, [cases, onMatch]);
1184
+ const finalPrompt = prompt || promptFromChildren;
1185
+ return /* @__PURE__ */ jsxDEV("span", {
1186
+ className,
1187
+ children: [
1188
+ /* @__PURE__ */ jsxDEV(ESIStructured, {
1189
+ prompt: finalPrompt,
1190
+ schema,
1191
+ temperature,
1192
+ cacheTtl,
1193
+ loading,
1194
+ onSuccess: handleSuccess,
1195
+ render: () => null
1196
+ }, undefined, false, undefined, this),
1197
+ matchedIndex !== null && matchedIndex >= 0 && cases[matchedIndex]?.content,
1198
+ matchedIndex === -1 && defaultCase
1199
+ ]
1200
+ }, undefined, true, undefined, this);
1201
+ }
1202
+ function defaultDescribeUsers(users) {
1203
+ if (users.length === 0)
1204
+ return "No other users are viewing this content.";
1205
+ if (users.length === 1)
1206
+ return `1 user is viewing: ${describeUser(users[0])}`;
1207
+ const roles = [...new Set(users.map((u) => u.role).filter(Boolean))];
1208
+ const roleStr = roles.length > 0 ? ` with roles: ${roles.join(", ")}` : "";
1209
+ return `${users.length} users are viewing${roleStr}:
1210
+ ${users.map(describeUser).join(`
1211
+ `)}`;
1212
+ }
1213
+ function describeUser(user) {
1214
+ const parts = [user.name || user.userId];
1215
+ if (user.role)
1216
+ parts.push(`(${user.role})`);
1217
+ if (user.status)
1218
+ parts.push(`[${user.status}]`);
1219
+ return `- ${parts.join(" ")}`;
1220
+ }
1221
+ function ESICollaborative({
1222
+ children,
1223
+ prompt,
1224
+ schema,
1225
+ render,
1226
+ fallback,
1227
+ loading = "...",
1228
+ describeUsers = defaultDescribeUsers,
1229
+ reactToPresenceChange = true,
1230
+ presenceDebounce = 2000,
1231
+ temperature,
1232
+ maxTokens,
1233
+ cacheTtl,
1234
+ onSuccess,
1235
+ className
1236
+ }) {
1237
+ const presence = usePresenceForESI();
1238
+ const [debouncedUsers, setDebouncedUsers] = useState(presence.users);
1239
+ const [result, setResult] = useState(null);
1240
+ useEffect(() => {
1241
+ if (!reactToPresenceChange)
1242
+ return;
1243
+ const timer = setTimeout(() => {
1244
+ setDebouncedUsers(presence.users);
1245
+ }, presenceDebounce);
1246
+ return () => clearTimeout(timer);
1247
+ }, [presence.users, reactToPresenceChange, presenceDebounce]);
1248
+ const basePrompt = prompt || (typeof children === "string" ? children : String(children || ""));
1249
+ const presenceDescription = describeUsers(debouncedUsers);
1250
+ const collaborativePrompt = `[Audience Context]
1251
+ ${presenceDescription}
1252
+
1253
+ [Task]
1254
+ ${basePrompt}
1255
+
1256
+ Consider ALL viewers when generating your response. The content should be relevant and appropriate for everyone currently viewing.`;
1257
+ const handleSuccess = useCallback((data) => {
1258
+ setResult(data);
1259
+ onSuccess?.(data, debouncedUsers);
1260
+ }, [debouncedUsers, onSuccess]);
1261
+ return /* @__PURE__ */ jsxDEV(ESIStructured, {
1262
+ prompt: collaborativePrompt,
1263
+ schema,
1264
+ temperature,
1265
+ maxTokens,
1266
+ cacheTtl,
1267
+ loading,
1268
+ fallback,
1269
+ onSuccess: handleSuccess,
1270
+ className,
1271
+ render: (data, meta) => {
1272
+ if (render) {
1273
+ return render(data, debouncedUsers);
1274
+ }
1275
+ return JSON.stringify(data);
1276
+ }
1277
+ }, undefined, false, undefined, this);
1278
+ }
1279
+ function ESIReflect({
1280
+ children,
1281
+ prompt,
1282
+ schema,
1283
+ until,
1284
+ maxIterations = 3,
1285
+ render,
1286
+ showProgress = false,
1287
+ fallback,
1288
+ loading = "...",
1289
+ onIteration,
1290
+ onComplete,
1291
+ className
1292
+ }) {
1293
+ const { process: process2, enabled } = useESI();
1294
+ const [currentResult, setCurrentResult] = useState(null);
1295
+ const [iteration, setIteration] = useState(0);
1296
+ const [isComplete, setIsComplete] = useState(false);
1297
+ const [isLoading, setIsLoading] = useState(true);
1298
+ const basePrompt = prompt || (typeof children === "string" ? children : String(children || ""));
1299
+ useEffect(() => {
1300
+ if (!enabled) {
1301
+ setIsLoading(false);
1302
+ return;
1303
+ }
1304
+ async function runReflection() {
1305
+ setIsLoading(true);
1306
+ let currentIteration = 0;
1307
+ let lastResult = null;
1308
+ let previousAttempts = [];
1309
+ while (currentIteration < maxIterations) {
1310
+ let reflectionPrompt = basePrompt;
1311
+ if (currentIteration > 0 && lastResult) {
1312
+ reflectionPrompt = `[Previous Attempt ${currentIteration}]
1313
+ ${JSON.stringify(lastResult)}
1314
+
1315
+ [Reflection]
1316
+ The previous attempt did not meet the quality threshold. Please improve upon it.
1317
+
1318
+ [Original Task]
1319
+ ${basePrompt}`;
1320
+ }
1321
+ const fullPrompt = reflectionPrompt + generateSchemaPrompt(schema);
1322
+ const directive = {
1323
+ id: `esi-reflect-${Date.now()}-${currentIteration}`,
1324
+ params: { model: "llm" },
1325
+ content: { type: "text", value: fullPrompt }
1326
+ };
1327
+ const result = await process2(directive);
1328
+ if (!result.success || !result.output) {
1329
+ break;
1330
+ }
1331
+ const parseResult = parseWithSchema(result.output, schema);
1332
+ if (!parseResult.success) {
1333
+ currentIteration++;
1334
+ continue;
1335
+ }
1336
+ lastResult = parseResult.data;
1337
+ setCurrentResult(parseResult.data);
1338
+ setIteration(currentIteration + 1);
1339
+ onIteration?.(parseResult.data, currentIteration + 1);
1340
+ if (until(parseResult.data, currentIteration + 1)) {
1341
+ setIsComplete(true);
1342
+ onComplete?.(parseResult.data, currentIteration + 1);
1343
+ break;
1344
+ }
1345
+ previousAttempts.push(result.output);
1346
+ currentIteration++;
1347
+ }
1348
+ if (!isComplete && lastResult) {
1349
+ setIsComplete(true);
1350
+ onComplete?.(lastResult, currentIteration);
1351
+ }
1352
+ setIsLoading(false);
1353
+ }
1354
+ runReflection();
1355
+ }, [basePrompt, enabled, maxIterations]);
1356
+ if (isLoading) {
1357
+ if (showProgress && currentResult) {
1358
+ return /* @__PURE__ */ jsxDEV("span", {
1359
+ className,
1360
+ children: [
1361
+ render ? render(currentResult, iteration) : JSON.stringify(currentResult),
1362
+ /* @__PURE__ */ jsxDEV("span", {
1363
+ children: [
1364
+ " (refining... iteration ",
1365
+ iteration,
1366
+ ")"
1367
+ ]
1368
+ }, undefined, true, undefined, this)
1369
+ ]
1370
+ }, undefined, true, undefined, this);
1371
+ }
1372
+ return /* @__PURE__ */ jsxDEV("span", {
1373
+ className,
1374
+ children: loading
1375
+ }, undefined, false, undefined, this);
1376
+ }
1377
+ if (!currentResult) {
1378
+ return /* @__PURE__ */ jsxDEV("span", {
1379
+ className,
1380
+ children: fallback
1381
+ }, undefined, false, undefined, this);
1382
+ }
1383
+ if (render) {
1384
+ return /* @__PURE__ */ jsxDEV("span", {
1385
+ className,
1386
+ children: render(currentResult, iteration)
1387
+ }, undefined, false, undefined, this);
1388
+ }
1389
+ return /* @__PURE__ */ jsxDEV("span", {
1390
+ className,
1391
+ children: JSON.stringify(currentResult)
1392
+ }, undefined, false, undefined, this);
1393
+ }
1394
+ function ESIOptimize({
1395
+ children,
1396
+ prompt,
1397
+ schema,
1398
+ criteria = ["clarity", "relevance", "completeness", "conciseness"],
1399
+ targetQuality = 0.85,
1400
+ maxRounds = 3,
1401
+ onlyWhenAlone = true,
1402
+ render,
1403
+ fallback,
1404
+ loading = "...",
1405
+ onImprove,
1406
+ onOptimized,
1407
+ className
1408
+ }) {
1409
+ const { process: process2, enabled } = useESI();
1410
+ const presence = usePresenceForESI();
1411
+ const [result, setResult] = useState(null);
1412
+ const [meta, setMeta] = useState({
1413
+ rounds: 0,
1414
+ quality: 0,
1415
+ improvements: [],
1416
+ wasOptimized: false
1417
+ });
1418
+ const [isLoading, setIsLoading] = useState(true);
1419
+ const basePrompt = prompt || (typeof children === "string" ? children : String(children || ""));
1420
+ const shouldOptimize = !onlyWhenAlone || presence.users.length <= 1;
1421
+ useEffect(() => {
1422
+ if (!enabled) {
1423
+ setIsLoading(false);
1424
+ return;
1425
+ }
1426
+ async function runOptimization() {
1427
+ setIsLoading(true);
1428
+ const criteriaList = criteria.join(", ");
1429
+ const firstPassPrompt = `${basePrompt}
1430
+
1431
+ After generating your response, assess its quality on these criteria: ${criteriaList}
1432
+
1433
+ ${generateSchemaPrompt(schema)}
1434
+
1435
+ Additionally, include a self-assessment in this format:
1436
+ {
1437
+ "result": <your response matching the schema above>,
1438
+ "selfAssessment": {
1439
+ "quality": <0-1 score>,
1440
+ "strengths": [<list of strengths>],
1441
+ "weaknesses": [<list of weaknesses>],
1442
+ "improvementSuggestions": [<specific improvements>]
1443
+ }
1444
+ }`;
1445
+ let currentResult = null;
1446
+ let currentQuality = 0;
1447
+ let round = 0;
1448
+ let improvements = [];
1449
+ let lastWeaknesses = [];
1450
+ const firstResult = await process2({
1451
+ id: `esi-optimize-${Date.now()}-0`,
1452
+ params: { model: "llm" },
1453
+ content: { type: "text", value: firstPassPrompt }
1454
+ });
1455
+ if (!firstResult.success || !firstResult.output) {
1456
+ setIsLoading(false);
1457
+ return;
1458
+ }
1459
+ try {
1460
+ const parsed = JSON.parse(extractJson(firstResult.output));
1461
+ const validated = schema.safeParse(parsed.result);
1462
+ if (validated.success) {
1463
+ currentResult = validated.data;
1464
+ currentQuality = parsed.selfAssessment?.quality || 0.5;
1465
+ lastWeaknesses = parsed.selfAssessment?.weaknesses || [];
1466
+ round = 1;
1467
+ setResult(currentResult);
1468
+ setMeta({
1469
+ rounds: 1,
1470
+ quality: currentQuality,
1471
+ improvements: [],
1472
+ wasOptimized: false
1473
+ });
1474
+ onImprove?.(currentResult, 1, currentQuality);
1475
+ }
1476
+ } catch {
1477
+ const parseResult = parseWithSchema(firstResult.output, schema);
1478
+ if (parseResult.success) {
1479
+ currentResult = parseResult.data;
1480
+ currentQuality = 0.6;
1481
+ round = 1;
1482
+ setResult(currentResult);
1483
+ } else {
1484
+ setIsLoading(false);
1485
+ return;
1486
+ }
1487
+ }
1488
+ if (shouldOptimize && currentQuality < targetQuality) {
1489
+ while (round < maxRounds && currentQuality < targetQuality) {
1490
+ const optimizePrompt = `You previously generated this response:
1491
+ ${JSON.stringify(currentResult)}
1492
+
1493
+ Quality score: ${currentQuality.toFixed(2)}
1494
+ Weaknesses identified: ${lastWeaknesses.join(", ") || "none specified"}
1495
+
1496
+ Please improve the response, focusing on: ${criteriaList}
1497
+ Address the weaknesses and aim for a quality score above ${targetQuality}.
1498
+
1499
+ ${generateSchemaPrompt(schema)}
1500
+
1501
+ Include your improved self-assessment:
1502
+ {
1503
+ "result": <improved response>,
1504
+ "selfAssessment": {
1505
+ "quality": <0-1 score>,
1506
+ "strengths": [...],
1507
+ "weaknesses": [...],
1508
+ "improvementSuggestions": [...]
1509
+ },
1510
+ "improvementsMade": [<what you improved>]
1511
+ }`;
1512
+ const improvedResult = await process2({
1513
+ id: `esi-optimize-${Date.now()}-${round}`,
1514
+ params: { model: "llm" },
1515
+ content: { type: "text", value: optimizePrompt }
1516
+ });
1517
+ if (!improvedResult.success || !improvedResult.output) {
1518
+ break;
1519
+ }
1520
+ try {
1521
+ const parsed = JSON.parse(extractJson(improvedResult.output));
1522
+ const validated = schema.safeParse(parsed.result);
1523
+ if (validated.success) {
1524
+ const newQuality = parsed.selfAssessment?.quality || currentQuality;
1525
+ if (newQuality > currentQuality) {
1526
+ currentResult = validated.data;
1527
+ currentQuality = newQuality;
1528
+ lastWeaknesses = parsed.selfAssessment?.weaknesses || [];
1529
+ if (parsed.improvementsMade) {
1530
+ improvements.push(...parsed.improvementsMade);
1531
+ }
1532
+ setResult(currentResult);
1533
+ setMeta({
1534
+ rounds: round + 1,
1535
+ quality: currentQuality,
1536
+ improvements,
1537
+ wasOptimized: true
1538
+ });
1539
+ onImprove?.(currentResult, round + 1, currentQuality);
1540
+ }
1541
+ }
1542
+ } catch {}
1543
+ round++;
1544
+ }
1545
+ }
1546
+ if (currentResult) {
1547
+ setMeta((prev) => ({
1548
+ ...prev,
1549
+ rounds: round,
1550
+ quality: currentQuality,
1551
+ wasOptimized: round > 1
1552
+ }));
1553
+ onOptimized?.(currentResult, round, currentQuality);
1554
+ }
1555
+ setIsLoading(false);
1556
+ }
1557
+ runOptimization();
1558
+ }, [basePrompt, enabled, shouldOptimize, targetQuality, maxRounds]);
1559
+ if (isLoading) {
1560
+ return /* @__PURE__ */ jsxDEV("span", {
1561
+ className,
1562
+ children: loading
1563
+ }, undefined, false, undefined, this);
1564
+ }
1565
+ if (!result) {
1566
+ return /* @__PURE__ */ jsxDEV("span", {
1567
+ className,
1568
+ children: fallback
1569
+ }, undefined, false, undefined, this);
1570
+ }
1571
+ if (render) {
1572
+ return /* @__PURE__ */ jsxDEV("span", {
1573
+ className,
1574
+ children: render(result, meta)
1575
+ }, undefined, false, undefined, this);
1576
+ }
1577
+ return /* @__PURE__ */ jsxDEV("span", {
1578
+ className,
1579
+ children: JSON.stringify(result)
1580
+ }, undefined, false, undefined, this);
1581
+ }
1582
+ function extractJson(str) {
1583
+ let cleaned = str.trim();
1584
+ if (cleaned.startsWith("```")) {
1585
+ const match = cleaned.match(/```(?:json)?\s*([\s\S]*?)```/);
1586
+ if (match)
1587
+ cleaned = match[1].trim();
1588
+ }
1589
+ const jsonMatch = cleaned.match(/\{[\s\S]*\}/);
1590
+ if (jsonMatch)
1591
+ return jsonMatch[0];
1592
+ return cleaned;
1593
+ }
1594
+ function ESIAuto({
1595
+ children,
1596
+ prompt,
1597
+ schema,
1598
+ render,
1599
+ collaborativeThreshold = 2,
1600
+ optimizeSettings,
1601
+ fallback,
1602
+ loading,
1603
+ className
1604
+ }) {
1605
+ const presence = usePresenceForESI();
1606
+ const userCount = presence.users.length;
1607
+ const mode = userCount >= collaborativeThreshold ? "collaborative" : userCount === 1 ? "optimized" : "basic";
1608
+ if (mode === "collaborative") {
1609
+ return /* @__PURE__ */ jsxDEV(ESICollaborative, {
1610
+ prompt,
1611
+ schema,
1612
+ fallback,
1613
+ loading,
1614
+ className,
1615
+ render: render ? (data) => render(data, "collaborative") : undefined,
1616
+ children
1617
+ }, undefined, false, undefined, this);
1618
+ }
1619
+ if (mode === "optimized") {
1620
+ return /* @__PURE__ */ jsxDEV(ESIOptimize, {
1621
+ prompt,
1622
+ schema,
1623
+ criteria: optimizeSettings?.criteria,
1624
+ targetQuality: optimizeSettings?.targetQuality,
1625
+ maxRounds: optimizeSettings?.maxRounds,
1626
+ fallback,
1627
+ loading,
1628
+ className,
1629
+ render: render ? (data) => render(data, "optimized") : undefined,
1630
+ children
1631
+ }, undefined, false, undefined, this);
1632
+ }
1633
+ return /* @__PURE__ */ jsxDEV(ESIStructured, {
1634
+ prompt,
1635
+ schema,
1636
+ fallback,
1637
+ loading,
1638
+ className,
1639
+ render: render ? (data) => render(data, "basic") : undefined,
1640
+ children
1641
+ }, undefined, false, undefined, this);
1642
+ }
1643
+ function ESIShow({
1644
+ condition,
1645
+ children,
1646
+ fallback = null,
1647
+ loading = null,
1648
+ cacheTtl,
1649
+ onEvaluate,
1650
+ className
1651
+ }) {
1652
+ const [show, setShow] = useState(null);
1653
+ const boolSchema = {
1654
+ safeParse: (val) => {
1655
+ if (typeof val === "boolean")
1656
+ return { success: true, data: val };
1657
+ if (typeof val === "string") {
1658
+ const lower = val.toLowerCase().trim();
1659
+ if (lower === "true" || lower === "yes" || lower === "1")
1660
+ return { success: true, data: true };
1661
+ if (lower === "false" || lower === "no" || lower === "0")
1662
+ return { success: true, data: false };
1663
+ }
1664
+ if (typeof val === "object" && val !== null && "result" in val) {
1665
+ return { success: true, data: Boolean(val.result) };
1666
+ }
1667
+ return { success: false, error: "Not a boolean" };
1668
+ }
1669
+ };
1670
+ return /* @__PURE__ */ jsxDEV("span", {
1671
+ className,
1672
+ children: [
1673
+ /* @__PURE__ */ jsxDEV(ESIStructured, {
1674
+ prompt: `Evaluate this condition and respond with only "true" or "false": ${condition}`,
1675
+ schema: boolSchema,
1676
+ cacheTtl,
1677
+ loading,
1678
+ onSuccess: (result) => {
1679
+ setShow(result);
1680
+ onEvaluate?.(result);
1681
+ },
1682
+ render: () => null
1683
+ }, undefined, false, undefined, this),
1684
+ show === true && children,
1685
+ show === false && fallback
1686
+ ]
1687
+ }, undefined, true, undefined, this);
1688
+ }
1689
+ function ESIHide({
1690
+ condition,
1691
+ children,
1692
+ loading = null,
1693
+ cacheTtl,
1694
+ className
1695
+ }) {
1696
+ return /* @__PURE__ */ jsxDEV(ESIShow, {
1697
+ condition,
1698
+ fallback: children,
1699
+ loading,
1700
+ cacheTtl,
1701
+ className,
1702
+ children: null
1703
+ }, undefined, false, undefined, this);
1704
+ }
1705
+ function ESIWhen({ condition, children, loading, cacheTtl, className }) {
1706
+ return /* @__PURE__ */ jsxDEV(ESIShow, {
1707
+ condition,
1708
+ loading,
1709
+ cacheTtl,
1710
+ className,
1711
+ children
1712
+ }, undefined, false, undefined, this);
1713
+ }
1714
+ function ESIUnless({ condition, children, loading, cacheTtl, className }) {
1715
+ return /* @__PURE__ */ jsxDEV(ESIHide, {
1716
+ condition,
1717
+ loading,
1718
+ cacheTtl,
1719
+ className,
1720
+ children
1721
+ }, undefined, false, undefined, this);
1722
+ }
1723
+ var TIER_LEVELS = { free: 0, starter: 1, pro: 2, enterprise: 3 };
1724
+ function ESITierGate({ minTier, children, fallback = null, className }) {
1725
+ const [hasAccess, setHasAccess] = useState(null);
1726
+ useEffect(() => {
1727
+ const state = typeof window !== "undefined" && window.__AEON_ESI_STATE__ || {};
1728
+ const userTier = state.userTier || "free";
1729
+ const userLevel = TIER_LEVELS[userTier] ?? 0;
1730
+ const requiredLevel = TIER_LEVELS[minTier] ?? 0;
1731
+ setHasAccess(userLevel >= requiredLevel);
1732
+ }, [minTier]);
1733
+ if (hasAccess === null)
1734
+ return /* @__PURE__ */ jsxDEV("span", {
1735
+ className
1736
+ }, undefined, false, undefined, this);
1737
+ return /* @__PURE__ */ jsxDEV("span", {
1738
+ className,
1739
+ children: hasAccess ? children : fallback
1740
+ }, undefined, false, undefined, this);
1741
+ }
1742
+ function ESIEmotionGate({
1743
+ allow,
1744
+ block,
1745
+ valenceRange,
1746
+ arousalRange,
1747
+ children,
1748
+ fallback = null,
1749
+ className
1750
+ }) {
1751
+ const [hasAccess, setHasAccess] = useState(null);
1752
+ useEffect(() => {
1753
+ const state = typeof window !== "undefined" && window.__AEON_ESI_STATE__ || {};
1754
+ const emotion = state.emotionState || {};
1755
+ let access = true;
1756
+ if (allow && allow.length > 0 && emotion.primary) {
1757
+ access = access && allow.includes(emotion.primary);
1758
+ }
1759
+ if (block && block.length > 0 && emotion.primary) {
1760
+ access = access && !block.includes(emotion.primary);
1761
+ }
1762
+ if (valenceRange && emotion.valence !== undefined) {
1763
+ access = access && emotion.valence >= valenceRange[0] && emotion.valence <= valenceRange[1];
1764
+ }
1765
+ if (arousalRange && emotion.arousal !== undefined) {
1766
+ access = access && emotion.arousal >= arousalRange[0] && emotion.arousal <= arousalRange[1];
1767
+ }
1768
+ setHasAccess(access);
1769
+ }, [allow, block, valenceRange, arousalRange]);
1770
+ if (hasAccess === null)
1771
+ return /* @__PURE__ */ jsxDEV("span", {
1772
+ className
1773
+ }, undefined, false, undefined, this);
1774
+ return /* @__PURE__ */ jsxDEV("span", {
1775
+ className,
1776
+ children: hasAccess ? children : fallback
1777
+ }, undefined, false, undefined, this);
1778
+ }
1779
+ function ESITimeGate({
1780
+ after,
1781
+ before,
1782
+ days,
1783
+ children,
1784
+ fallback = null,
1785
+ className
1786
+ }) {
1787
+ const [inRange, setInRange] = useState(null);
1788
+ useEffect(() => {
1789
+ const now = new Date;
1790
+ const hour = now.getHours();
1791
+ const day = now.getDay();
1792
+ let access = true;
1793
+ if (after !== undefined)
1794
+ access = access && hour >= after;
1795
+ if (before !== undefined)
1796
+ access = access && hour < before;
1797
+ if (days && days.length > 0)
1798
+ access = access && days.includes(day);
1799
+ setInRange(access);
1800
+ }, [after, before, days]);
1801
+ if (inRange === null)
1802
+ return /* @__PURE__ */ jsxDEV("span", {
1803
+ className
1804
+ }, undefined, false, undefined, this);
1805
+ return /* @__PURE__ */ jsxDEV("span", {
1806
+ className,
1807
+ children: inRange ? children : fallback
1808
+ }, undefined, false, undefined, this);
1809
+ }
1810
+ function ESIABTest({
1811
+ name,
1812
+ variants,
1813
+ selectionPrompt,
1814
+ random = false,
1815
+ onSelect,
1816
+ loading = null,
1817
+ className
1818
+ }) {
1819
+ const [selectedVariant, setSelectedVariant] = useState(null);
1820
+ const variantKeys = Object.keys(variants);
1821
+ useEffect(() => {
1822
+ if (random || !selectionPrompt) {
1823
+ const selected = variantKeys[Math.floor(Math.random() * variantKeys.length)];
1824
+ setSelectedVariant(selected);
1825
+ onSelect?.(selected);
1826
+ }
1827
+ }, [random, selectionPrompt]);
1828
+ if (random || !selectionPrompt) {
1829
+ if (!selectedVariant)
1830
+ return /* @__PURE__ */ jsxDEV("span", {
1831
+ className,
1832
+ children: loading
1833
+ }, undefined, false, undefined, this);
1834
+ return /* @__PURE__ */ jsxDEV("span", {
1835
+ className,
1836
+ children: variants[selectedVariant]
1837
+ }, undefined, false, undefined, this);
1838
+ }
1839
+ const variantSchema = {
1840
+ safeParse: (val) => {
1841
+ const str = String(val).trim();
1842
+ if (variantKeys.includes(str))
1843
+ return { success: true, data: str };
1844
+ for (const key of variantKeys) {
1845
+ if (str.toLowerCase().includes(key.toLowerCase())) {
1846
+ return { success: true, data: key };
1847
+ }
1848
+ }
1849
+ return { success: false, error: "Invalid variant" };
1850
+ }
1851
+ };
1852
+ return /* @__PURE__ */ jsxDEV("span", {
1853
+ className,
1854
+ children: [
1855
+ /* @__PURE__ */ jsxDEV(ESIStructured, {
1856
+ prompt: `${selectionPrompt}
1857
+
1858
+ Available variants: ${variantKeys.join(", ")}
1859
+
1860
+ Respond with only the variant name.`,
1861
+ schema: variantSchema,
1862
+ loading,
1863
+ onSuccess: (selected) => {
1864
+ setSelectedVariant(selected);
1865
+ onSelect?.(selected);
1866
+ },
1867
+ render: () => null
1868
+ }, undefined, false, undefined, this),
1869
+ selectedVariant && variants[selectedVariant]
1870
+ ]
1871
+ }, undefined, true, undefined, this);
1872
+ }
1873
+ function ESIForEach({
1874
+ prompt,
1875
+ itemSchema,
1876
+ render,
1877
+ maxItems = 10,
1878
+ empty = null,
1879
+ loading = "...",
1880
+ as: Wrapper = "div",
1881
+ className
1882
+ }) {
1883
+ const [items, setItems] = useState([]);
1884
+ const [isLoading, setIsLoading] = useState(true);
1885
+ const arraySchema = {
1886
+ safeParse: (val) => {
1887
+ try {
1888
+ let arr;
1889
+ if (Array.isArray(val)) {
1890
+ arr = val;
1891
+ } else if (typeof val === "string") {
1892
+ arr = JSON.parse(val);
1893
+ } else if (typeof val === "object" && val !== null && "items" in val) {
1894
+ arr = val.items;
1895
+ } else {
1896
+ return { success: false, error: "Not an array" };
1897
+ }
1898
+ const validItems = [];
1899
+ for (const item of arr.slice(0, maxItems)) {
1900
+ const result = itemSchema.safeParse(item);
1901
+ if (result.success) {
1902
+ validItems.push(result.data);
1903
+ }
1904
+ }
1905
+ return { success: true, data: validItems };
1906
+ } catch {
1907
+ return { success: false, error: "Parse error" };
1908
+ }
1909
+ }
1910
+ };
1911
+ return /* @__PURE__ */ jsxDEV(ESIStructured, {
1912
+ prompt: `${prompt}
1913
+
1914
+ Respond with a JSON array of items (max ${maxItems}).`,
1915
+ schema: arraySchema,
1916
+ loading,
1917
+ fallback: empty,
1918
+ className,
1919
+ onSuccess: (result) => {
1920
+ setItems(result);
1921
+ setIsLoading(false);
1922
+ },
1923
+ render: (data) => {
1924
+ if (data.length === 0)
1925
+ return /* @__PURE__ */ jsxDEV(Fragment, {
1926
+ children: empty
1927
+ }, undefined, false, undefined, this);
1928
+ return /* @__PURE__ */ jsxDEV(Wrapper, {
1929
+ className,
1930
+ children: data.map((item, i) => render(item, i))
1931
+ }, undefined, false, undefined, this);
1932
+ }
1933
+ }, undefined, false, undefined, this);
1934
+ }
1935
+ function ESIFirst({
1936
+ context,
1937
+ children,
1938
+ fallback = null,
1939
+ loading = null,
1940
+ className
1941
+ }) {
1942
+ return /* @__PURE__ */ jsxDEV("span", {
1943
+ className,
1944
+ children
1945
+ }, undefined, false, undefined, this);
1946
+ }
1947
+ function ESIClamp({
1948
+ prompt,
1949
+ min,
1950
+ max,
1951
+ render,
1952
+ defaultValue,
1953
+ loading = "...",
1954
+ className
1955
+ }) {
1956
+ const numSchema = {
1957
+ safeParse: (val) => {
1958
+ let num;
1959
+ if (typeof val === "number") {
1960
+ num = val;
1961
+ } else if (typeof val === "string") {
1962
+ num = parseFloat(val);
1963
+ } else if (typeof val === "object" && val !== null && "value" in val) {
1964
+ num = Number(val.value);
1965
+ } else {
1966
+ return { success: false, error: "Not a number" };
1967
+ }
1968
+ if (isNaN(num))
1969
+ return { success: false, error: "NaN" };
1970
+ return { success: true, data: Math.max(min, Math.min(max, num)) };
1971
+ }
1972
+ };
1973
+ return /* @__PURE__ */ jsxDEV(ESIStructured, {
1974
+ prompt: `${prompt}
1975
+
1976
+ Respond with a number between ${min} and ${max}.`,
1977
+ schema: numSchema,
1978
+ loading,
1979
+ fallback: defaultValue !== undefined ? render(defaultValue) : null,
1980
+ className,
1981
+ render: (value) => render(value)
1982
+ }, undefined, false, undefined, this);
1983
+ }
1984
+ function ESISelect({
1985
+ prompt,
1986
+ options,
1987
+ render,
1988
+ defaultOption,
1989
+ loading = "...",
1990
+ onSelect,
1991
+ className
1992
+ }) {
1993
+ const optionSchema = {
1994
+ safeParse: (val) => {
1995
+ const str = String(val).trim().toLowerCase();
1996
+ const match = options.find((o) => o.toLowerCase() === str);
1997
+ if (match)
1998
+ return { success: true, data: match };
1999
+ const partial = options.find((o) => str.includes(o.toLowerCase()) || o.toLowerCase().includes(str));
2000
+ if (partial)
2001
+ return { success: true, data: partial };
2002
+ return { success: false, error: "No match" };
2003
+ }
2004
+ };
2005
+ return /* @__PURE__ */ jsxDEV(ESIStructured, {
2006
+ prompt: `${prompt}
2007
+
2008
+ Options: ${options.join(", ")}
2009
+
2010
+ Respond with only one of the options.`,
2011
+ schema: optionSchema,
2012
+ loading,
2013
+ fallback: defaultOption ? render(defaultOption) : null,
2014
+ className,
2015
+ onSuccess: onSelect,
2016
+ render: (selected) => render(selected)
2017
+ }, undefined, false, undefined, this);
2018
+ }
2019
+ var DEFAULT_THRESHOLDS = [
2020
+ { value: 0.2, label: "very low" },
2021
+ { value: 0.4, label: "low" },
2022
+ { value: 0.6, label: "moderate" },
2023
+ { value: 0.8, label: "high" },
2024
+ { value: 1, label: "very high" }
2025
+ ];
2026
+ function ESIScore({
2027
+ prompt,
2028
+ render,
2029
+ thresholds = DEFAULT_THRESHOLDS,
2030
+ loading = "...",
2031
+ className
2032
+ }) {
2033
+ return /* @__PURE__ */ jsxDEV(ESIClamp, {
2034
+ prompt,
2035
+ min: 0,
2036
+ max: 1,
2037
+ loading,
2038
+ className,
2039
+ render: (score) => {
2040
+ const label = thresholds.find((t) => score <= t.value)?.label || "unknown";
2041
+ return render(score, label);
2042
+ }
2043
+ }, undefined, false, undefined, this);
2044
+ }
2045
+ var ESIControl = {
2046
+ Structured: ESIStructured,
2047
+ If: ESIIf,
2048
+ Show: ESIShow,
2049
+ Hide: ESIHide,
2050
+ When: ESIWhen,
2051
+ Unless: ESIUnless,
2052
+ Match: ESIMatch,
2053
+ Case: ESICase,
2054
+ Default: ESIDefault,
2055
+ First: ESIFirst,
2056
+ TierGate: ESITierGate,
2057
+ EmotionGate: ESIEmotionGate,
2058
+ TimeGate: ESITimeGate,
2059
+ ForEach: ESIForEach,
2060
+ Select: ESISelect,
2061
+ ABTest: ESIABTest,
2062
+ Clamp: ESIClamp,
2063
+ Score: ESIScore,
2064
+ Collaborative: ESICollaborative,
2065
+ Reflect: ESIReflect,
2066
+ Optimize: ESIOptimize,
2067
+ Auto: ESIAuto
2068
+ };
2069
+
2070
+ // src/router/esi-react.tsx
2071
+ import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
2072
+ var ESIContext = createContext2(null);
2073
+ var ESIProvider = ({
2074
+ children,
2075
+ config,
2076
+ userContext,
2077
+ processor: customProcessor
2078
+ }) => {
2079
+ const [processor] = useState2(() => customProcessor || new EdgeWorkersESIProcessor(config));
2080
+ useEffect2(() => {
2081
+ processor.warmup?.();
2082
+ }, [processor]);
2083
+ const process2 = useCallback2(async (directive) => {
2084
+ if (!userContext) {
2085
+ return {
2086
+ id: directive.id,
2087
+ success: false,
2088
+ error: "No user context available",
2089
+ latencyMs: 0,
2090
+ cached: false,
2091
+ model: directive.params.model
2092
+ };
2093
+ }
2094
+ return processor.process(directive, userContext);
2095
+ }, [processor, userContext]);
2096
+ const processWithStream = useCallback2(async (directive, onChunk) => {
2097
+ if (!userContext) {
2098
+ return {
2099
+ id: directive.id,
2100
+ success: false,
2101
+ error: "No user context available",
2102
+ latencyMs: 0,
2103
+ cached: false,
2104
+ model: directive.params.model
2105
+ };
2106
+ }
2107
+ if (!processor.stream) {
2108
+ return processor.process(directive, userContext);
2109
+ }
2110
+ return processor.stream(directive, userContext, onChunk);
2111
+ }, [processor, userContext]);
2112
+ return /* @__PURE__ */ jsxDEV2(ESIContext.Provider, {
2113
+ value: {
2114
+ processor,
2115
+ userContext: userContext || null,
2116
+ enabled: config?.enabled ?? true,
2117
+ process: process2,
2118
+ processWithStream
2119
+ },
2120
+ children
2121
+ }, undefined, false, undefined, this);
2122
+ };
2123
+ function useESI() {
2124
+ const ctx = useContext2(ESIContext);
2125
+ if (!ctx) {
2126
+ throw new Error("useESI must be used within an ESIProvider");
2127
+ }
2128
+ return ctx;
2129
+ }
2130
+ var ESIInfer = ({
2131
+ children,
2132
+ prompt,
2133
+ model = "llm",
2134
+ variant,
2135
+ temperature,
2136
+ maxTokens,
2137
+ system,
2138
+ stream = false,
2139
+ fallback,
2140
+ loading = "...",
2141
+ contextAware = false,
2142
+ signals,
2143
+ cacheTtl,
2144
+ render,
2145
+ className,
2146
+ onComplete,
2147
+ onError
2148
+ }) => {
2149
+ const { process: process2, processWithStream, enabled } = useESI();
2150
+ const [output, setOutput] = useState2("");
2151
+ const [isLoading, setIsLoading] = useState2(true);
2152
+ const [error, setError] = useState2(null);
2153
+ const promptText = prompt || (typeof children === "string" ? children : String(children || ""));
2154
+ useEffect2(() => {
2155
+ if (!enabled) {
2156
+ setOutput(typeof fallback === "string" ? fallback : "");
2157
+ setIsLoading(false);
2158
+ return;
2159
+ }
2160
+ const directive = contextAware ? esiWithContext(promptText, signals, {
2161
+ model,
2162
+ variant,
2163
+ temperature,
2164
+ maxTokens,
2165
+ system,
2166
+ cacheTtl,
2167
+ fallback: typeof fallback === "string" ? fallback : undefined
2168
+ }) : esiInfer(promptText, {
2169
+ model,
2170
+ variant,
2171
+ temperature,
2172
+ maxTokens,
2173
+ system,
2174
+ cacheTtl,
2175
+ fallback: typeof fallback === "string" ? fallback : undefined
2176
+ });
2177
+ if (stream) {
2178
+ setOutput("");
2179
+ processWithStream(directive, (chunk) => {
2180
+ setOutput((prev) => prev + chunk);
2181
+ }).then((result) => {
2182
+ setIsLoading(false);
2183
+ if (!result.success) {
2184
+ setError(result.error || "Inference failed");
2185
+ onError?.(result.error || "Inference failed");
2186
+ }
2187
+ onComplete?.(result);
2188
+ });
2189
+ } else {
2190
+ process2(directive).then((result) => {
2191
+ setIsLoading(false);
2192
+ if (result.success && result.output) {
2193
+ setOutput(result.output);
2194
+ } else {
2195
+ setError(result.error || "Inference failed");
2196
+ onError?.(result.error || "Inference failed");
2197
+ }
2198
+ onComplete?.(result);
2199
+ });
2200
+ }
2201
+ }, [promptText, model, variant, temperature, maxTokens, system, contextAware, stream, enabled]);
2202
+ if (isLoading && !stream) {
2203
+ return /* @__PURE__ */ jsxDEV2("span", {
2204
+ className,
2205
+ children: loading
2206
+ }, undefined, false, undefined, this);
2207
+ }
2208
+ if (error && fallback) {
2209
+ return /* @__PURE__ */ jsxDEV2("span", {
2210
+ className,
2211
+ children: fallback
2212
+ }, undefined, false, undefined, this);
2213
+ }
2214
+ if (render) {
2215
+ return /* @__PURE__ */ jsxDEV2("span", {
2216
+ className,
2217
+ children: render({
2218
+ id: "",
2219
+ success: !error,
2220
+ output,
2221
+ error: error || undefined,
2222
+ latencyMs: 0,
2223
+ cached: false,
2224
+ model
2225
+ })
2226
+ }, undefined, false, undefined, this);
2227
+ }
2228
+ return /* @__PURE__ */ jsxDEV2("span", {
2229
+ className,
2230
+ children: output || (isLoading ? loading : "")
2231
+ }, undefined, false, undefined, this);
2232
+ };
2233
+ var ESIEmbed = ({ children, onComplete, onError }) => {
2234
+ const { process: process2, enabled } = useESI();
2235
+ const text = typeof children === "string" ? children : String(children || "");
2236
+ useEffect2(() => {
2237
+ if (!enabled)
2238
+ return;
2239
+ const directive = esiEmbed(text);
2240
+ process2(directive).then((result) => {
2241
+ if (result.success && result.embedding) {
2242
+ onComplete?.(result.embedding);
2243
+ } else {
2244
+ onError?.(result.error || "Embedding failed");
2245
+ }
2246
+ });
2247
+ }, [text, enabled]);
2248
+ return null;
2249
+ };
2250
+ var ESIEmotion = ({
2251
+ children,
2252
+ contextAware = true,
2253
+ onComplete,
2254
+ onError
2255
+ }) => {
2256
+ const { process: process2, enabled } = useESI();
2257
+ const text = typeof children === "string" ? children : String(children || "");
2258
+ useEffect2(() => {
2259
+ if (!enabled)
2260
+ return;
2261
+ const directive = esiEmotion(text, contextAware);
2262
+ process2(directive).then((result) => {
2263
+ if (result.success && result.output) {
2264
+ try {
2265
+ const parsed = JSON.parse(result.output);
2266
+ onComplete?.(parsed);
2267
+ } catch {
2268
+ onComplete?.({ emotion: result.output, confidence: 1 });
2269
+ }
2270
+ } else {
2271
+ onError?.(result.error || "Emotion detection failed");
2272
+ }
2273
+ });
2274
+ }, [text, contextAware, enabled]);
2275
+ return null;
2276
+ };
2277
+ var ESIVision = ({
2278
+ src,
2279
+ prompt,
2280
+ fallback,
2281
+ loading = "...",
2282
+ className,
2283
+ onComplete,
2284
+ onError
2285
+ }) => {
2286
+ const { process: process2, enabled } = useESI();
2287
+ const [output, setOutput] = useState2("");
2288
+ const [isLoading, setIsLoading] = useState2(true);
2289
+ const [error, setError] = useState2(null);
2290
+ useEffect2(() => {
2291
+ if (!enabled) {
2292
+ setOutput(typeof fallback === "string" ? fallback : "");
2293
+ setIsLoading(false);
2294
+ return;
2295
+ }
2296
+ const directive = esiVision(src, prompt);
2297
+ process2(directive).then((result) => {
2298
+ setIsLoading(false);
2299
+ if (result.success && result.output) {
2300
+ setOutput(result.output);
2301
+ } else {
2302
+ setError(result.error || "Vision analysis failed");
2303
+ onError?.(result.error || "Vision analysis failed");
2304
+ }
2305
+ onComplete?.(result);
2306
+ });
2307
+ }, [src, prompt, enabled]);
2308
+ if (isLoading) {
2309
+ return /* @__PURE__ */ jsxDEV2("span", {
2310
+ className,
2311
+ children: loading
2312
+ }, undefined, false, undefined, this);
2313
+ }
2314
+ if (error && fallback) {
2315
+ return /* @__PURE__ */ jsxDEV2("span", {
2316
+ className,
2317
+ children: fallback
2318
+ }, undefined, false, undefined, this);
2319
+ }
2320
+ return /* @__PURE__ */ jsxDEV2("span", {
2321
+ className,
2322
+ children: output
2323
+ }, undefined, false, undefined, this);
2324
+ };
2325
+ function useESIInfer(options = {}) {
2326
+ const { process: process2, processWithStream, enabled } = useESI();
2327
+ const [result, setResult] = useState2(null);
2328
+ const [isLoading, setIsLoading] = useState2(false);
2329
+ const [error, setError] = useState2(null);
2330
+ const run = useCallback2(async (prompt) => {
2331
+ if (!enabled) {
2332
+ setError("ESI is disabled");
2333
+ return null;
2334
+ }
2335
+ setIsLoading(true);
2336
+ setError(null);
2337
+ const directive = options.contextAware ? esiWithContext(prompt, options.signals, {
2338
+ model: options.model,
2339
+ variant: options.variant,
2340
+ temperature: options.temperature,
2341
+ maxTokens: options.maxTokens,
2342
+ system: options.system,
2343
+ cacheTtl: options.cacheTtl
2344
+ }) : esiInfer(prompt, {
2345
+ model: options.model,
2346
+ variant: options.variant,
2347
+ temperature: options.temperature,
2348
+ maxTokens: options.maxTokens,
2349
+ system: options.system,
2350
+ cacheTtl: options.cacheTtl
2351
+ });
2352
+ try {
2353
+ let inferenceResult;
2354
+ if (options.stream) {
2355
+ let output = "";
2356
+ inferenceResult = await processWithStream(directive, (chunk) => {
2357
+ output += chunk;
2358
+ setResult((prev) => ({
2359
+ ...prev,
2360
+ output
2361
+ }));
2362
+ });
2363
+ } else {
2364
+ inferenceResult = await process2(directive);
2365
+ }
2366
+ setResult(inferenceResult);
2367
+ setIsLoading(false);
2368
+ if (!inferenceResult.success) {
2369
+ setError(inferenceResult.error || "Inference failed");
2370
+ }
2371
+ options.onComplete?.(inferenceResult);
2372
+ return inferenceResult;
2373
+ } catch (err) {
2374
+ const errorMsg = err instanceof Error ? err.message : "Unknown error";
2375
+ setError(errorMsg);
2376
+ setIsLoading(false);
2377
+ options.onError?.(errorMsg);
2378
+ return null;
2379
+ }
2380
+ }, [process2, processWithStream, enabled, options]);
2381
+ const reset = useCallback2(() => {
2382
+ setResult(null);
2383
+ setError(null);
2384
+ setIsLoading(false);
2385
+ }, []);
2386
+ return { run, result, isLoading, error, reset };
2387
+ }
2388
+ var DEFAULT_ESI_STATE = {
2389
+ userTier: "free",
2390
+ emotionState: null,
2391
+ preferences: {
2392
+ theme: "auto",
2393
+ reducedMotion: false
2394
+ },
2395
+ localHour: new Date().getHours(),
2396
+ timezone: "UTC",
2397
+ features: {
2398
+ aiInference: true,
2399
+ emotionTracking: true,
2400
+ collaboration: false,
2401
+ advancedInsights: false,
2402
+ customThemes: false,
2403
+ voiceSynthesis: false,
2404
+ imageAnalysis: false
2405
+ },
2406
+ isNewSession: true,
2407
+ recentPages: [],
2408
+ viewport: { width: 1920, height: 1080 },
2409
+ connection: "4g"
2410
+ };
2411
+ function useGlobalESIState() {
2412
+ const [state, setState] = useState2(() => {
2413
+ if (typeof window !== "undefined" && window.__AEON_ESI_STATE__) {
2414
+ return window.__AEON_ESI_STATE__;
2415
+ }
2416
+ return DEFAULT_ESI_STATE;
2417
+ });
2418
+ useEffect2(() => {
2419
+ if (typeof window !== "undefined" && window.__AEON_ESI_STATE__?.subscribe) {
2420
+ const unsubscribe = window.__AEON_ESI_STATE__.subscribe((newState) => {
2421
+ setState(newState);
2422
+ });
2423
+ return unsubscribe;
2424
+ }
2425
+ }, []);
2426
+ return state;
2427
+ }
2428
+ function useESIFeature(feature) {
2429
+ const { features } = useGlobalESIState();
2430
+ return features[feature] ?? false;
2431
+ }
2432
+ function useESITier() {
2433
+ const { userTier } = useGlobalESIState();
2434
+ return userTier;
2435
+ }
2436
+ function useESIEmotionState() {
2437
+ const { emotionState } = useGlobalESIState();
2438
+ return emotionState;
2439
+ }
2440
+ function useESIPreferences() {
2441
+ const { preferences } = useGlobalESIState();
2442
+ return preferences;
2443
+ }
2444
+ function updateGlobalESIState(partial) {
2445
+ if (typeof window !== "undefined" && window.__AEON_ESI_STATE__?.update) {
2446
+ window.__AEON_ESI_STATE__.update(partial);
2447
+ } else if (typeof window !== "undefined" && window.__AEON_ESI_STATE__) {
2448
+ Object.assign(window.__AEON_ESI_STATE__, partial);
2449
+ }
2450
+ }
2451
+ var ESI = {
2452
+ Provider: ESIProvider,
2453
+ Infer: ESIInfer,
2454
+ Embed: ESIEmbed,
2455
+ Emotion: ESIEmotion,
2456
+ Vision: ESIVision,
2457
+ Structured: ESIStructured,
2458
+ If: ESIIf,
2459
+ Show: ESIShow,
2460
+ Hide: ESIHide,
2461
+ When: ESIWhen,
2462
+ Unless: ESIUnless,
2463
+ Match: ESIMatch,
2464
+ Case: ESICase,
2465
+ Default: ESIDefault,
2466
+ First: ESIFirst,
2467
+ TierGate: ESITierGate,
2468
+ EmotionGate: ESIEmotionGate,
2469
+ TimeGate: ESITimeGate,
2470
+ ForEach: ESIForEach,
2471
+ Select: ESISelect,
2472
+ ABTest: ESIABTest,
2473
+ Clamp: ESIClamp,
2474
+ Score: ESIScore,
2475
+ Collaborative: ESICollaborative,
2476
+ Reflect: ESIReflect,
2477
+ Optimize: ESIOptimize,
2478
+ Auto: ESIAuto
2479
+ };
2480
+ // src/router/heuristic-adapter.ts
2481
+ var DEFAULT_CONFIG = {
2482
+ tierFeatures: {
2483
+ free: {},
2484
+ starter: {},
2485
+ pro: {},
2486
+ enterprise: {}
2487
+ },
2488
+ defaultAccent: "#336699",
2489
+ signals: {},
2490
+ defaultPaths: ["/"],
2491
+ maxSpeculationPaths: 5
2492
+ };
2493
+ function defaultDeriveTheme(context) {
2494
+ if (context.preferences.theme) {
2495
+ return context.preferences.theme;
2496
+ }
2497
+ const hour = context.localHour;
2498
+ const isNight = hour >= 20 || hour < 6;
2499
+ const isEvening = hour >= 18 && hour < 20;
2500
+ if (isNight) {
2501
+ return "dark";
2502
+ }
2503
+ if (isEvening) {
2504
+ return "auto";
2505
+ }
2506
+ return "light";
2507
+ }
2508
+ function determineDensity(context) {
2509
+ if (context.preferences.density) {
2510
+ return context.preferences.density;
2511
+ }
2512
+ const { width, height } = context.viewport;
2513
+ if (width < 768) {
2514
+ return "compact";
2515
+ }
2516
+ if (width >= 1440 && height >= 900) {
2517
+ return "comfortable";
2518
+ }
2519
+ return "normal";
2520
+ }
2521
+ function buildTransitionMatrix(history) {
2522
+ const matrix = {};
2523
+ for (let i = 0;i < history.length - 1; i++) {
2524
+ const from = history[i];
2525
+ const to = history[i + 1];
2526
+ if (!matrix[from]) {
2527
+ matrix[from] = {};
2528
+ }
2529
+ matrix[from][to] = (matrix[from][to] || 0) + 1;
2530
+ }
2531
+ for (const from of Object.keys(matrix)) {
2532
+ const total = Object.values(matrix[from]).reduce((a, b) => a + b, 0);
2533
+ for (const to of Object.keys(matrix[from])) {
2534
+ matrix[from][to] /= total;
2535
+ }
2536
+ }
2537
+ return matrix;
2538
+ }
2539
+ function defaultPredictNavigation(currentPath, context, defaultPaths, topN) {
2540
+ const history = context.recentPages;
2541
+ if (history.length >= 3) {
2542
+ const matrix = buildTransitionMatrix(history);
2543
+ const transitions = matrix[currentPath];
2544
+ if (transitions) {
2545
+ const sorted = Object.entries(transitions).sort(([, a], [, b]) => b - a).slice(0, topN).map(([path]) => path);
2546
+ if (sorted.length > 0) {
2547
+ return sorted;
2548
+ }
2549
+ }
2550
+ }
2551
+ return defaultPaths.filter((p) => p !== currentPath).slice(0, topN);
2552
+ }
2553
+ function defaultScoreRelevance(node, context) {
2554
+ let score = 50;
2555
+ if (node.requiredTier) {
2556
+ const tierOrder = ["free", "starter", "pro", "enterprise"];
2557
+ const requiredIndex = tierOrder.indexOf(node.requiredTier);
2558
+ const userIndex = tierOrder.indexOf(context.tier);
2559
+ if (userIndex < requiredIndex) {
2560
+ return 0;
2561
+ }
2562
+ score += 10;
2563
+ }
2564
+ if (node.relevanceSignals) {
2565
+ for (const signal of node.relevanceSignals) {
2566
+ if (signal.startsWith("recentPage:")) {
2567
+ const page = signal.slice("recentPage:".length);
2568
+ if (context.recentPages.includes(page)) {
2569
+ score += 20;
2570
+ }
2571
+ }
2572
+ if (signal.startsWith("timeOfDay:")) {
2573
+ const timeRange = signal.slice("timeOfDay:".length);
2574
+ const hour = context.localHour;
2575
+ if (timeRange === "morning" && hour >= 5 && hour < 12)
2576
+ score += 15;
2577
+ if (timeRange === "afternoon" && hour >= 12 && hour < 17)
2578
+ score += 15;
2579
+ if (timeRange === "evening" && hour >= 17 && hour < 21)
2580
+ score += 15;
2581
+ if (timeRange === "night" && (hour >= 21 || hour < 5))
2582
+ score += 15;
2583
+ }
2584
+ if (signal.startsWith("preference:")) {
2585
+ const pref = signal.slice("preference:".length);
2586
+ if (context.preferences[pref]) {
2587
+ score += 20;
2588
+ }
2589
+ }
2590
+ if (signal.startsWith("tier:")) {
2591
+ const requiredTier = signal.slice("tier:".length);
2592
+ const tierOrder = ["free", "starter", "pro", "enterprise"];
2593
+ if (tierOrder.indexOf(context.tier) >= tierOrder.indexOf(requiredTier)) {
2594
+ score += 15;
2595
+ }
2596
+ }
2597
+ }
2598
+ }
2599
+ if (node.defaultHidden) {
2600
+ score -= 30;
2601
+ }
2602
+ return Math.max(0, Math.min(100, score));
2603
+ }
2604
+ function orderComponentsByRelevance(tree, context, scoreRelevance) {
2605
+ const scored = [];
2606
+ tree.nodes.forEach((node, id) => {
2607
+ scored.push({
2608
+ id,
2609
+ score: scoreRelevance(node, context)
2610
+ });
2611
+ });
2612
+ return scored.sort((a, b) => b.score - a.score).map((s) => s.id);
2613
+ }
2614
+ function findHiddenComponents(tree, context, scoreRelevance) {
2615
+ const hidden = [];
2616
+ tree.nodes.forEach((node, id) => {
2617
+ const score = scoreRelevance(node, context);
2618
+ if (score === 0) {
2619
+ hidden.push(id);
2620
+ }
2621
+ });
2622
+ return hidden;
2623
+ }
2624
+ function computeSkeletonHints(route, context, tree) {
2625
+ let layout = "custom";
2626
+ if (route === "/" || route.includes("dashboard")) {
2627
+ layout = "dashboard";
2628
+ } else if (route.includes("chat") || route.includes("message")) {
2629
+ layout = "chat";
2630
+ } else if (route.includes("setting") || route.includes("config")) {
2631
+ layout = "settings";
2632
+ } else if (route.includes("tool")) {
2633
+ layout = "tools";
2634
+ }
2635
+ const baseHeight = context.viewport.height;
2636
+ const contentMultiplier = tree.nodes.size > 10 ? 1.5 : 1;
2637
+ const estimatedHeight = Math.round(baseHeight * contentMultiplier);
2638
+ const sections = tree.getChildren(tree.rootId).map((child, i) => ({
2639
+ id: child.id,
2640
+ height: Math.round(estimatedHeight / (tree.nodes.size || 1)),
2641
+ priority: i + 1
2642
+ }));
2643
+ return {
2644
+ layout,
2645
+ estimatedHeight,
2646
+ sections
2647
+ };
2648
+ }
2649
+ function getPrefetchDepth(context) {
2650
+ switch (context.connection) {
2651
+ case "fast":
2652
+ case "4g":
2653
+ return { prefetch: 5, prerender: 1 };
2654
+ case "3g":
2655
+ return { prefetch: 3, prerender: 0 };
2656
+ case "2g":
2657
+ return { prefetch: 1, prerender: 0 };
2658
+ case "slow-2g":
2659
+ return { prefetch: 0, prerender: 0 };
2660
+ default:
2661
+ return { prefetch: 3, prerender: 0 };
2662
+ }
2663
+ }
2664
+
2665
+ class HeuristicAdapter {
2666
+ name = "heuristic";
2667
+ config;
2668
+ constructor(config = {}) {
2669
+ this.config = {
2670
+ ...DEFAULT_CONFIG,
2671
+ ...config,
2672
+ tierFeatures: config.tierFeatures ?? DEFAULT_CONFIG.tierFeatures,
2673
+ signals: config.signals ?? DEFAULT_CONFIG.signals
2674
+ };
2675
+ }
2676
+ async route(path, context, tree) {
2677
+ const startTime = Date.now();
2678
+ const sessionId = this.generateSessionId(path, context);
2679
+ const featureFlags = { ...this.config.tierFeatures[context.tier] };
2680
+ const theme = this.config.signals.deriveTheme ? this.config.signals.deriveTheme(context) : defaultDeriveTheme(context);
2681
+ const accent = this.config.signals.deriveAccent ? this.config.signals.deriveAccent(context) : this.config.defaultAccent;
2682
+ const density = determineDensity(context);
2683
+ const scoreRelevance = this.config.signals.scoreRelevance ?? defaultScoreRelevance;
2684
+ const componentOrder = orderComponentsByRelevance(tree, context, scoreRelevance);
2685
+ const hiddenComponents = findHiddenComponents(tree, context, scoreRelevance);
2686
+ const predictions = this.config.signals.predictNavigation ? this.config.signals.predictNavigation(path, context) : defaultPredictNavigation(path, context, this.config.defaultPaths, this.config.maxSpeculationPaths);
2687
+ const { prefetch: prefetchDepth, prerender: prerenderCount } = getPrefetchDepth(context);
2688
+ const prefetch = predictions.slice(0, prefetchDepth);
2689
+ const prerender = predictions.slice(0, prerenderCount);
2690
+ const skeleton = computeSkeletonHints(path, context, tree);
2691
+ return {
2692
+ route: path,
2693
+ sessionId,
2694
+ componentOrder,
2695
+ hiddenComponents,
2696
+ featureFlags,
2697
+ theme,
2698
+ accent,
2699
+ density,
2700
+ prefetch,
2701
+ prerender,
2702
+ skeleton,
2703
+ routedAt: startTime,
2704
+ routerName: this.name,
2705
+ confidence: 0.85
2706
+ };
2707
+ }
2708
+ async speculate(currentPath, context) {
2709
+ return this.config.signals.predictNavigation ? this.config.signals.predictNavigation(currentPath, context) : defaultPredictNavigation(currentPath, context, this.config.defaultPaths, this.config.maxSpeculationPaths);
2710
+ }
2711
+ personalizeTree(tree, decision) {
2712
+ const cloned = tree.clone();
2713
+ if (decision.hiddenComponents) {
2714
+ for (const id of decision.hiddenComponents) {
2715
+ const node = cloned.getNode(id);
2716
+ if (node) {
2717
+ node.defaultHidden = true;
2718
+ }
2719
+ }
2720
+ }
2721
+ return cloned;
2722
+ }
2723
+ emotionToAccent(emotionState) {
2724
+ if (this.config.signals.deriveAccent) {
2725
+ return this.config.signals.deriveAccent({
2726
+ emotionState,
2727
+ tier: "free",
2728
+ recentPages: [],
2729
+ dwellTimes: new Map,
2730
+ clickPatterns: [],
2731
+ preferences: {},
2732
+ viewport: { width: 0, height: 0 },
2733
+ connection: "fast",
2734
+ reducedMotion: false,
2735
+ localHour: 12,
2736
+ timezone: "UTC",
2737
+ isNewSession: true
2738
+ });
2739
+ }
2740
+ return this.config.defaultAccent;
2741
+ }
2742
+ generateSessionId(path, context) {
2743
+ const base = path.replace(/^\/|\/$/g, "").replace(/\//g, "-") || "index";
2744
+ const userId = context.userId || "anon";
2745
+ const sessionPrefix = context.sessionId || Date.now().toString(36);
2746
+ return `${base}-${userId.slice(0, 8)}-${sessionPrefix.slice(0, 8)}`;
2747
+ }
2748
+ }
2749
+ // src/router/context-extractor.ts
2750
+ function parseCookies(cookieHeader) {
2751
+ if (!cookieHeader)
2752
+ return {};
2753
+ return cookieHeader.split(";").reduce((acc, cookie) => {
2754
+ const [key, value] = cookie.trim().split("=");
2755
+ if (key && value) {
2756
+ acc[key] = decodeURIComponent(value);
2757
+ }
2758
+ return acc;
2759
+ }, {});
2760
+ }
2761
+ function parseJSON(value, fallback) {
2762
+ if (!value)
2763
+ return fallback;
2764
+ try {
2765
+ return JSON.parse(value);
2766
+ } catch {
2767
+ return fallback;
2768
+ }
2769
+ }
2770
+ function extractViewport(request) {
2771
+ const headers = request.headers;
2772
+ const viewportWidth = headers.get("sec-ch-viewport-width");
2773
+ const viewportHeight = headers.get("sec-ch-viewport-height");
2774
+ const dpr = headers.get("sec-ch-dpr");
2775
+ if (viewportWidth && viewportHeight) {
2776
+ return {
2777
+ width: parseInt(viewportWidth, 10),
2778
+ height: parseInt(viewportHeight, 10),
2779
+ devicePixelRatio: dpr ? parseFloat(dpr) : undefined
2780
+ };
2781
+ }
2782
+ const xViewport = headers.get("x-viewport");
2783
+ if (xViewport) {
2784
+ const [width, height, devicePixelRatio] = xViewport.split(",").map(Number);
2785
+ return { width: width || 1920, height: height || 1080, devicePixelRatio };
2786
+ }
2787
+ return { width: 1920, height: 1080 };
2788
+ }
2789
+ function extractConnection(request) {
2790
+ const headers = request.headers;
2791
+ const downlink = headers.get("downlink");
2792
+ const rtt = headers.get("rtt");
2793
+ const ect = headers.get("ect");
2794
+ if (ect) {
2795
+ switch (ect) {
2796
+ case "4g":
2797
+ return "fast";
2798
+ case "3g":
2799
+ return "3g";
2800
+ case "2g":
2801
+ return "2g";
2802
+ case "slow-2g":
2803
+ return "slow-2g";
2804
+ }
2805
+ }
2806
+ if (downlink) {
2807
+ const mbps = parseFloat(downlink);
2808
+ if (mbps >= 10)
2809
+ return "fast";
2810
+ if (mbps >= 2)
2811
+ return "4g";
2812
+ if (mbps >= 0.5)
2813
+ return "3g";
2814
+ if (mbps >= 0.1)
2815
+ return "2g";
2816
+ return "slow-2g";
2817
+ }
2818
+ if (rtt) {
2819
+ const ms = parseInt(rtt, 10);
2820
+ if (ms < 50)
2821
+ return "fast";
2822
+ if (ms < 100)
2823
+ return "4g";
2824
+ if (ms < 300)
2825
+ return "3g";
2826
+ if (ms < 700)
2827
+ return "2g";
2828
+ return "slow-2g";
2829
+ }
2830
+ return "4g";
2831
+ }
2832
+ function extractReducedMotion(request) {
2833
+ const prefersReducedMotion = request.headers.get("sec-ch-prefers-reduced-motion");
2834
+ return prefersReducedMotion === "reduce";
2835
+ }
2836
+ function extractTimeContext(request) {
2837
+ const headers = request.headers;
2838
+ const xTimezone = headers.get("x-timezone");
2839
+ const xLocalHour = headers.get("x-local-hour");
2840
+ const cfTimezone = request.cf?.timezone;
2841
+ const timezone = xTimezone || cfTimezone || "UTC";
2842
+ const localHour = xLocalHour ? parseInt(xLocalHour, 10) : new Date().getUTCHours();
2843
+ return { timezone, localHour };
2844
+ }
2845
+ function extractIdentity(cookies, request) {
2846
+ const userId = cookies["user_id"] || request.headers.get("x-user-id") || undefined;
2847
+ const tierCookie = cookies["user_tier"];
2848
+ const tierHeader = request.headers.get("x-user-tier");
2849
+ const tier = tierCookie || tierHeader || "free";
2850
+ return { userId, tier };
2851
+ }
2852
+ function extractNavigationHistory(cookies) {
2853
+ const recentPages = parseJSON(cookies["recent_pages"], []);
2854
+ const dwellTimesObj = parseJSON(cookies["dwell_times"], {});
2855
+ const clickPatterns = parseJSON(cookies["click_patterns"], []);
2856
+ return {
2857
+ recentPages,
2858
+ dwellTimes: new Map(Object.entries(dwellTimesObj)),
2859
+ clickPatterns
2860
+ };
2861
+ }
2862
+ function extractEmotionState(cookies, request) {
2863
+ const xEmotion = request.headers.get("x-emotion-state");
2864
+ if (xEmotion) {
2865
+ return parseJSON(xEmotion, undefined);
2866
+ }
2867
+ const emotionCookie = cookies["emotion_state"];
2868
+ if (emotionCookie) {
2869
+ return parseJSON(emotionCookie, undefined);
2870
+ }
2871
+ return;
2872
+ }
2873
+ function extractPreferences(cookies) {
2874
+ return parseJSON(cookies["user_preferences"], {});
2875
+ }
2876
+ function extractSessionInfo(cookies) {
2877
+ const sessionId = cookies["session_id"];
2878
+ const sessionStarted = cookies["session_started"];
2879
+ return {
2880
+ sessionId,
2881
+ isNewSession: !sessionId,
2882
+ sessionStartedAt: sessionStarted ? new Date(sessionStarted) : undefined
2883
+ };
2884
+ }
2885
+ async function extractUserContext(request, options = {}) {
2886
+ const cookies = parseCookies(request.headers.get("cookie"));
2887
+ const viewport = extractViewport(request);
2888
+ const connection = extractConnection(request);
2889
+ const reducedMotion = extractReducedMotion(request);
2890
+ const { timezone, localHour } = extractTimeContext(request);
2891
+ const { userId, tier: initialTier } = extractIdentity(cookies, request);
2892
+ const { recentPages, dwellTimes, clickPatterns } = extractNavigationHistory(cookies);
2893
+ const preferences = extractPreferences(cookies);
2894
+ const { sessionId, isNewSession, sessionStartedAt } = extractSessionInfo(cookies);
2895
+ let tier = initialTier;
2896
+ if (options.resolveUserTier && userId) {
2897
+ try {
2898
+ tier = await options.resolveUserTier(userId);
2899
+ } catch {}
2900
+ }
2901
+ let emotionState = extractEmotionState(cookies, request);
2902
+ if (!emotionState && options.detectEmotion) {
2903
+ try {
2904
+ emotionState = await options.detectEmotion(request);
2905
+ } catch {}
2906
+ }
2907
+ let context = {
2908
+ userId,
2909
+ tier,
2910
+ recentPages,
2911
+ dwellTimes,
2912
+ clickPatterns,
2913
+ emotionState,
2914
+ preferences,
2915
+ viewport,
2916
+ connection,
2917
+ reducedMotion,
2918
+ localHour,
2919
+ timezone,
2920
+ sessionId,
2921
+ isNewSession,
2922
+ sessionStartedAt
2923
+ };
2924
+ if (options.enrich) {
2925
+ context = await options.enrich(context, request);
2926
+ }
2927
+ return context;
2928
+ }
2929
+ function createContextMiddleware(options = {}) {
2930
+ return async (request) => {
2931
+ return extractUserContext(request, options);
2932
+ };
2933
+ }
2934
+ function setContextCookies(response, context, currentPath) {
2935
+ const headers = new Headers(response.headers);
2936
+ const recentPages = [...context.recentPages.slice(-9), currentPath];
2937
+ headers.append("Set-Cookie", `recent_pages=${encodeURIComponent(JSON.stringify(recentPages))}; Path=/; Max-Age=604800; SameSite=Lax`);
2938
+ if (context.isNewSession) {
2939
+ const sessionId = `sess_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
2940
+ headers.append("Set-Cookie", `session_id=${sessionId}; Path=/; Max-Age=86400; SameSite=Lax`);
2941
+ headers.append("Set-Cookie", `session_started=${new Date().toISOString()}; Path=/; Max-Age=86400; SameSite=Lax`);
2942
+ }
2943
+ return new Response(response.body, {
2944
+ status: response.status,
2945
+ statusText: response.statusText,
2946
+ headers
2947
+ });
2948
+ }
2949
+ function addSpeculationHeaders(response, prefetch, prerender) {
2950
+ const headers = new Headers(response.headers);
2951
+ if (prefetch.length > 0) {
2952
+ const linkHeader = prefetch.map((path) => `<${path}>; rel=prefetch`).join(", ");
2953
+ headers.append("Link", linkHeader);
2954
+ }
2955
+ if (prerender.length > 0) {
2956
+ headers.set("X-Prerender-Hints", prerender.join(","));
2957
+ }
2958
+ return new Response(response.body, {
2959
+ status: response.status,
2960
+ statusText: response.statusText,
2961
+ headers
2962
+ });
2963
+ }
2964
+ function serializeToESIState(context) {
2965
+ const tierFeatures = {
2966
+ free: {
2967
+ aiInference: true,
2968
+ emotionTracking: true,
2969
+ collaboration: false,
2970
+ advancedInsights: false,
2971
+ customThemes: false,
2972
+ voiceSynthesis: false,
2973
+ imageAnalysis: false
2974
+ },
2975
+ starter: {
2976
+ aiInference: true,
2977
+ emotionTracking: true,
2978
+ collaboration: false,
2979
+ advancedInsights: true,
2980
+ customThemes: true,
2981
+ voiceSynthesis: false,
2982
+ imageAnalysis: false
2983
+ },
2984
+ pro: {
2985
+ aiInference: true,
2986
+ emotionTracking: true,
2987
+ collaboration: true,
2988
+ advancedInsights: true,
2989
+ customThemes: true,
2990
+ voiceSynthesis: true,
2991
+ imageAnalysis: true
2992
+ },
2993
+ enterprise: {
2994
+ aiInference: true,
2995
+ emotionTracking: true,
2996
+ collaboration: true,
2997
+ advancedInsights: true,
2998
+ customThemes: true,
2999
+ voiceSynthesis: true,
3000
+ imageAnalysis: true
3001
+ }
3002
+ };
3003
+ return {
3004
+ userTier: context.tier,
3005
+ emotionState: context.emotionState ? {
3006
+ primary: context.emotionState.primary,
3007
+ valence: context.emotionState.valence,
3008
+ arousal: context.emotionState.arousal,
3009
+ confidence: context.emotionState.confidence
3010
+ } : undefined,
3011
+ preferences: {
3012
+ theme: context.preferences.theme,
3013
+ reducedMotion: context.reducedMotion,
3014
+ language: context.preferences.language
3015
+ },
3016
+ sessionId: context.sessionId,
3017
+ localHour: context.localHour,
3018
+ timezone: context.timezone,
3019
+ features: tierFeatures[context.tier],
3020
+ userId: context.userId,
3021
+ isNewSession: context.isNewSession,
3022
+ recentPages: context.recentPages.slice(-10),
3023
+ viewport: {
3024
+ width: context.viewport.width,
3025
+ height: context.viewport.height
3026
+ },
3027
+ connection: context.connection
3028
+ };
3029
+ }
3030
+ function generateESIStateScript(esiState) {
3031
+ const stateJson = JSON.stringify(esiState);
3032
+ return `<script>window.__AEON_ESI_STATE__=${stateJson};</script>`;
3033
+ }
3034
+ function generateESIStateScriptFromContext(context) {
3035
+ const esiState = serializeToESIState(context);
3036
+ return generateESIStateScript(esiState);
3037
+ }
3038
+ // src/router/speculation.ts
3039
+ function supportsSpeculationRules() {
3040
+ if (typeof document === "undefined")
3041
+ return false;
3042
+ return "supports" in HTMLScriptElement && HTMLScriptElement.supports?.("speculationrules");
3043
+ }
3044
+ function supportsLinkPrefetch() {
3045
+ if (typeof document === "undefined")
3046
+ return false;
3047
+ const link = document.createElement("link");
3048
+ return link.relList?.supports?.("prefetch") ?? false;
3049
+ }
3050
+ function addSpeculationRules(prefetch, prerender) {
3051
+ if (!supportsSpeculationRules())
3052
+ return null;
3053
+ const rules = {};
3054
+ if (prefetch.length > 0) {
3055
+ rules.prefetch = [{ urls: prefetch }];
3056
+ }
3057
+ if (prerender.length > 0) {
3058
+ rules.prerender = [{ urls: prerender }];
3059
+ }
3060
+ if (Object.keys(rules).length === 0)
3061
+ return null;
3062
+ const script = document.createElement("script");
3063
+ script.type = "speculationrules";
3064
+ script.textContent = JSON.stringify(rules);
3065
+ document.head.appendChild(script);
3066
+ return script;
3067
+ }
3068
+ function removeSpeculationRules(script) {
3069
+ script.remove();
3070
+ }
3071
+ function linkPrefetch(path) {
3072
+ if (!supportsLinkPrefetch())
3073
+ return null;
3074
+ const existing = document.querySelector(`link[rel="prefetch"][href="${path}"]`);
3075
+ if (existing)
3076
+ return existing;
3077
+ const link = document.createElement("link");
3078
+ link.rel = "prefetch";
3079
+ link.href = path;
3080
+ document.head.appendChild(link);
3081
+ return link;
3082
+ }
3083
+ function removePrefetch(link) {
3084
+ link.remove();
3085
+ }
3086
+
3087
+ class SpeculationManager {
3088
+ options;
3089
+ state;
3090
+ observers = new Map;
3091
+ hoverTimers = new Map;
3092
+ speculationScript = null;
3093
+ prefetchLinks = new Map;
3094
+ constructor(options = {}) {
3095
+ this.options = {
3096
+ maxPrefetch: options.maxPrefetch ?? 5,
3097
+ maxPrerender: options.maxPrerender ?? 1,
3098
+ hoverDelay: options.hoverDelay ?? 100,
3099
+ prefetchOnVisible: options.prefetchOnVisible ?? true,
3100
+ visibilityThreshold: options.visibilityThreshold ?? 0.1,
3101
+ cacheDuration: options.cacheDuration ?? 5 * 60 * 1000,
3102
+ onSpeculate: options.onSpeculate ?? (() => {})
3103
+ };
3104
+ this.state = {
3105
+ prefetched: new Set,
3106
+ prerendered: new Set,
3107
+ pending: new Set
3108
+ };
3109
+ }
3110
+ initFromHints(prefetch = [], prerender = []) {
3111
+ const newPrefetch = prefetch.filter((p) => !this.state.prefetched.has(p) && !this.state.prerendered.has(p)).slice(0, this.options.maxPrefetch);
3112
+ const newPrerender = prerender.filter((p) => !this.state.prerendered.has(p)).slice(0, this.options.maxPrerender);
3113
+ if (supportsSpeculationRules()) {
3114
+ this.speculationScript = addSpeculationRules(newPrefetch, newPrerender);
3115
+ newPrefetch.forEach((p) => {
3116
+ this.state.prefetched.add(p);
3117
+ this.options.onSpeculate(p, "prefetch");
3118
+ });
3119
+ newPrerender.forEach((p) => {
3120
+ this.state.prerendered.add(p);
3121
+ this.options.onSpeculate(p, "prerender");
3122
+ });
3123
+ } else {
3124
+ newPrefetch.forEach((path) => {
3125
+ const link = linkPrefetch(path);
3126
+ if (link) {
3127
+ this.prefetchLinks.set(path, link);
3128
+ this.state.prefetched.add(path);
3129
+ this.options.onSpeculate(path, "prefetch");
3130
+ }
3131
+ });
3132
+ }
3133
+ }
3134
+ prefetch(path) {
3135
+ if (this.state.prefetched.has(path) || this.state.prerendered.has(path)) {
3136
+ return false;
3137
+ }
3138
+ if (this.state.prefetched.size >= this.options.maxPrefetch) {
3139
+ return false;
3140
+ }
3141
+ if (supportsSpeculationRules()) {
3142
+ const allPrefetch = [...this.state.prefetched, path];
3143
+ const allPrerender = [...this.state.prerendered];
3144
+ if (this.speculationScript) {
3145
+ removeSpeculationRules(this.speculationScript);
3146
+ }
3147
+ this.speculationScript = addSpeculationRules(allPrefetch, allPrerender);
3148
+ } else {
3149
+ const link = linkPrefetch(path);
3150
+ if (link) {
3151
+ this.prefetchLinks.set(path, link);
3152
+ }
3153
+ }
3154
+ this.state.prefetched.add(path);
3155
+ this.options.onSpeculate(path, "prefetch");
3156
+ return true;
3157
+ }
3158
+ watchHover(element) {
3159
+ const path = new URL(element.href, window.location.href).pathname;
3160
+ const handleMouseEnter = () => {
3161
+ if (this.state.prefetched.has(path) || this.state.pending.has(path)) {
3162
+ return;
3163
+ }
3164
+ this.state.pending.add(path);
3165
+ const timer = setTimeout(() => {
3166
+ this.prefetch(path);
3167
+ this.state.pending.delete(path);
3168
+ }, this.options.hoverDelay);
3169
+ this.hoverTimers.set(element, timer);
3170
+ };
3171
+ const handleMouseLeave = () => {
3172
+ const timer = this.hoverTimers.get(element);
3173
+ if (timer) {
3174
+ clearTimeout(timer);
3175
+ this.hoverTimers.delete(element);
3176
+ }
3177
+ this.state.pending.delete(path);
3178
+ };
3179
+ element.addEventListener("mouseenter", handleMouseEnter);
3180
+ element.addEventListener("mouseleave", handleMouseLeave);
3181
+ return () => {
3182
+ element.removeEventListener("mouseenter", handleMouseEnter);
3183
+ element.removeEventListener("mouseleave", handleMouseLeave);
3184
+ handleMouseLeave();
3185
+ };
3186
+ }
3187
+ watchVisible(element) {
3188
+ if (!this.options.prefetchOnVisible) {
3189
+ return () => {};
3190
+ }
3191
+ const path = new URL(element.href, window.location.href).pathname;
3192
+ const observer = new IntersectionObserver((entries) => {
3193
+ entries.forEach((entry) => {
3194
+ if (entry.isIntersecting) {
3195
+ this.prefetch(path);
3196
+ observer.disconnect();
3197
+ this.observers.delete(element);
3198
+ }
3199
+ });
3200
+ }, { threshold: this.options.visibilityThreshold });
3201
+ observer.observe(element);
3202
+ this.observers.set(element, observer);
3203
+ return () => {
3204
+ observer.disconnect();
3205
+ this.observers.delete(element);
3206
+ };
3207
+ }
3208
+ watchAllLinks() {
3209
+ const links = document.querySelectorAll('a[href^="/"]');
3210
+ const cleanups = [];
3211
+ links.forEach((link) => {
3212
+ if (link instanceof HTMLAnchorElement) {
3213
+ cleanups.push(this.watchHover(link));
3214
+ cleanups.push(this.watchVisible(link));
3215
+ }
3216
+ });
3217
+ return () => {
3218
+ cleanups.forEach((cleanup) => cleanup());
3219
+ };
3220
+ }
3221
+ clear() {
3222
+ if (this.speculationScript) {
3223
+ removeSpeculationRules(this.speculationScript);
3224
+ this.speculationScript = null;
3225
+ }
3226
+ this.prefetchLinks.forEach((link) => removePrefetch(link));
3227
+ this.prefetchLinks.clear();
3228
+ this.observers.forEach((observer) => observer.disconnect());
3229
+ this.observers.clear();
3230
+ this.hoverTimers.forEach((timer) => clearTimeout(timer));
3231
+ this.hoverTimers.clear();
3232
+ this.state.prefetched.clear();
3233
+ this.state.prerendered.clear();
3234
+ this.state.pending.clear();
3235
+ }
3236
+ getState() {
3237
+ return {
3238
+ prefetched: new Set(this.state.prefetched),
3239
+ prerendered: new Set(this.state.prerendered),
3240
+ pending: new Set(this.state.pending)
3241
+ };
3242
+ }
3243
+ }
3244
+ function createSpeculationHook(useState3, useEffect3, useRef) {
3245
+ return function useSpeculation(options = {}) {
3246
+ const managerRef = useRef(null);
3247
+ const [state, setState] = useState3({
3248
+ prefetched: new Set,
3249
+ prerendered: new Set,
3250
+ pending: new Set
3251
+ });
3252
+ useEffect3(() => {
3253
+ managerRef.current = new SpeculationManager({
3254
+ ...options,
3255
+ onSpeculate: (path, type) => {
3256
+ options.onSpeculate?.(path, type);
3257
+ setState(managerRef.current.getState());
3258
+ }
3259
+ });
3260
+ const cleanup = managerRef.current.watchAllLinks();
3261
+ return () => {
3262
+ cleanup();
3263
+ managerRef.current?.clear();
3264
+ };
3265
+ }, []);
3266
+ return {
3267
+ state,
3268
+ prefetch: (path) => managerRef.current?.prefetch(path),
3269
+ initFromHints: (prefetch, prerender) => managerRef.current?.initFromHints(prefetch, prerender),
3270
+ clear: () => managerRef.current?.clear()
3271
+ };
3272
+ };
3273
+ }
3274
+ function autoInitSpeculation() {
3275
+ if (typeof window === "undefined")
3276
+ return null;
3277
+ const hints = window.__AEON_SPECULATION__;
3278
+ const manager = new SpeculationManager;
3279
+ if (hints) {
3280
+ manager.initFromHints(hints.prefetch || [], hints.prerender || []);
3281
+ }
3282
+ manager.watchAllLinks();
3283
+ return manager;
3284
+ }
3285
+ export { DEFAULT_ROUTER_CONFIG, DEFAULT_ESI_CONFIG, esiContext, esiCyrano, esiHalo, evaluateTrigger, createExhaustEntry, CYRANO_TOOL_SUGGESTIONS, getToolSuggestions, EdgeWorkersESIProcessor, esiInfer, esiEmbed, esiEmotion, esiVision, esiWithContext, 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, 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 };