File size: 446,587 Bytes
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0740f8b
 
 
 
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ddb7cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b87832
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df8cbca
 
a90cf72
 
4c4337e
 
8b87832
4c4337e
 
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ddb7cf
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0740f8b
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0740f8b
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0740f8b
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ddb7cf
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df8cbca
 
 
a90cf72
df8cbca
 
 
 
a90cf72
 
df8cbca
 
 
 
 
a90cf72
c3d7ce7
df8cbca
 
 
 
 
 
 
c3d7ce7
df8cbca
 
 
b9f04cb
df8cbca
 
 
 
 
 
 
 
 
 
 
a90cf72
df8cbca
 
b9f04cb
df8cbca
b9f04cb
 
df8cbca
 
 
 
b9f04cb
df8cbca
 
 
 
b9f04cb
 
df8cbca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9f04cb
df8cbca
 
 
 
b9f04cb
df8cbca
b9f04cb
df8cbca
 
b9f04cb
df8cbca
 
b9f04cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a90cf72
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f273c93
 
 
 
 
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376142b
099a95e
 
376142b
 
 
 
 
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
376142b
 
 
 
 
 
 
 
 
 
099a95e
 
 
376142b
099a95e
 
 
 
376142b
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0740f8b
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0740f8b
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0740f8b
099a95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
/* ── Trusted Types 호환 (YouTube 등) ── */
(function(){
  if(window.trustedTypes && trustedTypes.createPolicy){
    try{
      if(!trustedTypes.defaultPolicy){
        trustedTypes.createPolicy('default',{
          createHTML:function(s){return s;},
          createScriptURL:function(s){return s;},
          createScript:function(s){return s;}
        });
      }
    }catch(e){}
  }
})();
var $t=Object.defineProperty;var xt=L=>{throw TypeError(L)};var qt=(L,M,W)=>M in L?$t(L,M,{enumerable:!0,configurable:!0,writable:!0,value:W}):L[M]=W;var a=(L,M)=>$t(L,"name",{value:M,configurable:!0});var oe=(L,M,W)=>qt(L,typeof M!="symbol"?M+"":M,W),mt=(L,M,W)=>M.has(L)||xt("Cannot "+W);var p=(L,M,W)=>(mt(L,M,"read from private field"),W?W.call(L):M.get(L)),Z=(L,M,W)=>M.has(L)?xt("Cannot add the same private member more than once"):M instanceof WeakSet?M.add(L):M.set(L,W),S=(L,M,W,De)=>(mt(L,M,"write to private field"),De?De.call(L,W):M.set(L,W),W),b=(L,M,W)=>(mt(L,M,"access private method"),W);(function(){"use strict";var Ue,Oe,se,Ee,X,R,St,Pe,Me,_t,Tt,It,zt,At,Pt,st,ne,je,ie,ye,Ce,be,Re,we,B,Ge,$e,j,xe,ve,Ze,Q,Be,He,Je,Ye,qe,_,Ot,Ct,Rt,Zt,yt,Nt,Lt,Mt,tt,bt,Ft,Dt,Ut,wt,ot,it,jt,Bt,Wt,Vt,Fe,vt,kt,Gt,Ht,Jt,Y,ae,ce,Se,Te,Ne,Yt,Et;var __vite_style__=document.createElement("style");__vite_style__.textContent=`._wrapper_gtdpc_1{position:fixed;bottom:100px;left:50%;transform:translate(-50%) translateY(20px);opacity:0;z-index:2147483642;box-sizing:border-box;overflow:visible;--width: 360px;--height: 40px;--border-radius: 12px;--side-space: 12px;--history-width: calc(var(--width) - var(--side-space) * 2);--color-1: rgb(57, 182, 255);--color-2: rgb(189, 69, 251);--color-3: rgb(255, 87, 51);--color-4: rgb(255, 214, 0);width:var(--width);height:var(--height);transition:all .3s ease-in-out}._wrapper_gtdpc_1 *{box-sizing:border-box}@media(max-width:480px){._wrapper_gtdpc_1{width:calc(100vw - 40px);--width: calc(100vw - 40px) }}._wrapper_gtdpc_1 ._background_gtdpc_39{position:absolute;inset:-2px -8px;border-radius:calc(var(--border-radius) + 4px);filter:blur(16px);overflow:hidden}._wrapper_gtdpc_1 ._background_gtdpc_39:before{content:"";z-index:-1;pointer-events:none;position:absolute;width:100%;height:100%;left:0;top:0;background-image:linear-gradient(to bottom left,var(--color-1),var(--color-2),var(--color-1));animation:_mask-running_gtdpc_1 2s linear infinite}._wrapper_gtdpc_1 ._background_gtdpc_39:after{content:"";z-index:-1;pointer-events:none;position:absolute;width:100%;height:100%;left:0;top:0;background-image:linear-gradient(to bottom left,var(--color-2),var(--color-1),var(--color-2));animation:_mask-running_gtdpc_1 2s linear infinite;animation-delay:1s}@keyframes _mask-running_gtdpc_1{0%{transform:translate(-100%)}to{transform:translate(100%)}}._header_gtdpc_99{display:flex;align-items:center;justify-content:space-between;padding:8px 12px;-webkit-user-select:none;user-select:none;position:absolute;inset:0;cursor:pointer;flex-shrink:0;background:#00000080;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);border-radius:var(--border-radius);background-clip:padding-box;box-shadow:0 0 0 2px #fff6,0 0 5px 1px #ffffff4d}._header_gtdpc_99 ._statusSection_gtdpc_121{display:flex;align-items:center;gap:8px;flex:1;min-height:24px}._header_gtdpc_99 ._statusSection_gtdpc_121 ._indicator_gtdpc_128{width:6px;height:6px;border-radius:50%;background:#ffffff80;flex-shrink:0;animation:none}._header_gtdpc_99 ._statusSection_gtdpc_121 ._indicator_gtdpc_128._thinking_gtdpc_137{background:#39b6ff;animation:_pulse_gtdpc_1 .8s ease-in-out infinite}._header_gtdpc_99 ._statusSection_gtdpc_121 ._indicator_gtdpc_128._tool_executing_gtdpc_142{background:#bd45fb;animation:_pulse_gtdpc_1 .6s ease-in-out infinite}._header_gtdpc_99 ._statusSection_gtdpc_121 ._indicator_gtdpc_128._retry_gtdpc_147{background:#ffd600;animation:_retryPulse_gtdpc_1 1s ease-in-out infinite}._header_gtdpc_99 ._statusSection_gtdpc_121 ._indicator_gtdpc_128._completed_gtdpc_153,._header_gtdpc_99 ._statusSection_gtdpc_121 ._indicator_gtdpc_128._input_gtdpc_154,._header_gtdpc_99 ._statusSection_gtdpc_121 ._indicator_gtdpc_128._output_gtdpc_155{background:#22c55e;animation:none}._header_gtdpc_99 ._statusSection_gtdpc_121 ._indicator_gtdpc_128._error_gtdpc_160{background:#ef4444;animation:none}._header_gtdpc_99 ._statusSection_gtdpc_121 ._statusText_gtdpc_166{color:#fff;font-size:12px;line-height:1;font-weight:500;transition:all .3s ease-in-out;position:relative;overflow:hidden;display:flex;align-items:center;min-height:24px}._header_gtdpc_99 ._statusSection_gtdpc_121 ._statusText_gtdpc_166._fadeOut_gtdpc_178{animation:_statusTextFadeOut_gtdpc_1 .3s ease forwards}._header_gtdpc_99 ._statusSection_gtdpc_121 ._statusText_gtdpc_166._fadeIn_gtdpc_182{animation:_statusTextFadeIn_gtdpc_1 .3s ease forwards}._header_gtdpc_99 ._controls_gtdpc_188{display:flex;align-items:center;gap:4px}._header_gtdpc_99 ._controls_gtdpc_188 ._controlButton_gtdpc_193{width:24px;height:24px;border:none;border-radius:4px;background:#ffffff1a;color:#fff;cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:12px;line-height:1}._header_gtdpc_99 ._controls_gtdpc_188 ._controlButton_gtdpc_193:hover{background:#fff3}._header_gtdpc_99 ._controls_gtdpc_188 ._stopButton_gtdpc_212{background:#ef444433;color:#ff2929;font-weight:600}._header_gtdpc_99 ._controls_gtdpc_188 ._stopButton_gtdpc_212:hover{background:#ef44444d}@keyframes _statusTextFadeIn_gtdpc_1{0%{opacity:0;transform:translateY(5px)}to{opacity:1;transform:translateY(0)}}@keyframes _statusTextFadeOut_gtdpc_1{0%{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-5px)}}._historySectionWrapper_gtdpc_246{position:absolute;width:var(--history-width);bottom:var(--height);left:var(--side-space);z-index:-2;padding-top:0;visibility:collapse;overflow:hidden;transition:all .2s;background:#02001480;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);text-shadow:0 0 1px rgba(0,0,0,.2);border-top-left-radius:calc(var(--border-radius) + 4px);border-top-right-radius:calc(var(--border-radius) + 4px);border:2px solid rgba(255,255,255,.4);box-shadow:0 4px 16px #0009}._expanded_gtdpc_278 ._historySectionWrapper_gtdpc_246{padding-top:8px;visibility:visible}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246{position:relative;overflow-y:auto;overscroll-behavior:contain;scrollbar-width:none;max-height:0;padding-inline:8px;transition:max-height .2s}._expanded_gtdpc_278 :is(._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246){max-height:400px}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297{padding:8px 10px;margin-bottom:6px;background:linear-gradient(135deg,#ffffff14,#ffffff08);border-radius:8px;border-left:2px solid rgba(57,182,255,.5);font-size:12px;color:#fff;line-height:1.3;position:relative;overflow:hidden;box-shadow:inset 0 1px #ffffff1a,0 1px 3px #0000001a}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297:before{content:"";position:absolute;top:0;left:0;right:0;height:1px;background:linear-gradient(90deg,transparent,rgba(255,255,255,.2),transparent)}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297:hover{background:linear-gradient(135deg,#ffffff1f,#ffffff0f);box-shadow:inset 0 1px #ffffff26,0 2px 4px #00000026}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297:last-child{margin-bottom:10px}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297._completed_gtdpc_153,._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297._input_gtdpc_154,._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297._output_gtdpc_155{border-left-color:#22c55e;background:linear-gradient(135deg,#22c55e1a,#22c55e0d)}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297._error_gtdpc_160{border-left-color:#ef4444;background:linear-gradient(135deg,#ef44441a,#ef44440d)}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297._retry_gtdpc_147{border-left-color:#ffd600;background:linear-gradient(135deg,#ffd6001a,#ffd6000d)}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297._observation_gtdpc_355{border-left-color:#9333ea;background:linear-gradient(135deg,#9333ea1a,#9333ea0d)}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297._question_gtdpc_360{border-left-color:#ff9f43;background:linear-gradient(135deg,#ff9f4326,#ff9f4314)}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297._doneSuccess_gtdpc_366{background:linear-gradient(135deg,#22c55e40,#22c55e26,#22c55e14);border:none;border-left:4px solid rgb(34,197,94);box-shadow:0 4px 12px #22c55e4d,inset 0 1px #fff3,0 0 20px #22c55e1a;font-weight:600;color:#dcfce7;padding:10px 12px;margin-bottom:8px;border-radius:8px;position:relative;overflow:hidden}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297._doneSuccess_gtdpc_366:before{background:linear-gradient(90deg,transparent,rgba(34,197,94,.4),transparent)}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297._doneSuccess_gtdpc_366:after{content:"";position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg,transparent,rgba(255,255,255,.1),transparent);animation:_shimmer_gtdpc_1 2s ease-in-out infinite}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297._doneSuccess_gtdpc_366 ._historyContent_gtdpc_402 ._statusIcon_gtdpc_403{font-size:16px;animation:_celebrate_gtdpc_1 .8s ease-in-out;filter:drop-shadow(0 2px 4px rgba(34,197,94,.5))}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297._doneError_gtdpc_412{background:linear-gradient(135deg,#ef444440,#ef444426,#ef444414);border:none;border-left:4px solid rgb(239,68,68);box-shadow:0 4px 12px #ef44444d,inset 0 1px #fff3,0 0 20px #ef44441a;font-weight:600;color:#fee2e2;padding:10px 12px;margin-bottom:8px;border-radius:8px;position:relative;overflow:hidden}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297._doneError_gtdpc_412:before{background:linear-gradient(90deg,transparent,rgba(239,68,68,.4),transparent)}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297._doneError_gtdpc_412 ._historyContent_gtdpc_402 ._statusIcon_gtdpc_403{font-size:16px;filter:drop-shadow(0 2px 4px rgba(239,68,68,.5))}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297 ._historyContent_gtdpc_402{display:flex;align-items:flex-start;gap:8px;word-break:break-all;white-space:pre-wrap}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297 ._historyContent_gtdpc_402 ._statusIcon_gtdpc_403{font-size:12px;flex-shrink:0;line-height:1;transition:all .3s ease}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297 ._historyContent_gtdpc_402 ._reflectionLines_gtdpc_462{display:flex;flex-direction:column;gap:4px}._historySectionWrapper_gtdpc_246 ._historySection_gtdpc_246 ._historyItem_gtdpc_297 ._historyMeta_gtdpc_469{font-size:10px;color:#fff9;margin-top:8px;line-height:1}@keyframes _pulse_gtdpc_1{0%,to{opacity:1;transform:scale(1)}50%{opacity:.4;transform:scale(1.3)}}@keyframes _retryPulse_gtdpc_1{0%,to{opacity:1;transform:scale(1) rotate(0)}25%{opacity:.6;transform:scale(1.2) rotate(90deg)}50%{opacity:.8;transform:scale(1.1) rotate(180deg)}75%{opacity:.6;transform:scale(1.2) rotate(270deg)}}@keyframes _celebrate_gtdpc_1{0%,to{transform:scale(1)}25%{transform:scale(1.2) rotate(-5deg)}75%{transform:scale(1.2) rotate(5deg)}}@keyframes _shimmer_gtdpc_1{0%{left:-100%}to{left:100%}}._inputSectionWrapper_gtdpc_539{position:absolute;width:var(--history-width);top:var(--height);left:var(--side-space);z-index:-1;visibility:visible;overflow:hidden;height:48px;transition:all .2s;background:#bababa33;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);border-bottom-left-radius:calc(var(--border-radius) + 4px);border-bottom-right-radius:calc(var(--border-radius) + 4px);border:2px solid rgba(255,255,255,.3);box-shadow:0 1px 16px #0006}._inputSectionWrapper_gtdpc_539._hidden_gtdpc_562{visibility:collapse;height:0}._inputSectionWrapper_gtdpc_539 ._inputSection_gtdpc_539{display:flex;align-items:center;gap:4px;padding:8px}._inputSectionWrapper_gtdpc_539 ._inputSection_gtdpc_539 ._taskInput_gtdpc_573{flex:1;background:#fff6;border:1px solid rgba(255,255,255,.3);border-radius:10px;padding-inline:10px;color:#141414;font-size:12px;height:28px;line-height:1;outline:none;transition:all .2s ease}._inputSectionWrapper_gtdpc_539 ._inputSection_gtdpc_539 ._taskInput_gtdpc_573::placeholder{color:#353535}._inputSectionWrapper_gtdpc_539 ._inputSection_gtdpc_539 ._taskInput_gtdpc_573:focus{background:#fffc;border-color:#39b6ff99;box-shadow:0 0 0 2px #39b6ff33}._wrapper_gf8tz_1{position:fixed;inset:0;z-index:2147483641;cursor:wait;overflow:hidden;display:none}._cursor_1dgwb_2{position:absolute;width:var(--cursor-size, 75px);height:var(--cursor-size, 75px);pointer-events:none;z-index:10000}._cursorBorder_1dgwb_10{position:absolute;width:100%;height:100%;background:linear-gradient(45deg,#39b6ff,#bd45fb);-webkit-mask-image:url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20100%20100'%20fill='none'%3e%3cg%3e%3cpath%20d='M%2015%2042%20L%2015%2036.99%20Q%2015%2031.99%2023.7%2031.99%20L%2028.05%2031.99%20Q%2032.41%2031.99%2032.41%2021.99%20L%2032.41%2017%20Q%2032.41%2012%2041.09%2016.95%20L%2076.31%2037.05%20Q%2085%2042%2076.31%2046.95%20L%2041.09%2067.05%20Q%2032.41%2072%2032.41%2062.01%20L%2032.41%2057.01%20Q%2032.41%2052.01%2023.7%2052.01%20L%2019.35%2052.01%20Q%2015%2052.01%2015%2047.01%20Z'%20fill='none'%20stroke='%23000000'%20stroke-width='6'%20stroke-miterlimit='10'%20style='stroke:%20light-dark(rgb(0,%200,%200),%20rgb(255,%20255,%20255));'/%3e%3c/g%3e%3c/svg%3e");mask-image:url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20100%20100'%20fill='none'%3e%3cg%3e%3cpath%20d='M%2015%2042%20L%2015%2036.99%20Q%2015%2031.99%2023.7%2031.99%20L%2028.05%2031.99%20Q%2032.41%2031.99%2032.41%2021.99%20L%2032.41%2017%20Q%2032.41%2012%2041.09%2016.95%20L%2076.31%2037.05%20Q%2085%2042%2076.31%2046.95%20L%2041.09%2067.05%20Q%2032.41%2072%2032.41%2062.01%20L%2032.41%2057.01%20Q%2032.41%2052.01%2023.7%2052.01%20L%2019.35%2052.01%20Q%2015%2052.01%2015%2047.01%20Z'%20fill='none'%20stroke='%23000000'%20stroke-width='6'%20stroke-miterlimit='10'%20style='stroke:%20light-dark(rgb(0,%200,%200),%20rgb(255,%20255,%20255));'/%3e%3c/g%3e%3c/svg%3e");-webkit-mask-size:100% 100%;mask-size:100% 100%;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;transform-origin:center;transform:rotate(-135deg) scale(1.2);margin-left:-10px;margin-top:-18px}._cursorFilling_1dgwb_25{position:absolute;width:100%;height:100%;background:url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20100%20100'%3e%3cdefs%3e%3c/defs%3e%3cg%20xmlns='http://www.w3.org/2000/svg'%20style='filter:%20drop-shadow(light-dark(rgba(0,%200,%200,%200.4),%20rgba(237,%20237,%20237,%200.4))%203px%204px%204px);'%3e%3cpath%20d='M%2015%2042%20L%2015%2036.99%20Q%2015%2031.99%2023.7%2031.99%20L%2028.05%2031.99%20Q%2032.41%2031.99%2032.41%2021.99%20L%2032.41%2017%20Q%2032.41%2012%2041.09%2016.95%20L%2076.31%2037.05%20Q%2085%2042%2076.31%2046.95%20L%2041.09%2067.05%20Q%2032.41%2072%2032.41%2062.01%20L%2032.41%2057.01%20Q%2032.41%2052.01%2023.7%2052.01%20L%2019.35%2052.01%20Q%2015%2052.01%2015%2047.01%20Z'%20fill='%23ffffff'%20stroke='none'%20style='fill:%20%23ffffff;'/%3e%3c/g%3e%3c/svg%3e");background-size:100% 100%;background-repeat:no-repeat;transform-origin:center;transform:rotate(-135deg) scale(1.2);margin-left:-10px;margin-top:-18px}._cursorRipple_1dgwb_39{position:absolute;width:100%;height:100%;pointer-events:none;margin-left:-50%;margin-top:-50%}._cursorRipple_1dgwb_39:after{content:"";opacity:0;position:absolute;inset:0;border:4px solid rgba(57,182,255,1);border-radius:50%}._cursor_1dgwb_2._clicking_1dgwb_57 ._cursorRipple_1dgwb_39:after{animation:_cursor-ripple_1dgwb_1 .3s ease-out forwards}@keyframes _cursor-ripple_1dgwb_1{0%{transform:scale(0);opacity:1}to{transform:scale(2);opacity:0}}
/*$vite$:1*/`,document.head.appendChild(__vite_style__);function $constructor(e,t,o){function n(l,d){if(l._zod||Object.defineProperty(l,"_zod",{value:{def:d,constr:s,traits:new Set},enumerable:!1}),l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,d);const h=s.prototype,f=Object.keys(h);for(let g=0;g<f.length;g++){const m=f[g];m in l||(l[m]=h[m].bind(l))}}a(n,"init");const r=o?.Parent??Object,c=class c extends r{};a(c,"Definition");let i=c;Object.defineProperty(i,"name",{value:e});function s(l){var d;const h=o?.Parent?new i:this;n(h,l),(d=h._zod).deferred??(d.deferred=[]);for(const f of h._zod.deferred)f();return h}return a(s,"_"),Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a(l=>o?.Parent&&l instanceof o.Parent?!0:l?._zod?.traits?.has(e),"value")}),Object.defineProperty(s,"name",{value:e}),s}a($constructor,"$constructor");const L=class L extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};a(L,"$ZodAsyncError");let $ZodAsyncError=L;const M=class M extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};a(M,"$ZodEncodeError");let $ZodEncodeError=M;const globalConfig={};function config(e){return globalConfig}a(config,"config");function getEnumValues(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,r])=>t.indexOf(+n)===-1).map(([n,r])=>r)}a(getEnumValues,"getEnumValues");function jsonStringifyReplacer(e,t){return typeof t=="bigint"?t.toString():t}a(jsonStringifyReplacer,"jsonStringifyReplacer");function cached(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}a(cached,"cached");function nullish(e){return e==null}a(nullish,"nullish");function cleanRegex(e){const t=e.startsWith("^")?1:0,o=e.endsWith("$")?e.length-1:e.length;return e.slice(t,o)}a(cleanRegex,"cleanRegex");function floatSafeRemainder(e,t){const o=(e.toString().split(".")[1]||"").length,n=t.toString();let r=(n.split(".")[1]||"").length;if(r===0&&/\d?e-\d?/.test(n)){const l=n.match(/\d?e-(\d?)/);l?.[1]&&(r=Number.parseInt(l[1]))}const i=o>r?o:r,s=Number.parseInt(e.toFixed(i).replace(".","")),c=Number.parseInt(t.toFixed(i).replace(".",""));return s%c/10**i}a(floatSafeRemainder,"floatSafeRemainder");const EVALUATING=Symbol("evaluating");function defineLazy(e,t,o){let n;Object.defineProperty(e,t,{get(){if(n!==EVALUATING)return n===void 0&&(n=EVALUATING,n=o()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}a(defineLazy,"defineLazy");function assignProp(e,t,o){Object.defineProperty(e,t,{value:o,writable:!0,enumerable:!0,configurable:!0})}a(assignProp,"assignProp");function mergeDefs(...e){const t={};for(const o of e){const n=Object.getOwnPropertyDescriptors(o);Object.assign(t,n)}return Object.defineProperties({},t)}a(mergeDefs,"mergeDefs");function esc(e){return JSON.stringify(e)}a(esc,"esc");function slugify(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}a(slugify,"slugify");const captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function isObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(isObject,"isObject");const allowsEval=cached(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function isPlainObject(e){if(isObject(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const o=t.prototype;return!(isObject(o)===!1||Object.prototype.hasOwnProperty.call(o,"isPrototypeOf")===!1)}a(isPlainObject,"isPlainObject");function shallowClone(e){return isPlainObject(e)?{...e}:Array.isArray(e)?[...e]:e}a(shallowClone,"shallowClone");const propertyKeyTypes=new Set(["string","number","symbol"]);function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(escapeRegex,"escapeRegex");function clone(e,t,o){const n=new e._zod.constr(t??e._zod.def);return(!t||o?.parent)&&(n._zod.parent=e),n}a(clone,"clone");function normalizeParams(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:a(()=>t,"error")};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:a(()=>t.error,"error")}:t}a(normalizeParams,"normalizeParams");function optionalKeys(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}a(optionalKeys,"optionalKeys");const NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function pick(e,t){const o=e._zod.def,n=o.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=mergeDefs(e._zod.def,{get shape(){const s={};for(const c in t){if(!(c in o.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(s[c]=o.shape[c])}return assignProp(this,"shape",s),s},checks:[]});return clone(e,i)}a(pick,"pick");function omit(e,t){const o=e._zod.def,n=o.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=mergeDefs(e._zod.def,{get shape(){const s={...e._zod.def.shape};for(const c in t){if(!(c in o.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete s[c]}return assignProp(this,"shape",s),s},checks:[]});return clone(e,i)}a(omit,"omit");function extend(e,t){if(!isPlainObject(t))throw new Error("Invalid input to extend: expected a plain object");const o=e._zod.def.checks;if(o&&o.length>0){const i=e._zod.def.shape;for(const s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=mergeDefs(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return assignProp(this,"shape",i),i}});return clone(e,r)}a(extend,"extend");function safeExtend(e,t){if(!isPlainObject(t))throw new Error("Invalid input to safeExtend: expected a plain object");const o=mergeDefs(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return assignProp(this,"shape",n),n}});return clone(e,o)}a(safeExtend,"safeExtend");function merge(e,t){const o=mergeDefs(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return assignProp(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return clone(e,o)}a(merge,"merge");function partial(e,t,o){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=mergeDefs(t._zod.def,{get shape(){const c=t._zod.def.shape,l={...c};if(o)for(const d in o){if(!(d in c))throw new Error(`Unrecognized key: "${d}"`);o[d]&&(l[d]=e?new e({type:"optional",innerType:c[d]}):c[d])}else for(const d in c)l[d]=e?new e({type:"optional",innerType:c[d]}):c[d];return assignProp(this,"shape",l),l},checks:[]});return clone(t,s)}a(partial,"partial");function required(e,t,o){const n=mergeDefs(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(o)for(const s in o){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);o[s]&&(i[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)i[s]=new e({type:"nonoptional",innerType:r[s]});return assignProp(this,"shape",i),i}});return clone(t,n)}a(required,"required");function aborted(e,t=0){if(e.aborted===!0)return!0;for(let o=t;o<e.issues.length;o++)if(e.issues[o]?.continue!==!0)return!0;return!1}a(aborted,"aborted");function prefixIssues(e,t){return t.map(o=>{var n;return(n=o).path??(n.path=[]),o.path.unshift(e),o})}a(prefixIssues,"prefixIssues");function unwrapMessage(e){return typeof e=="string"?e:e?.message}a(unwrapMessage,"unwrapMessage");function finalizeIssue(e,t,o){const n={...e,path:e.path??[]};if(!e.message){const r=unwrapMessage(e.inst?._zod.def?.error?.(e))??unwrapMessage(t?.error?.(e))??unwrapMessage(o.customError?.(e))??unwrapMessage(o.localeError?.(e))??"Invalid input";n.message=r}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}a(finalizeIssue,"finalizeIssue");function getLengthableOrigin(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}a(getLengthableOrigin,"getLengthableOrigin");function issue(...e){const[t,o,n]=e;return typeof t=="string"?{message:t,code:"custom",input:o,inst:n}:{...t}}a(issue,"issue");const initializer$1=a((e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,jsonStringifyReplacer,2),Object.defineProperty(e,"toString",{value:a(()=>e.message,"value"),enumerable:!1})},"initializer$1"),$ZodError=$constructor("$ZodError",initializer$1),$ZodRealError=$constructor("$ZodError",initializer$1,{Parent:Error});function flattenError(e,t=o=>o.message){const o={},n=[];for(const r of e.issues)r.path.length>0?(o[r.path[0]]=o[r.path[0]]||[],o[r.path[0]].push(t(r))):n.push(t(r));return{formErrors:n,fieldErrors:o}}a(flattenError,"flattenError");function formatError(e,t=o=>o.message){const o={_errors:[]},n=a(r=>{for(const i of r.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(s=>n({issues:s}));else if(i.code==="invalid_key")n({issues:i.issues});else if(i.code==="invalid_element")n({issues:i.issues});else if(i.path.length===0)o._errors.push(t(i));else{let s=o,c=0;for(;c<i.path.length;){const l=i.path[c];c===i.path.length-1?(s[l]=s[l]||{_errors:[]},s[l]._errors.push(t(i))):s[l]=s[l]||{_errors:[]},s=s[l],c++}}},"processError");return n(e),o}a(formatError,"formatError");function toDotPath(e){const t=[],o=e.map(n=>typeof n=="object"?n.key:n);for(const n of o)typeof n=="number"?t.push(`[${n}]`):typeof n=="symbol"?t.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?t.push(`[${JSON.stringify(n)}]`):(t.length&&t.push("."),t.push(n));return t.join("")}a(toDotPath,"toDotPath");function prettifyError(e){const t=[],o=[...e.issues].sort((n,r)=>(n.path??[]).length-(r.path??[]).length);for(const n of o)t.push(`✖ ${n.message}`),n.path?.length&&t.push(`  → at ${toDotPath(n.path)}`);return t.join(`
`)}a(prettifyError,"prettifyError");const _parse=a(e=>(t,o,n,r)=>{const i=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:o,issues:[]},i);if(s instanceof Promise)throw new $ZodAsyncError;if(s.issues.length){const c=new(r?.Err??e)(s.issues.map(l=>finalizeIssue(l,i,config())));throw captureStackTrace(c,r?.callee),c}return s.value},"_parse"),_parseAsync=a(e=>async(t,o,n,r)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:o,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const c=new(r?.Err??e)(s.issues.map(l=>finalizeIssue(l,i,config())));throw captureStackTrace(c,r?.callee),c}return s.value},"_parseAsync"),_safeParse=a(e=>(t,o,n)=>{const r=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:o,issues:[]},r);if(i instanceof Promise)throw new $ZodAsyncError;return i.issues.length?{success:!1,error:new(e??$ZodError)(i.issues.map(s=>finalizeIssue(s,r,config())))}:{success:!0,data:i.value}},"_safeParse"),safeParse$1=_safeParse($ZodRealError),_safeParseAsync=a(e=>async(t,o,n)=>{const r=n?Object.assign(n,{async:!0}):{async:!0};let i=t._zod.run({value:o,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>finalizeIssue(s,r,config())))}:{success:!0,data:i.value}},"_safeParseAsync"),safeParseAsync$1=_safeParseAsync($ZodRealError),_encode=a(e=>(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return _parse(e)(t,o,r)},"_encode"),_decode=a(e=>(t,o,n)=>_parse(e)(t,o,n),"_decode"),_encodeAsync=a(e=>async(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return _parseAsync(e)(t,o,r)},"_encodeAsync"),_decodeAsync=a(e=>async(t,o,n)=>_parseAsync(e)(t,o,n),"_decodeAsync"),_safeEncode=a(e=>(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return _safeParse(e)(t,o,r)},"_safeEncode"),_safeDecode=a(e=>(t,o,n)=>_safeParse(e)(t,o,n),"_safeDecode"),_safeEncodeAsync=a(e=>async(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return _safeParseAsync(e)(t,o,r)},"_safeEncodeAsync"),_safeDecodeAsync=a(e=>async(t,o,n)=>_safeParseAsync(e)(t,o,n),"_safeDecodeAsync"),cuid=/^[cC][^\s-]{8,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/,duration$1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=a(e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,"uuid"),email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_emoji$1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function emoji(){return new RegExp(_emoji$1,"u")}a(emoji,"emoji");const ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^[A-Za-z0-9_-]*$/,e164=/^\+[1-9]\d{6,14}$/,dateSource="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",date$1=new RegExp(`^${dateSource}$`);function timeSource(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}a(timeSource,"timeSource");function time$1(e){return new RegExp(`^${timeSource(e)}$`)}a(time$1,"time$1");function datetime$1(e){const t=timeSource({precision:e.precision}),o=["Z"];e.local&&o.push(""),e.offset&&o.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${t}(?:${o.join("|")})`;return new RegExp(`^${dateSource}T(?:${n})$`)}a(datetime$1,"datetime$1");const string$1=a(e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},"string$1"),integer=/^-?\d+$/,number$1=/^-?\d+(?:\.\d+)?$/,boolean$1=/^(?:true|false)$/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/,$ZodCheck=$constructor("$ZodCheck",(e,t)=>{var o;e._zod??(e._zod={}),e._zod.def=t,(o=e._zod).onattach??(o.onattach=[])}),numericOriginMap={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(e,t)=>{$ZodCheck.init(e,t);const o=numericOriginMap[typeof t.value];e._zod.onattach.push(n=>{const r=n._zod.bag,i=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:o,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(e,t)=>{$ZodCheck.init(e,t);const o=numericOriginMap[typeof t.value];e._zod.onattach.push(n=>{const r=n._zod.bag,i=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:o,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(e,t)=>{$ZodCheck.init(e,t),e._zod.onattach.push(o=>{var n;(n=o._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=o=>{if(typeof o.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof o.value=="bigint"?o.value%t.value===BigInt(0):floatSafeRemainder(o.value,t.value)===0)||o.issues.push({origin:typeof o.value,code:"not_multiple_of",divisor:t.value,input:o.value,inst:e,continue:!t.abort})}}),$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(e,t)=>{$ZodCheck.init(e,t),t.format=t.format||"float64";const o=t.format?.includes("int"),n=o?"int":"number",[r,i]=NUMBER_FORMAT_RANGES[t.format];e._zod.onattach.push(s=>{const c=s._zod.bag;c.format=t.format,c.minimum=r,c.maximum=i,o&&(c.pattern=integer)}),e._zod.check=s=>{const c=s.value;if(o){if(!Number.isInteger(c)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?s.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):s.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}c<r&&s.issues.push({origin:"number",input:c,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),c>i&&s.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(e,t)=>{var o;$ZodCheck.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!nullish(r)&&r.length!==void 0}),e._zod.onattach.push(n=>{const r=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const s=getLengthableOrigin(r);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(e,t)=>{var o;$ZodCheck.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!nullish(r)&&r.length!==void 0}),e._zod.onattach.push(n=>{const r=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const s=getLengthableOrigin(r);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(e,t)=>{var o;$ZodCheck.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!nullish(r)&&r.length!==void 0}),e._zod.onattach.push(n=>{const r=n._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=n=>{const r=n.value,i=r.length;if(i===t.length)return;const s=getLengthableOrigin(r),c=i>t.length;n.issues.push({origin:s,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(e,t)=>{var o,n;$ZodCheck.init(e,t),e._zod.onattach.push(r=>{const i=r._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(o=e._zod).check??(o.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(e,t)=>{$ZodCheckStringFormat.init(e,t),e._zod.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:"regex",input:o.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=lowercase),$ZodCheckStringFormat.init(e,t)}),$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=uppercase),$ZodCheckStringFormat.init(e,t)}),$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(e,t)=>{$ZodCheck.init(e,t);const o=escapeRegex(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${o}`:o);t.pattern=n,e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(e,t)=>{$ZodCheck.init(e,t);const o=new RegExp(`^${escapeRegex(t.prefix)}.*`);t.pattern??(t.pattern=o),e._zod.onattach.push(n=>{const r=n._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(o)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(e,t)=>{$ZodCheck.init(e,t);const o=new RegExp(`.*${escapeRegex(t.suffix)}$`);t.pattern??(t.pattern=o),e._zod.onattach.push(n=>{const r=n._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(o)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(e,t)=>{$ZodCheck.init(e,t),e._zod.check=o=>{o.value=t.tx(o.value)}}),W=class W{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const n=t.split(`
`).filter(s=>s),r=Math.min(...n.map(s=>s.length-s.trimStart().length)),i=n.map(s=>s.slice(r)).map(s=>" ".repeat(this.indent*2)+s);for(const s of i)this.content.push(s)}compile(){const t=Function,o=this?.args,r=[...(this?.content??[""]).map(i=>`  ${i}`)];return new t(...o,r.join(`
`))}};a(W,"Doc");let Doc=W;const version={major:4,minor:3,patch:6},$ZodType=$constructor("$ZodType",(e,t)=>{var o;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=version;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const r of n)for(const i of r._zod.onattach)i(e);if(n.length===0)(o=e._zod).deferred??(o.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const r=a((s,c,l)=>{let d=aborted(s),h;for(const f of c){if(f._zod.def.when){if(!f._zod.def.when(s))continue}else if(d)continue;const g=s.issues.length,m=f._zod.check(s);if(m instanceof Promise&&l?.async===!1)throw new $ZodAsyncError;if(h||m instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await m,s.issues.length!==g&&(d||(d=aborted(s,g)))});else{if(s.issues.length===g)continue;d||(d=aborted(s,g))}}return h?h.then(()=>s):s},"runChecks"),i=a((s,c,l)=>{if(aborted(s))return s.aborted=!0,s;const d=r(c,n,l);if(d instanceof Promise){if(l.async===!1)throw new $ZodAsyncError;return d.then(h=>e._zod.parse(h,l))}return e._zod.parse(d,l)},"handleCanaryResult");e._zod.run=(s,c)=>{if(c.skipChecks)return e._zod.parse(s,c);if(c.direction==="backward"){const d=e._zod.parse({value:s.value,issues:[]},{...c,skipChecks:!0});return d instanceof Promise?d.then(h=>i(h,s,c)):i(d,s,c)}const l=e._zod.parse(s,c);if(l instanceof Promise){if(c.async===!1)throw new $ZodAsyncError;return l.then(d=>r(d,n,c))}return r(l,n,c)}}defineLazy(e,"~standard",()=>({validate:a(r=>{try{const i=safeParse$1(e,r);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return safeParseAsync$1(e,r).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},"validate"),vendor:"zod",version:1}))}),$ZodString=$constructor("$ZodString",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??string$1(e._zod.bag),e._zod.parse=(o,n)=>{if(t.coerce)try{o.value=String(o.value)}catch{}return typeof o.value=="string"||o.issues.push({expected:"string",code:"invalid_type",input:o.value,inst:e}),o}}),$ZodStringFormat=$constructor("$ZodStringFormat",(e,t)=>{$ZodCheckStringFormat.init(e,t),$ZodString.init(e,t)}),$ZodGUID=$constructor("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=guid),$ZodStringFormat.init(e,t)}),$ZodUUID=$constructor("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=uuid(n))}else t.pattern??(t.pattern=uuid());$ZodStringFormat.init(e,t)}),$ZodEmail=$constructor("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=email),$ZodStringFormat.init(e,t)}),$ZodURL=$constructor("$ZodURL",(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=o=>{try{const n=o.value.trim(),r=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.hostname)||o.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:o.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||o.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:o.value,inst:e,continue:!t.abort})),t.normalize?o.value=r.href:o.value=n;return}catch{o.issues.push({code:"invalid_format",format:"url",input:o.value,inst:e,continue:!t.abort})}}}),$ZodEmoji=$constructor("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=emoji()),$ZodStringFormat.init(e,t)}),$ZodNanoID=$constructor("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=nanoid),$ZodStringFormat.init(e,t)}),$ZodCUID=$constructor("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=cuid),$ZodStringFormat.init(e,t)}),$ZodCUID2=$constructor("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=cuid2),$ZodStringFormat.init(e,t)}),$ZodULID=$constructor("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ulid),$ZodStringFormat.init(e,t)}),$ZodXID=$constructor("$ZodXID",(e,t)=>{t.pattern??(t.pattern=xid),$ZodStringFormat.init(e,t)}),$ZodKSUID=$constructor("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ksuid),$ZodStringFormat.init(e,t)}),$ZodISODateTime=$constructor("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=datetime$1(t)),$ZodStringFormat.init(e,t)}),$ZodISODate=$constructor("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=date$1),$ZodStringFormat.init(e,t)}),$ZodISOTime=$constructor("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=time$1(t)),$ZodStringFormat.init(e,t)}),$ZodISODuration=$constructor("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=duration$1),$ZodStringFormat.init(e,t)}),$ZodIPv4=$constructor("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ipv4),$ZodStringFormat.init(e,t),e._zod.bag.format="ipv4"}),$ZodIPv6=$constructor("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ipv6),$ZodStringFormat.init(e,t),e._zod.bag.format="ipv6",e._zod.check=o=>{try{new URL(`http://[${o.value}]`)}catch{o.issues.push({code:"invalid_format",format:"ipv6",input:o.value,inst:e,continue:!t.abort})}}}),$ZodCIDRv4=$constructor("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=cidrv4),$ZodStringFormat.init(e,t)}),$ZodCIDRv6=$constructor("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=cidrv6),$ZodStringFormat.init(e,t),e._zod.check=o=>{const n=o.value.split("/");try{if(n.length!==2)throw new Error;const[r,i]=n;if(!i)throw new Error;const s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{o.issues.push({code:"invalid_format",format:"cidrv6",input:o.value,inst:e,continue:!t.abort})}}});function isValidBase64(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}a(isValidBase64,"isValidBase64");const $ZodBase64=$constructor("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=base64),$ZodStringFormat.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=o=>{isValidBase64(o.value)||o.issues.push({code:"invalid_format",format:"base64",input:o.value,inst:e,continue:!t.abort})}});function isValidBase64URL(e){if(!base64url.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),o=t.padEnd(Math.ceil(t.length/4)*4,"=");return isValidBase64(o)}a(isValidBase64URL,"isValidBase64URL");const $ZodBase64URL=$constructor("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=base64url),$ZodStringFormat.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=o=>{isValidBase64URL(o.value)||o.issues.push({code:"invalid_format",format:"base64url",input:o.value,inst:e,continue:!t.abort})}}),$ZodE164=$constructor("$ZodE164",(e,t)=>{t.pattern??(t.pattern=e164),$ZodStringFormat.init(e,t)});function isValidJWT(e,t=null){try{const o=e.split(".");if(o.length!==3)return!1;const[n]=o;if(!n)return!1;const r=JSON.parse(atob(n));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}a(isValidJWT,"isValidJWT");const $ZodJWT=$constructor("$ZodJWT",(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=o=>{isValidJWT(o.value,t.alg)||o.issues.push({code:"invalid_format",format:"jwt",input:o.value,inst:e,continue:!t.abort})}}),$ZodNumber=$constructor("$ZodNumber",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=e._zod.bag.pattern??number$1,e._zod.parse=(o,n)=>{if(t.coerce)try{o.value=Number(o.value)}catch{}const r=o.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return o;const i=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return o.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...i?{received:i}:{}}),o}}),$ZodNumberFormat=$constructor("$ZodNumberFormat",(e,t)=>{$ZodCheckNumberFormat.init(e,t),$ZodNumber.init(e,t)}),$ZodBoolean=$constructor("$ZodBoolean",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=boolean$1,e._zod.parse=(o,n)=>{if(t.coerce)try{o.value=!!o.value}catch{}const r=o.value;return typeof r=="boolean"||o.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),o}}),$ZodUnknown=$constructor("$ZodUnknown",(e,t)=>{$ZodType.init(e,t),e._zod.parse=o=>o}),$ZodNever=$constructor("$ZodNever",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(o,n)=>(o.issues.push({expected:"never",code:"invalid_type",input:o.value,inst:e}),o)});function handleArrayResult(e,t,o){e.issues.length&&t.issues.push(...prefixIssues(o,e.issues)),t.value[o]=e.value}a(handleArrayResult,"handleArrayResult");const $ZodArray=$constructor("$ZodArray",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(o,n)=>{const r=o.value;if(!Array.isArray(r))return o.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),o;o.value=Array(r.length);const i=[];for(let s=0;s<r.length;s++){const c=r[s],l=t.element._zod.run({value:c,issues:[]},n);l instanceof Promise?i.push(l.then(d=>handleArrayResult(d,o,s))):handleArrayResult(l,o,s)}return i.length?Promise.all(i).then(()=>o):o}});function handlePropertyResult(e,t,o,n,r){if(e.issues.length){if(r&&!(o in n))return;t.issues.push(...prefixIssues(o,e.issues))}e.value===void 0?o in n&&(t.value[o]=void 0):t.value[o]=e.value}a(handlePropertyResult,"handlePropertyResult");function normalizeDef(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const o=optionalKeys(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}a(normalizeDef,"normalizeDef");function handleCatchall(e,t,o,n,r,i){const s=[],c=r.keySet,l=r.catchall._zod,d=l.def.type,h=l.optout==="optional";for(const f in t){if(c.has(f))continue;if(d==="never"){s.push(f);continue}const g=l.run({value:t[f],issues:[]},n);g instanceof Promise?e.push(g.then(m=>handlePropertyResult(m,o,f,t,h))):handlePropertyResult(g,o,f,t,h)}return s.length&&o.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>o):o}a(handleCatchall,"handleCatchall");const $ZodObject=$constructor("$ZodObject",(e,t)=>{if($ZodType.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const c=t.shape;Object.defineProperty(t,"shape",{get:a(()=>{const l={...c};return Object.defineProperty(t,"shape",{value:l}),l},"get")})}const n=cached(()=>normalizeDef(t));defineLazy(e._zod,"propValues",()=>{const c=t.shape,l={};for(const d in c){const h=c[d]._zod;if(h.values){l[d]??(l[d]=new Set);for(const f of h.values)l[d].add(f)}}return l});const r=isObject,i=t.catchall;let s;e._zod.parse=(c,l)=>{s??(s=n.value);const d=c.value;if(!r(d))return c.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),c;c.value={};const h=[],f=s.shape;for(const g of s.keys){const m=f[g],T=m._zod.optout==="optional",I=m._zod.run({value:d[g],issues:[]},l);I instanceof Promise?h.push(I.then(A=>handlePropertyResult(A,c,g,d,T))):handlePropertyResult(I,c,g,d,T)}return i?handleCatchall(h,d,c,l,n.value,e):h.length?Promise.all(h).then(()=>c):c}}),$ZodObjectJIT=$constructor("$ZodObjectJIT",(e,t)=>{$ZodObject.init(e,t);const o=e._zod.parse,n=cached(()=>normalizeDef(t)),r=a(g=>{const m=new Doc(["shape","payload","ctx"]),T=n.value,I=a(v=>{const k=esc(v);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`},"parseStr");m.write("const input = payload.value;");const A=Object.create(null);let C=0;for(const v of T.keys)A[v]=`key_${C++}`;m.write("const newResult = {};");for(const v of T.keys){const k=A[v],O=esc(v),H=g[v]?._zod?.optout==="optional";m.write(`const ${k} = ${I(v)};`),H?m.write(`
        if (${k}.issues.length) {
          if (${O} in input) {
            payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
              ...iss,
              path: iss.path ? [${O}, ...iss.path] : [${O}]
            })));
          }
        }
        
        if (${k}.value === undefined) {
          if (${O} in input) {
            newResult[${O}] = undefined;
          }
        } else {
          newResult[${O}] = ${k}.value;
        }
        
      `):m.write(`
        if (${k}.issues.length) {
          payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${O}, ...iss.path] : [${O}]
          })));
        }
        
        if (${k}.value === undefined) {
          if (${O} in input) {
            newResult[${O}] = undefined;
          }
        } else {
          newResult[${O}] = ${k}.value;
        }
        
      `)}m.write("payload.value = newResult;"),m.write("return payload;");const D=m.compile();return(v,k)=>D(g,v,k)},"generateFastpass");let i;const s=isObject,c=!globalConfig.jitless,d=c&&allowsEval.value,h=t.catchall;let f;e._zod.parse=(g,m)=>{f??(f=n.value);const T=g.value;return s(T)?c&&d&&m?.async===!1&&m.jitless!==!0?(i||(i=r(t.shape)),g=i(g,m),h?handleCatchall([],T,g,m,f,e):g):o(g,m):(g.issues.push({expected:"object",code:"invalid_type",input:T,inst:e}),g)}});function handleUnionResults(e,t,o,n){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const r=e.filter(i=>!aborted(i));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:o,errors:e.map(i=>i.issues.map(s=>finalizeIssue(s,n,config())))}),t)}a(handleUnionResults,"handleUnionResults");const $ZodUnion=$constructor("$ZodUnion",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),defineLazy(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),defineLazy(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),defineLazy(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>cleanRegex(i.source)).join("|")})$`)}});const o=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(r,i)=>{if(o)return n(r,i);let s=!1;const c=[];for(const l of t.options){const d=l._zod.run({value:r.value,issues:[]},i);if(d instanceof Promise)c.push(d),s=!0;else{if(d.issues.length===0)return d;c.push(d)}}return s?Promise.all(c).then(l=>handleUnionResults(l,r,e,i)):handleUnionResults(c,r,e,i)}}),$ZodIntersection=$constructor("$ZodIntersection",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(o,n)=>{const r=o.value,i=t.left._zod.run({value:r,issues:[]},n),s=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([l,d])=>handleIntersectionResults(o,l,d)):handleIntersectionResults(o,i,s)}});function mergeValues(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(isPlainObject(e)&&isPlainObject(t)){const o=Object.keys(t),n=Object.keys(e).filter(i=>o.indexOf(i)!==-1),r={...e,...t};for(const i of n){const s=mergeValues(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};r[i]=s.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const o=[];for(let n=0;n<e.length;n++){const r=e[n],i=t[n],s=mergeValues(r,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};o.push(s.data)}return{valid:!0,data:o}}return{valid:!1,mergeErrorPath:[]}}a(mergeValues,"mergeValues");function handleIntersectionResults(e,t,o){const n=new Map;let r;for(const c of t.issues)if(c.code==="unrecognized_keys"){r??(r=c);for(const l of c.keys)n.has(l)||n.set(l,{}),n.get(l).l=!0}else e.issues.push(c);for(const c of o.issues)if(c.code==="unrecognized_keys")for(const l of c.keys)n.has(l)||n.set(l,{}),n.get(l).r=!0;else e.issues.push(c);const i=[...n].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(i.length&&r&&e.issues.push({...r,keys:i}),aborted(e))return e;const s=mergeValues(t.value,o.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}a(handleIntersectionResults,"handleIntersectionResults");const $ZodEnum=$constructor("$ZodEnum",(e,t)=>{$ZodType.init(e,t);const o=getEnumValues(t.entries),n=new Set(o);e._zod.values=n,e._zod.pattern=new RegExp(`^(${o.filter(r=>propertyKeyTypes.has(typeof r)).map(r=>typeof r=="string"?escapeRegex(r):r.toString()).join("|")})$`),e._zod.parse=(r,i)=>{const s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:o,input:s,inst:e}),r}}),$ZodTransform=$constructor("$ZodTransform",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(o,n)=>{if(n.direction==="backward")throw new $ZodEncodeError(e.constructor.name);const r=t.transform(o.value,o);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(s=>(o.value=s,o));if(r instanceof Promise)throw new $ZodAsyncError;return o.value=r,o}});function handleOptionalResult(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}a(handleOptionalResult,"handleOptionalResult");const $ZodOptional=$constructor("$ZodOptional",(e,t)=>{$ZodType.init(e,t),e._zod.optin="optional",e._zod.optout="optional",defineLazy(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),defineLazy(e._zod,"pattern",()=>{const o=t.innerType._zod.pattern;return o?new RegExp(`^(${cleanRegex(o.source)})?$`):void 0}),e._zod.parse=(o,n)=>{if(t.innerType._zod.optin==="optional"){const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(i=>handleOptionalResult(i,o.value)):handleOptionalResult(r,o.value)}return o.value===void 0?o:t.innerType._zod.run(o,n)}}),$ZodExactOptional=$constructor("$ZodExactOptional",(e,t)=>{$ZodOptional.init(e,t),defineLazy(e._zod,"values",()=>t.innerType._zod.values),defineLazy(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(o,n)=>t.innerType._zod.run(o,n)}),$ZodNullable=$constructor("$ZodNullable",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"optin",()=>t.innerType._zod.optin),defineLazy(e._zod,"optout",()=>t.innerType._zod.optout),defineLazy(e._zod,"pattern",()=>{const o=t.innerType._zod.pattern;return o?new RegExp(`^(${cleanRegex(o.source)}|null)$`):void 0}),defineLazy(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(o,n)=>o.value===null?o:t.innerType._zod.run(o,n)}),$ZodDefault=$constructor("$ZodDefault",(e,t)=>{$ZodType.init(e,t),e._zod.optin="optional",defineLazy(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(o,n)=>{if(n.direction==="backward")return t.innerType._zod.run(o,n);if(o.value===void 0)return o.value=t.defaultValue,o;const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(i=>handleDefaultResult(i,t)):handleDefaultResult(r,t)}});function handleDefaultResult(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}a(handleDefaultResult,"handleDefaultResult");const $ZodPrefault=$constructor("$ZodPrefault",(e,t)=>{$ZodType.init(e,t),e._zod.optin="optional",defineLazy(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(o,n)=>(n.direction==="backward"||o.value===void 0&&(o.value=t.defaultValue),t.innerType._zod.run(o,n))}),$ZodNonOptional=$constructor("$ZodNonOptional",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"values",()=>{const o=t.innerType._zod.values;return o?new Set([...o].filter(n=>n!==void 0)):void 0}),e._zod.parse=(o,n)=>{const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(i=>handleNonOptionalResult(i,e)):handleNonOptionalResult(r,e)}});function handleNonOptionalResult(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}a(handleNonOptionalResult,"handleNonOptionalResult");const $ZodCatch=$constructor("$ZodCatch",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"optin",()=>t.innerType._zod.optin),defineLazy(e._zod,"optout",()=>t.innerType._zod.optout),defineLazy(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(o,n)=>{if(n.direction==="backward")return t.innerType._zod.run(o,n);const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(i=>(o.value=i.value,i.issues.length&&(o.value=t.catchValue({...o,error:{issues:i.issues.map(s=>finalizeIssue(s,n,config()))},input:o.value}),o.issues=[]),o)):(o.value=r.value,r.issues.length&&(o.value=t.catchValue({...o,error:{issues:r.issues.map(i=>finalizeIssue(i,n,config()))},input:o.value}),o.issues=[]),o)}}),$ZodPipe=$constructor("$ZodPipe",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"values",()=>t.in._zod.values),defineLazy(e._zod,"optin",()=>t.in._zod.optin),defineLazy(e._zod,"optout",()=>t.out._zod.optout),defineLazy(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(o,n)=>{if(n.direction==="backward"){const i=t.out._zod.run(o,n);return i instanceof Promise?i.then(s=>handlePipeResult(s,t.in,n)):handlePipeResult(i,t.in,n)}const r=t.in._zod.run(o,n);return r instanceof Promise?r.then(i=>handlePipeResult(i,t.out,n)):handlePipeResult(r,t.out,n)}});function handlePipeResult(e,t,o){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},o)}a(handlePipeResult,"handlePipeResult");const $ZodReadonly=$constructor("$ZodReadonly",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"propValues",()=>t.innerType._zod.propValues),defineLazy(e._zod,"values",()=>t.innerType._zod.values),defineLazy(e._zod,"optin",()=>t.innerType?._zod?.optin),defineLazy(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(o,n)=>{if(n.direction==="backward")return t.innerType._zod.run(o,n);const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(handleReadonlyResult):handleReadonlyResult(r)}});function handleReadonlyResult(e){return e.value=Object.freeze(e.value),e}a(handleReadonlyResult,"handleReadonlyResult");const $ZodCustom=$constructor("$ZodCustom",(e,t)=>{$ZodCheck.init(e,t),$ZodType.init(e,t),e._zod.parse=(o,n)=>o,e._zod.check=o=>{const n=o.value,r=t.fn(n);if(r instanceof Promise)return r.then(i=>handleRefineResult(i,o,n,e));handleRefineResult(r,o,n,e)}});function handleRefineResult(e,t,o,n){if(!e){const r={code:"custom",input:o,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(r.params=n._zod.def.params),t.issues.push(issue(r))}}a(handleRefineResult,"handleRefineResult");var _a;const De=class De{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...o){const n=o[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const o=this._map.get(t);return o&&typeof o=="object"&&"id"in o&&this._idmap.delete(o.id),this._map.delete(t),this}get(t){const o=t._zod.parent;if(o){const n={...this.get(o)??{}};delete n.id;const r={...n,...this._map.get(t)};return Object.keys(r).length?r:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};a(De,"$ZodRegistry");let $ZodRegistry=De;function registry(){return new $ZodRegistry}a(registry,"registry"),(_a=globalThis).__zod_globalRegistry??(_a.__zod_globalRegistry=registry());const globalRegistry=globalThis.__zod_globalRegistry;function _string(e,t){return new e({type:"string",...normalizeParams(t)})}a(_string,"_string");function _email(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(t)})}a(_email,"_email");function _guid(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(t)})}a(_guid,"_guid");function _uuid(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(t)})}a(_uuid,"_uuid");function _uuidv4(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(t)})}a(_uuidv4,"_uuidv4");function _uuidv6(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(t)})}a(_uuidv6,"_uuidv6");function _uuidv7(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(t)})}a(_uuidv7,"_uuidv7");function _url(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(t)})}a(_url,"_url");function _emoji(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(t)})}a(_emoji,"_emoji");function _nanoid(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(t)})}a(_nanoid,"_nanoid");function _cuid(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(t)})}a(_cuid,"_cuid");function _cuid2(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(t)})}a(_cuid2,"_cuid2");function _ulid(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(t)})}a(_ulid,"_ulid");function _xid(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(t)})}a(_xid,"_xid");function _ksuid(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(t)})}a(_ksuid,"_ksuid");function _ipv4(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(t)})}a(_ipv4,"_ipv4");function _ipv6(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(t)})}a(_ipv6,"_ipv6");function _cidrv4(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(t)})}a(_cidrv4,"_cidrv4");function _cidrv6(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(t)})}a(_cidrv6,"_cidrv6");function _base64(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(t)})}a(_base64,"_base64");function _base64url(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(t)})}a(_base64url,"_base64url");function _e164(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(t)})}a(_e164,"_e164");function _jwt(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(t)})}a(_jwt,"_jwt");function _isoDateTime(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(t)})}a(_isoDateTime,"_isoDateTime");function _isoDate(e,t){return new e({type:"string",format:"date",check:"string_format",...normalizeParams(t)})}a(_isoDate,"_isoDate");function _isoTime(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(t)})}a(_isoTime,"_isoTime");function _isoDuration(e,t){return new e({type:"string",format:"duration",check:"string_format",...normalizeParams(t)})}a(_isoDuration,"_isoDuration");function _number(e,t){return new e({type:"number",checks:[],...normalizeParams(t)})}a(_number,"_number");function _int(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(t)})}a(_int,"_int");function _boolean(e,t){return new e({type:"boolean",...normalizeParams(t)})}a(_boolean,"_boolean");function _unknown(e){return new e({type:"unknown"})}a(_unknown,"_unknown");function _never(e,t){return new e({type:"never",...normalizeParams(t)})}a(_never,"_never");function _lt(e,t){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(t),value:e,inclusive:!1})}a(_lt,"_lt");function _lte(e,t){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(t),value:e,inclusive:!0})}a(_lte,"_lte");function _gt(e,t){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(t),value:e,inclusive:!1})}a(_gt,"_gt");function _gte(e,t){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(t),value:e,inclusive:!0})}a(_gte,"_gte");function _multipleOf(e,t){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(t),value:e})}a(_multipleOf,"_multipleOf");function _maxLength(e,t){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(t),maximum:e})}a(_maxLength,"_maxLength");function _minLength(e,t){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(t),minimum:e})}a(_minLength,"_minLength");function _length(e,t){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(t),length:e})}a(_length,"_length");function _regex(e,t){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(t),pattern:e})}a(_regex,"_regex");function _lowercase(e){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(e)})}a(_lowercase,"_lowercase");function _uppercase(e){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(e)})}a(_uppercase,"_uppercase");function _includes(e,t){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(t),includes:e})}a(_includes,"_includes");function _startsWith(e,t){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(t),prefix:e})}a(_startsWith,"_startsWith");function _endsWith(e,t){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(t),suffix:e})}a(_endsWith,"_endsWith");function _overwrite(e){return new $ZodCheckOverwrite({check:"overwrite",tx:e})}a(_overwrite,"_overwrite");function _normalize(e){return _overwrite(t=>t.normalize(e))}a(_normalize,"_normalize");function _trim(){return _overwrite(e=>e.trim())}a(_trim,"_trim");function _toLowerCase(){return _overwrite(e=>e.toLowerCase())}a(_toLowerCase,"_toLowerCase");function _toUpperCase(){return _overwrite(e=>e.toUpperCase())}a(_toUpperCase,"_toUpperCase");function _slugify(){return _overwrite(e=>slugify(e))}a(_slugify,"_slugify");function _array(e,t,o){return new e({type:"array",element:t,...normalizeParams(o)})}a(_array,"_array");function _refine(e,t,o){return new e({type:"custom",check:"custom",fn:t,...normalizeParams(o)})}a(_refine,"_refine");function _superRefine(e){const t=_check(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(issue(n,o.value,t._zod.def));else{const r=n;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=o.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),o.issues.push(issue(r))}},e(o.value,o)));return t}a(_superRefine,"_superRefine");function _check(e,t){const o=new $ZodCheck({check:"custom",...normalizeParams(t)});return o._zod.check=e,o}a(_check,"_check");function initializeContext(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??globalRegistry,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}a(initializeContext,"initializeContext");function process(e,t,o={path:[],schemaPath:[]}){var n;const r=e._zod.def,i=t.seen.get(e);if(i)return i.count++,o.schemaPath.includes(e)&&(i.cycle=o.path),i.schema;const s={schema:{},count:1,cycle:void 0,path:o.path};t.seen.set(e,s);const c=e._zod.toJSONSchema?.();if(c)s.schema=c;else{const h={...o,schemaPath:[...o.schemaPath,e],path:o.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,h);else{const g=s.schema,m=t.processors[r.type];if(!m)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);m(e,t,g,h)}const f=e._zod.parent;f&&(s.ref||(s.ref=f),process(f,t,h),t.seen.get(f).isParent=!0)}const l=t.metadataRegistry.get(e);return l&&Object.assign(s.schema,l),t.io==="input"&&isTransforming(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&s.schema._prefault&&((n=s.schema).default??(n.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}a(process,"process");function extractDefs(e,t){const o=e.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const s of e.seen.entries()){const c=e.metadataRegistry.get(s[0])?.id;if(c){const l=n.get(c);if(l&&l!==s[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(c,s[0])}}const r=a(s=>{const c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const f=e.external.registry.get(s[0])?.id,g=e.external.uri??(T=>T);if(f)return{ref:g(f)};const m=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=m,{defId:m,ref:`${g("__shared")}#/${c}/${m}`}}if(s[1]===o)return{ref:"#"};const d=`#/${c}/`,h=s[1].schema.id??`__schema${e.counter++}`;return{defId:h,ref:d+h}},"makeURI"),i=a(s=>{if(s[1].schema.$ref)return;const c=s[1],{ref:l,defId:d}=r(s);c.def={...c.schema},d&&(c.defId=d);const h=c.schema;for(const f in h)delete h[f];h.$ref=l},"extractToDef");if(e.cycles==="throw")for(const s of e.seen.entries()){const c=s[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>

Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const c=s[1];if(t===s[0]){i(s);continue}if(e.external){const d=e.external.registry.get(s[0])?.id;if(t!==s[0]&&d){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(c.cycle){i(s);continue}if(c.count>1&&e.reused==="ref"){i(s);continue}}}a(extractDefs,"extractDefs");function finalize(e,t){const o=e.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=a(s=>{const c=e.seen.get(s);if(c.ref===null)return;const l=c.def??c.schema,d={...l},h=c.ref;if(c.ref=null,h){n(h);const g=e.seen.get(h),m=g.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(m)):Object.assign(l,m),Object.assign(l,d),s._zod.parent===h)for(const I in l)I==="$ref"||I==="allOf"||I in d||delete l[I];if(m.$ref&&g.def)for(const I in l)I==="$ref"||I==="allOf"||I in g.def&&JSON.stringify(l[I])===JSON.stringify(g.def[I])&&delete l[I]}const f=s._zod.parent;if(f&&f!==h){n(f);const g=e.seen.get(f);if(g?.schema.$ref&&(l.$ref=g.schema.$ref,g.def))for(const m in l)m==="$ref"||m==="allOf"||m in g.def&&JSON.stringify(l[m])===JSON.stringify(g.def[m])&&delete l[m]}e.override({zodSchema:s,jsonSchema:l,path:c.path??[]})},"flattenRef");for(const s of[...e.seen.entries()].reverse())n(s[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const s=e.external.registry.get(t)?.id;if(!s)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(s)}Object.assign(r,o.def??o.schema);const i=e.external?.defs??{};for(const s of e.seen.entries()){const c=s[1];c.def&&c.defId&&(i[c.defId]=c.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?r.$defs=i:r.definitions=i);try{const s=JSON.parse(JSON.stringify(r));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(t,"input",e.processors),output:createStandardJSONSchemaMethod(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}a(finalize,"finalize");function isTransforming(e,t){const o=t??{seen:new Set};if(o.seen.has(e))return!1;o.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return isTransforming(n.element,o);if(n.type==="set")return isTransforming(n.valueType,o);if(n.type==="lazy")return isTransforming(n.getter(),o);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return isTransforming(n.innerType,o);if(n.type==="intersection")return isTransforming(n.left,o)||isTransforming(n.right,o);if(n.type==="record"||n.type==="map")return isTransforming(n.keyType,o)||isTransforming(n.valueType,o);if(n.type==="pipe")return isTransforming(n.in,o)||isTransforming(n.out,o);if(n.type==="object"){for(const r in n.shape)if(isTransforming(n.shape[r],o))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(isTransforming(r,o))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(isTransforming(r,o))return!0;return!!(n.rest&&isTransforming(n.rest,o))}return!1}a(isTransforming,"isTransforming");const createToJSONSchemaMethod=a((e,t={})=>o=>{const n=initializeContext({...o,processors:t});return process(e,n),extractDefs(n,e),finalize(n,e)},"createToJSONSchemaMethod"),createStandardJSONSchemaMethod=a((e,t,o={})=>n=>{const{libraryOptions:r,target:i}=n??{},s=initializeContext({...r??{},target:i,io:t,processors:o});return process(e,s),extractDefs(s,e),finalize(s,e)},"createStandardJSONSchemaMethod"),formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},stringProcessor=a((e,t,o,n)=>{const r=o;r.type="string";const{minimum:i,maximum:s,format:c,patterns:l,contentEncoding:d}=e._zod.bag;if(typeof i=="number"&&(r.minLength=i),typeof s=="number"&&(r.maxLength=s),c&&(r.format=formatMap[c]??c,r.format===""&&delete r.format,c==="time"&&delete r.format),d&&(r.contentEncoding=d),l&&l.size>0){const h=[...l];h.length===1?r.pattern=h[0].source:h.length>1&&(r.allOf=[...h.map(f=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},"stringProcessor"),numberProcessor=a((e,t,o,n)=>{const r=o,{minimum:i,maximum:s,format:c,multipleOf:l,exclusiveMaximum:d,exclusiveMinimum:h}=e._zod.bag;typeof c=="string"&&c.includes("int")?r.type="integer":r.type="number",typeof h=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.minimum=h,r.exclusiveMinimum=!0):r.exclusiveMinimum=h),typeof i=="number"&&(r.minimum=i,typeof h=="number"&&t.target!=="draft-04"&&(h>=i?delete r.minimum:delete r.exclusiveMinimum)),typeof d=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.maximum=d,r.exclusiveMaximum=!0):r.exclusiveMaximum=d),typeof s=="number"&&(r.maximum=s,typeof d=="number"&&t.target!=="draft-04"&&(d<=s?delete r.maximum:delete r.exclusiveMaximum)),typeof l=="number"&&(r.multipleOf=l)},"numberProcessor"),booleanProcessor=a((e,t,o,n)=>{o.type="boolean"},"booleanProcessor"),bigintProcessor=a((e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},"bigintProcessor"),symbolProcessor=a((e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},"symbolProcessor"),nullProcessor=a((e,t,o,n)=>{t.target==="openapi-3.0"?(o.type="string",o.nullable=!0,o.enum=[null]):o.type="null"},"nullProcessor"),undefinedProcessor=a((e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},"undefinedProcessor"),voidProcessor=a((e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},"voidProcessor"),neverProcessor=a((e,t,o,n)=>{o.not={}},"neverProcessor"),anyProcessor=a((e,t,o,n)=>{},"anyProcessor"),unknownProcessor=a((e,t,o,n)=>{},"unknownProcessor"),dateProcessor=a((e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},"dateProcessor"),enumProcessor=a((e,t,o,n)=>{const r=e._zod.def,i=getEnumValues(r.entries);i.every(s=>typeof s=="number")&&(o.type="number"),i.every(s=>typeof s=="string")&&(o.type="string"),o.enum=i},"enumProcessor"),literalProcessor=a((e,t,o,n)=>{const r=e._zod.def,i=[];for(const s of r.values)if(s===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){const s=i[0];o.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?o.enum=[s]:o.const=s}else i.every(s=>typeof s=="number")&&(o.type="number"),i.every(s=>typeof s=="string")&&(o.type="string"),i.every(s=>typeof s=="boolean")&&(o.type="boolean"),i.every(s=>s===null)&&(o.type="null"),o.enum=i},"literalProcessor"),nanProcessor=a((e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},"nanProcessor"),templateLiteralProcessor=a((e,t,o,n)=>{const r=o,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=i.source},"templateLiteralProcessor"),fileProcessor=a((e,t,o,n)=>{const r=o,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:c,mime:l}=e._zod.bag;s!==void 0&&(i.minLength=s),c!==void 0&&(i.maxLength=c),l?l.length===1?(i.contentMediaType=l[0],Object.assign(r,i)):(Object.assign(r,i),r.anyOf=l.map(d=>({contentMediaType:d}))):Object.assign(r,i)},"fileProcessor"),successProcessor=a((e,t,o,n)=>{o.type="boolean"},"successProcessor"),customProcessor=a((e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},"customProcessor"),functionProcessor=a((e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},"functionProcessor"),transformProcessor=a((e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},"transformProcessor"),mapProcessor=a((e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},"mapProcessor"),setProcessor=a((e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},"setProcessor"),arrayProcessor=a((e,t,o,n)=>{const r=o,i=e._zod.def,{minimum:s,maximum:c}=e._zod.bag;typeof s=="number"&&(r.minItems=s),typeof c=="number"&&(r.maxItems=c),r.type="array",r.items=process(i.element,t,{...n,path:[...n.path,"items"]})},"arrayProcessor"),objectProcessor=a((e,t,o,n)=>{const r=o,i=e._zod.def;r.type="object",r.properties={};const s=i.shape;for(const d in s)r.properties[d]=process(s[d],t,{...n,path:[...n.path,"properties",d]});const c=new Set(Object.keys(s)),l=new Set([...c].filter(d=>{const h=i.shape[d]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));l.size>0&&(r.required=Array.from(l)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=process(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},"objectProcessor"),unionProcessor=a((e,t,o,n)=>{const r=e._zod.def,i=r.inclusive===!1,s=r.options.map((c,l)=>process(c,t,{...n,path:[...n.path,i?"oneOf":"anyOf",l]}));i?o.oneOf=s:o.anyOf=s},"unionProcessor"),intersectionProcessor=a((e,t,o,n)=>{const r=e._zod.def,i=process(r.left,t,{...n,path:[...n.path,"allOf",0]}),s=process(r.right,t,{...n,path:[...n.path,"allOf",1]}),c=a(d=>"allOf"in d&&Object.keys(d).length===1,"isSimpleIntersection"),l=[...c(i)?i.allOf:[i],...c(s)?s.allOf:[s]];o.allOf=l},"intersectionProcessor"),tupleProcessor=a((e,t,o,n)=>{const r=o,i=e._zod.def;r.type="array";const s=t.target==="draft-2020-12"?"prefixItems":"items",c=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",l=i.items.map((g,m)=>process(g,t,{...n,path:[...n.path,s,m]})),d=i.rest?process(i.rest,t,{...n,path:[...n.path,c,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;t.target==="draft-2020-12"?(r.prefixItems=l,d&&(r.items=d)):t.target==="openapi-3.0"?(r.items={anyOf:l},d&&r.items.anyOf.push(d),r.minItems=l.length,d||(r.maxItems=l.length)):(r.items=l,d&&(r.additionalItems=d));const{minimum:h,maximum:f}=e._zod.bag;typeof h=="number"&&(r.minItems=h),typeof f=="number"&&(r.maxItems=f)},"tupleProcessor"),recordProcessor=a((e,t,o,n)=>{const r=o,i=e._zod.def;r.type="object";const s=i.keyType,l=s._zod.bag?.patterns;if(i.mode==="loose"&&l&&l.size>0){const h=process(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});r.patternProperties={};for(const f of l)r.patternProperties[f.source]=h}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=process(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=process(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const d=s._zod.values;if(d){const h=[...d].filter(f=>typeof f=="string"||typeof f=="number");h.length>0&&(r.required=h)}},"recordProcessor"),nullableProcessor=a((e,t,o,n)=>{const r=e._zod.def,i=process(r.innerType,t,n),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=r.innerType,o.nullable=!0):o.anyOf=[i,{type:"null"}]},"nullableProcessor"),nonoptionalProcessor=a((e,t,o,n)=>{const r=e._zod.def;process(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},"nonoptionalProcessor"),defaultProcessor=a((e,t,o,n)=>{const r=e._zod.def;process(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,o.default=JSON.parse(JSON.stringify(r.defaultValue))},"defaultProcessor"),prefaultProcessor=a((e,t,o,n)=>{const r=e._zod.def;process(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,t.io==="input"&&(o._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},"prefaultProcessor"),catchProcessor=a((e,t,o,n)=>{const r=e._zod.def;process(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType;let s;try{s=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}o.default=s},"catchProcessor"),pipeProcessor=a((e,t,o,n)=>{const r=e._zod.def,i=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;process(i,t,n);const s=t.seen.get(e);s.ref=i},"pipeProcessor"),readonlyProcessor=a((e,t,o,n)=>{const r=e._zod.def;process(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,o.readOnly=!0},"readonlyProcessor"),promiseProcessor=a((e,t,o,n)=>{const r=e._zod.def;process(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},"promiseProcessor"),optionalProcessor=a((e,t,o,n)=>{const r=e._zod.def;process(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},"optionalProcessor"),lazyProcessor=a((e,t,o,n)=>{const r=e._zod.innerType;process(r,t,n);const i=t.seen.get(e);i.ref=r},"lazyProcessor"),allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(e,t){if("_idmap"in e){const n=e,r=initializeContext({...t,processors:allProcessors}),i={};for(const l of n._idmap.entries()){const[d,h]=l;process(h,r)}const s={},c={registry:n,uri:t?.uri,defs:i};r.external=c;for(const l of n._idmap.entries()){const[d,h]=l;extractDefs(r,h),s[d]=finalize(r,h)}if(Object.keys(i).length>0){const l=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[l]:i}}return{schemas:s}}const o=initializeContext({...t,processors:allProcessors});return process(e,o),extractDefs(o,e),finalize(o,e)}a(toJSONSchema,"toJSONSchema");const ZodISODateTime=$constructor("ZodISODateTime",(e,t)=>{$ZodISODateTime.init(e,t),ZodStringFormat.init(e,t)});function datetime(e){return _isoDateTime(ZodISODateTime,e)}a(datetime,"datetime");const ZodISODate=$constructor("ZodISODate",(e,t)=>{$ZodISODate.init(e,t),ZodStringFormat.init(e,t)});function date(e){return _isoDate(ZodISODate,e)}a(date,"date");const ZodISOTime=$constructor("ZodISOTime",(e,t)=>{$ZodISOTime.init(e,t),ZodStringFormat.init(e,t)});function time(e){return _isoTime(ZodISOTime,e)}a(time,"time");const ZodISODuration=$constructor("ZodISODuration",(e,t)=>{$ZodISODuration.init(e,t),ZodStringFormat.init(e,t)});function duration(e){return _isoDuration(ZodISODuration,e)}a(duration,"duration");const initializer=a((e,t)=>{$ZodError.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:a(o=>formatError(e,o),"value")},flatten:{value:a(o=>flattenError(e,o),"value")},addIssue:{value:a(o=>{e.issues.push(o),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)},"value")},addIssues:{value:a(o=>{e.issues.push(...o),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)},"value")},isEmpty:{get(){return e.issues.length===0}}})},"initializer"),ZodRealError=$constructor("ZodError",initializer,{Parent:Error}),parse=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse=_safeParse(ZodRealError),safeParseAsync=_safeParseAsync(ZodRealError),encode=_encode(ZodRealError),decode=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_safeDecodeAsync(ZodRealError),ZodType=$constructor("ZodType",(e,t)=>($ZodType.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:createStandardJSONSchemaMethod(e,"input"),output:createStandardJSONSchemaMethod(e,"output")}}),e.toJSONSchema=createToJSONSchemaMethod(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...o)=>e.clone(mergeDefs(t,{checks:[...t.checks??[],...o.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(o,n)=>clone(e,o,n),e.brand=()=>e,e.register=((o,n)=>(o.add(e,n),e)),e.parse=(o,n)=>parse(e,o,n,{callee:e.parse}),e.safeParse=(o,n)=>safeParse(e,o,n),e.parseAsync=async(o,n)=>parseAsync(e,o,n,{callee:e.parseAsync}),e.safeParseAsync=async(o,n)=>safeParseAsync(e,o,n),e.spa=e.safeParseAsync,e.encode=(o,n)=>encode(e,o,n),e.decode=(o,n)=>decode(e,o,n),e.encodeAsync=async(o,n)=>encodeAsync(e,o,n),e.decodeAsync=async(o,n)=>decodeAsync(e,o,n),e.safeEncode=(o,n)=>safeEncode(e,o,n),e.safeDecode=(o,n)=>safeDecode(e,o,n),e.safeEncodeAsync=async(o,n)=>safeEncodeAsync(e,o,n),e.safeDecodeAsync=async(o,n)=>safeDecodeAsync(e,o,n),e.refine=(o,n)=>e.check(refine(o,n)),e.superRefine=o=>e.check(superRefine(o)),e.overwrite=o=>e.check(_overwrite(o)),e.optional=()=>optional(e),e.exactOptional=()=>exactOptional(e),e.nullable=()=>nullable(e),e.nullish=()=>optional(nullable(e)),e.nonoptional=o=>nonoptional(e,o),e.array=()=>array(e),e.or=o=>union([e,o]),e.and=o=>intersection(e,o),e.transform=o=>pipe(e,transform(o)),e.default=o=>_default(e,o),e.prefault=o=>prefault(e,o),e.catch=o=>_catch(e,o),e.pipe=o=>pipe(e,o),e.readonly=()=>readonly(e),e.describe=o=>{const n=e.clone();return globalRegistry.add(n,{description:o}),n},Object.defineProperty(e,"description",{get(){return globalRegistry.get(e)?.description},configurable:!0}),e.meta=(...o)=>{if(o.length===0)return globalRegistry.get(e);const n=e.clone();return globalRegistry.add(n,o[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=o=>o(e),e)),_ZodString=$constructor("_ZodString",(e,t)=>{$ZodString.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(n,r,i)=>stringProcessor(e,n,r);const o=e._zod.bag;e.format=o.format??null,e.minLength=o.minimum??null,e.maxLength=o.maximum??null,e.regex=(...n)=>e.check(_regex(...n)),e.includes=(...n)=>e.check(_includes(...n)),e.startsWith=(...n)=>e.check(_startsWith(...n)),e.endsWith=(...n)=>e.check(_endsWith(...n)),e.min=(...n)=>e.check(_minLength(...n)),e.max=(...n)=>e.check(_maxLength(...n)),e.length=(...n)=>e.check(_length(...n)),e.nonempty=(...n)=>e.check(_minLength(1,...n)),e.lowercase=n=>e.check(_lowercase(n)),e.uppercase=n=>e.check(_uppercase(n)),e.trim=()=>e.check(_trim()),e.normalize=(...n)=>e.check(_normalize(...n)),e.toLowerCase=()=>e.check(_toLowerCase()),e.toUpperCase=()=>e.check(_toUpperCase()),e.slugify=()=>e.check(_slugify())}),ZodString=$constructor("ZodString",(e,t)=>{$ZodString.init(e,t),_ZodString.init(e,t),e.email=o=>e.check(_email(ZodEmail,o)),e.url=o=>e.check(_url(ZodURL,o)),e.jwt=o=>e.check(_jwt(ZodJWT,o)),e.emoji=o=>e.check(_emoji(ZodEmoji,o)),e.guid=o=>e.check(_guid(ZodGUID,o)),e.uuid=o=>e.check(_uuid(ZodUUID,o)),e.uuidv4=o=>e.check(_uuidv4(ZodUUID,o)),e.uuidv6=o=>e.check(_uuidv6(ZodUUID,o)),e.uuidv7=o=>e.check(_uuidv7(ZodUUID,o)),e.nanoid=o=>e.check(_nanoid(ZodNanoID,o)),e.guid=o=>e.check(_guid(ZodGUID,o)),e.cuid=o=>e.check(_cuid(ZodCUID,o)),e.cuid2=o=>e.check(_cuid2(ZodCUID2,o)),e.ulid=o=>e.check(_ulid(ZodULID,o)),e.base64=o=>e.check(_base64(ZodBase64,o)),e.base64url=o=>e.check(_base64url(ZodBase64URL,o)),e.xid=o=>e.check(_xid(ZodXID,o)),e.ksuid=o=>e.check(_ksuid(ZodKSUID,o)),e.ipv4=o=>e.check(_ipv4(ZodIPv4,o)),e.ipv6=o=>e.check(_ipv6(ZodIPv6,o)),e.cidrv4=o=>e.check(_cidrv4(ZodCIDRv4,o)),e.cidrv6=o=>e.check(_cidrv6(ZodCIDRv6,o)),e.e164=o=>e.check(_e164(ZodE164,o)),e.datetime=o=>e.check(datetime(o)),e.date=o=>e.check(date(o)),e.time=o=>e.check(time(o)),e.duration=o=>e.check(duration(o))});function string(e){return _string(ZodString,e)}a(string,"string");const ZodStringFormat=$constructor("ZodStringFormat",(e,t)=>{$ZodStringFormat.init(e,t),_ZodString.init(e,t)}),ZodEmail=$constructor("ZodEmail",(e,t)=>{$ZodEmail.init(e,t),ZodStringFormat.init(e,t)}),ZodGUID=$constructor("ZodGUID",(e,t)=>{$ZodGUID.init(e,t),ZodStringFormat.init(e,t)}),ZodUUID=$constructor("ZodUUID",(e,t)=>{$ZodUUID.init(e,t),ZodStringFormat.init(e,t)}),ZodURL=$constructor("ZodURL",(e,t)=>{$ZodURL.init(e,t),ZodStringFormat.init(e,t)}),ZodEmoji=$constructor("ZodEmoji",(e,t)=>{$ZodEmoji.init(e,t),ZodStringFormat.init(e,t)}),ZodNanoID=$constructor("ZodNanoID",(e,t)=>{$ZodNanoID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID=$constructor("ZodCUID",(e,t)=>{$ZodCUID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID2=$constructor("ZodCUID2",(e,t)=>{$ZodCUID2.init(e,t),ZodStringFormat.init(e,t)}),ZodULID=$constructor("ZodULID",(e,t)=>{$ZodULID.init(e,t),ZodStringFormat.init(e,t)}),ZodXID=$constructor("ZodXID",(e,t)=>{$ZodXID.init(e,t),ZodStringFormat.init(e,t)}),ZodKSUID=$constructor("ZodKSUID",(e,t)=>{$ZodKSUID.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv4=$constructor("ZodIPv4",(e,t)=>{$ZodIPv4.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv6=$constructor("ZodIPv6",(e,t)=>{$ZodIPv6.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv4=$constructor("ZodCIDRv4",(e,t)=>{$ZodCIDRv4.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv6=$constructor("ZodCIDRv6",(e,t)=>{$ZodCIDRv6.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64=$constructor("ZodBase64",(e,t)=>{$ZodBase64.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64URL=$constructor("ZodBase64URL",(e,t)=>{$ZodBase64URL.init(e,t),ZodStringFormat.init(e,t)}),ZodE164=$constructor("ZodE164",(e,t)=>{$ZodE164.init(e,t),ZodStringFormat.init(e,t)}),ZodJWT=$constructor("ZodJWT",(e,t)=>{$ZodJWT.init(e,t),ZodStringFormat.init(e,t)}),ZodNumber=$constructor("ZodNumber",(e,t)=>{$ZodNumber.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(n,r,i)=>numberProcessor(e,n,r),e.gt=(n,r)=>e.check(_gt(n,r)),e.gte=(n,r)=>e.check(_gte(n,r)),e.min=(n,r)=>e.check(_gte(n,r)),e.lt=(n,r)=>e.check(_lt(n,r)),e.lte=(n,r)=>e.check(_lte(n,r)),e.max=(n,r)=>e.check(_lte(n,r)),e.int=n=>e.check(int(n)),e.safe=n=>e.check(int(n)),e.positive=n=>e.check(_gt(0,n)),e.nonnegative=n=>e.check(_gte(0,n)),e.negative=n=>e.check(_lt(0,n)),e.nonpositive=n=>e.check(_lte(0,n)),e.multipleOf=(n,r)=>e.check(_multipleOf(n,r)),e.step=(n,r)=>e.check(_multipleOf(n,r)),e.finite=()=>e;const o=e._zod.bag;e.minValue=Math.max(o.minimum??Number.NEGATIVE_INFINITY,o.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(o.maximum??Number.POSITIVE_INFINITY,o.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(o.format??"").includes("int")||Number.isSafeInteger(o.multipleOf??.5),e.isFinite=!0,e.format=o.format??null});function number(e){return _number(ZodNumber,e)}a(number,"number");const ZodNumberFormat=$constructor("ZodNumberFormat",(e,t)=>{$ZodNumberFormat.init(e,t),ZodNumber.init(e,t)});function int(e){return _int(ZodNumberFormat,e)}a(int,"int");const ZodBoolean=$constructor("ZodBoolean",(e,t)=>{$ZodBoolean.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>booleanProcessor(e,o,n)});function boolean(e){return _boolean(ZodBoolean,e)}a(boolean,"boolean");const ZodUnknown=$constructor("ZodUnknown",(e,t)=>{$ZodUnknown.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>unknownProcessor()});function unknown(){return _unknown(ZodUnknown)}a(unknown,"unknown");const ZodNever=$constructor("ZodNever",(e,t)=>{$ZodNever.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>neverProcessor(e,o,n)});function never(e){return _never(ZodNever,e)}a(never,"never");const ZodArray=$constructor("ZodArray",(e,t)=>{$ZodArray.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>arrayProcessor(e,o,n,r),e.element=t.element,e.min=(o,n)=>e.check(_minLength(o,n)),e.nonempty=o=>e.check(_minLength(1,o)),e.max=(o,n)=>e.check(_maxLength(o,n)),e.length=(o,n)=>e.check(_length(o,n)),e.unwrap=()=>e.element});function array(e,t){return _array(ZodArray,e,t)}a(array,"array");const ZodObject=$constructor("ZodObject",(e,t)=>{$ZodObjectJIT.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>objectProcessor(e,o,n,r),defineLazy(e,"shape",()=>t.shape),e.keyof=()=>_enum(Object.keys(e._zod.def.shape)),e.catchall=o=>e.clone({...e._zod.def,catchall:o}),e.passthrough=()=>e.clone({...e._zod.def,catchall:unknown()}),e.loose=()=>e.clone({...e._zod.def,catchall:unknown()}),e.strict=()=>e.clone({...e._zod.def,catchall:never()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=o=>extend(e,o),e.safeExtend=o=>safeExtend(e,o),e.merge=o=>merge(e,o),e.pick=o=>pick(e,o),e.omit=o=>omit(e,o),e.partial=(...o)=>partial(ZodOptional,e,o[0]),e.required=(...o)=>required(ZodNonOptional,e,o[0])});function object(e,t){const o={type:"object",shape:e??{},...normalizeParams(t)};return new ZodObject(o)}a(object,"object");const ZodUnion=$constructor("ZodUnion",(e,t)=>{$ZodUnion.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>unionProcessor(e,o,n,r),e.options=t.options});function union(e,t){return new ZodUnion({type:"union",options:e,...normalizeParams(t)})}a(union,"union");const ZodIntersection=$constructor("ZodIntersection",(e,t)=>{$ZodIntersection.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>intersectionProcessor(e,o,n,r)});function intersection(e,t){return new ZodIntersection({type:"intersection",left:e,right:t})}a(intersection,"intersection");const ZodEnum=$constructor("ZodEnum",(e,t)=>{$ZodEnum.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(n,r,i)=>enumProcessor(e,n,r),e.enum=t.entries,e.options=Object.values(t.entries);const o=new Set(Object.keys(t.entries));e.extract=(n,r)=>{const i={};for(const s of n)if(o.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new ZodEnum({...t,checks:[],...normalizeParams(r),entries:i})},e.exclude=(n,r)=>{const i={...t.entries};for(const s of n)if(o.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new ZodEnum({...t,checks:[],...normalizeParams(r),entries:i})}});function _enum(e,t){const o=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new ZodEnum({type:"enum",entries:o,...normalizeParams(t)})}a(_enum,"_enum");const ZodTransform=$constructor("ZodTransform",(e,t)=>{$ZodTransform.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>transformProcessor(e,o),e._zod.parse=(o,n)=>{if(n.direction==="backward")throw new $ZodEncodeError(e.constructor.name);o.addIssue=i=>{if(typeof i=="string")o.issues.push(issue(i,o.value,t));else{const s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=o.value),s.inst??(s.inst=e),o.issues.push(issue(s))}};const r=t.transform(o.value,o);return r instanceof Promise?r.then(i=>(o.value=i,o)):(o.value=r,o)}});function transform(e){return new ZodTransform({type:"transform",transform:e})}a(transform,"transform");const ZodOptional=$constructor("ZodOptional",(e,t)=>{$ZodOptional.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>optionalProcessor(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function optional(e){return new ZodOptional({type:"optional",innerType:e})}a(optional,"optional");const ZodExactOptional=$constructor("ZodExactOptional",(e,t)=>{$ZodExactOptional.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>optionalProcessor(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function exactOptional(e){return new ZodExactOptional({type:"optional",innerType:e})}a(exactOptional,"exactOptional");const ZodNullable=$constructor("ZodNullable",(e,t)=>{$ZodNullable.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>nullableProcessor(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function nullable(e){return new ZodNullable({type:"nullable",innerType:e})}a(nullable,"nullable");const ZodDefault=$constructor("ZodDefault",(e,t)=>{$ZodDefault.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>defaultProcessor(e,o,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _default(e,t){return new ZodDefault({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():shallowClone(t)}})}a(_default,"_default");const ZodPrefault=$constructor("ZodPrefault",(e,t)=>{$ZodPrefault.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>prefaultProcessor(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function prefault(e,t){return new ZodPrefault({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():shallowClone(t)}})}a(prefault,"prefault");const ZodNonOptional=$constructor("ZodNonOptional",(e,t)=>{$ZodNonOptional.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>nonoptionalProcessor(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function nonoptional(e,t){return new ZodNonOptional({type:"nonoptional",innerType:e,...normalizeParams(t)})}a(nonoptional,"nonoptional");const ZodCatch=$constructor("ZodCatch",(e,t)=>{$ZodCatch.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>catchProcessor(e,o,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _catch(e,t){return new ZodCatch({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}a(_catch,"_catch");const ZodPipe=$constructor("ZodPipe",(e,t)=>{$ZodPipe.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>pipeProcessor(e,o,n,r),e.in=t.in,e.out=t.out});function pipe(e,t){return new ZodPipe({type:"pipe",in:e,out:t})}a(pipe,"pipe");const ZodReadonly=$constructor("ZodReadonly",(e,t)=>{$ZodReadonly.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>readonlyProcessor(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function readonly(e){return new ZodReadonly({type:"readonly",innerType:e})}a(readonly,"readonly");const ZodCustom=$constructor("ZodCustom",(e,t)=>{$ZodCustom.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(o,n,r)=>customProcessor(e,o)});function refine(e,t={}){return _refine(ZodCustom,e,t)}a(refine,"refine");function superRefine(e){return _superRefine(e)}a(superRefine,"superRefine");const InvokeErrorType={NETWORK_ERROR:"network_error",RATE_LIMIT:"rate_limit",SERVER_ERROR:"server_error",NO_TOOL_CALL:"no_tool_call",INVALID_TOOL_ARGS:"invalid_tool_args",TOOL_EXECUTION_ERROR:"tool_execution_error",UNKNOWN:"unknown",AUTH_ERROR:"auth_error",CONTEXT_LENGTH:"context_length",CONTENT_FILTER:"content_filter"},at=class at extends Error{type;retryable;statusCode;rawError;rawResponse;constructor(t,o,n,r){super(o),this.name="InvokeError",this.type=t,this.retryable=this.isRetryable(t,n),this.rawError=n,this.rawResponse=r}isRetryable(t,o){return o?.name==="AbortError"?!1:[InvokeErrorType.NETWORK_ERROR,InvokeErrorType.RATE_LIMIT,InvokeErrorType.SERVER_ERROR,InvokeErrorType.NO_TOOL_CALL,InvokeErrorType.INVALID_TOOL_ARGS,InvokeErrorType.TOOL_EXECUTION_ERROR,InvokeErrorType.UNKNOWN].includes(t)}};a(at,"InvokeError");let InvokeError=at;const ANSI_BACKGROUND_OFFSET=10,wrapAnsi16=a((e=0)=>t=>`\x1B[${t+e}m`,"wrapAnsi16"),wrapAnsi256=a((e=0)=>t=>`\x1B[${38+e};5;${t}m`,"wrapAnsi256"),wrapAnsi16m=a((e=0)=>(t,o,n)=>`\x1B[${38+e};2;${t};${o};${n}m`,"wrapAnsi16m"),styles$3={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(styles$3.modifier);const foregroundColorNames=Object.keys(styles$3.color),backgroundColorNames=Object.keys(styles$3.bgColor);[...foregroundColorNames,...backgroundColorNames];function assembleStyles(){const e=new Map;for(const[t,o]of Object.entries(styles$3)){for(const[n,r]of Object.entries(o))styles$3[n]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},o[n]=styles$3[n],e.set(r[0],r[1]);Object.defineProperty(styles$3,t,{value:o,enumerable:!1})}return Object.defineProperty(styles$3,"codes",{value:e,enumerable:!1}),styles$3.color.close="\x1B[39m",styles$3.bgColor.close="\x1B[49m",styles$3.color.ansi=wrapAnsi16(),styles$3.color.ansi256=wrapAnsi256(),styles$3.color.ansi16m=wrapAnsi16m(),styles$3.bgColor.ansi=wrapAnsi16(ANSI_BACKGROUND_OFFSET),styles$3.bgColor.ansi256=wrapAnsi256(ANSI_BACKGROUND_OFFSET),styles$3.bgColor.ansi16m=wrapAnsi16m(ANSI_BACKGROUND_OFFSET),Object.defineProperties(styles$3,{rgbToAnsi256:{value(t,o,n){return t===o&&o===n?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(o/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(t){const o=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!o)return[0,0,0];let[n]=o;n.length===3&&(n=[...n].map(i=>i+i).join(""));const r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:a(t=>styles$3.rgbToAnsi256(...styles$3.hexToRgb(t)),"value"),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let o,n,r;if(t>=232)o=((t-232)*10+8)/255,n=o,r=o;else{t-=16;const c=t%36;o=Math.floor(t/36)/5,n=Math.floor(c/6)/5,r=c%6/5}const i=Math.max(o,n,r)*2;if(i===0)return 30;let s=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(o));return i===2&&(s+=60),s},enumerable:!1},rgbToAnsi:{value:a((t,o,n)=>styles$3.ansi256ToAnsi(styles$3.rgbToAnsi256(t,o,n)),"value"),enumerable:!1},hexToAnsi:{value:a(t=>styles$3.ansi256ToAnsi(styles$3.hexToAnsi256(t)),"value"),enumerable:!1}}),styles$3}a(assembleStyles,"assembleStyles");const ansiStyles=assembleStyles(),level=(()=>{if(!("navigator"in globalThis))return 0;if(globalThis.navigator.userAgentData){const e=navigator.userAgentData.brands.find(({brand:t})=>t==="Chromium");if(e&&e.version>93)return 3}return/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)?1:0})(),colorSupport=level!==0&&{level},supportsColor={stdout:colorSupport,stderr:colorSupport};function stringReplaceAll(e,t,o){let n=e.indexOf(t);if(n===-1)return e;const r=t.length;let i=0,s="";do s+=e.slice(i,n)+t+o,i=n+r,n=e.indexOf(t,i);while(n!==-1);return s+=e.slice(i),s}a(stringReplaceAll,"stringReplaceAll");function stringEncaseCRLFWithFirstIndex(e,t,o,n){let r=0,i="";do{const s=e[n-1]==="\r";i+=e.slice(r,s?n-1:n)+t+(s?`\r
`:`
`)+o,r=n+1,n=e.indexOf(`
`,r)}while(n!==-1);return i+=e.slice(r),i}a(stringEncaseCRLFWithFirstIndex,"stringEncaseCRLFWithFirstIndex");const{stdout:stdoutColor,stderr:stderrColor}=supportsColor,GENERATOR=Symbol("GENERATOR"),STYLER=Symbol("STYLER"),IS_EMPTY=Symbol("IS_EMPTY"),levelMapping=["ansi","ansi","ansi256","ansi16m"],styles$2=Object.create(null),applyOptions=a((e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const o=stdoutColor?stdoutColor.level:0;e.level=t.level===void 0?o:t.level},"applyOptions"),chalkFactory=a(e=>{const t=a((...o)=>o.join(" "),"chalk");return applyOptions(t,e),Object.setPrototypeOf(t,createChalk.prototype),t},"chalkFactory");function createChalk(e){return chalkFactory(e)}a(createChalk,"createChalk"),Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(const[e,t]of Object.entries(ansiStyles))styles$2[e]={get(){const o=createBuilder(this,createStyler(t.open,t.close,this[STYLER]),this[IS_EMPTY]);return Object.defineProperty(this,e,{value:o}),o}};styles$2.visible={get(){const e=createBuilder(this,this[STYLER],!0);return Object.defineProperty(this,"visible",{value:e}),e}};const getModelAnsi=a((e,t,o,...n)=>e==="rgb"?t==="ansi16m"?ansiStyles[o].ansi16m(...n):t==="ansi256"?ansiStyles[o].ansi256(ansiStyles.rgbToAnsi256(...n)):ansiStyles[o].ansi(ansiStyles.rgbToAnsi(...n)):e==="hex"?getModelAnsi("rgb",t,o,...ansiStyles.hexToRgb(...n)):ansiStyles[o][e](...n),"getModelAnsi"),usedModels=["rgb","hex","ansi256"];for(const e of usedModels){styles$2[e]={get(){const{level:o}=this;return function(...n){const r=createStyler(getModelAnsi(e,levelMapping[o],"color",...n),ansiStyles.color.close,this[STYLER]);return createBuilder(this,r,this[IS_EMPTY])}}};const t="bg"+e[0].toUpperCase()+e.slice(1);styles$2[t]={get(){const{level:o}=this;return function(...n){const r=createStyler(getModelAnsi(e,levelMapping[o],"bgColor",...n),ansiStyles.bgColor.close,this[STYLER]);return createBuilder(this,r,this[IS_EMPTY])}}}}const proto=Object.defineProperties(()=>{},{...styles$2,level:{enumerable:!0,get(){return this[GENERATOR].level},set(e){this[GENERATOR].level=e}}}),createStyler=a((e,t,o)=>{let n,r;return o===void 0?(n=e,r=t):(n=o.openAll+e,r=t+o.closeAll),{open:e,close:t,openAll:n,closeAll:r,parent:o}},"createStyler"),createBuilder=a((e,t,o)=>{const n=a((...r)=>applyStyle(n,r.length===1?""+r[0]:r.join(" ")),"builder");return Object.setPrototypeOf(n,proto),n[GENERATOR]=e,n[STYLER]=t,n[IS_EMPTY]=o,n},"createBuilder"),applyStyle=a((e,t)=>{if(e.level<=0||!t)return e[IS_EMPTY]?"":t;let o=e[STYLER];if(o===void 0)return t;const{openAll:n,closeAll:r}=o;if(t.includes("\x1B"))for(;o!==void 0;)t=stringReplaceAll(t,o.close,o.open),o=o.parent;const i=t.indexOf(`
`);return i!==-1&&(t=stringEncaseCRLFWithFirstIndex(t,r,n,i)),n+t+r},"applyStyle");Object.defineProperties(createChalk.prototype,styles$2);const chalk=createChalk();createChalk({level:stderrColor?stderrColor.level:0});const debug=console.debug.bind(console,chalk.gray("[LLM]"));function zodToOpenAITool(e,t){return{type:"function",function:{name:e,description:t.description,parameters:toJSONSchema(t.inputSchema,{target:"openapi-3.0"})}}}a(zodToOpenAITool,"zodToOpenAITool");function modelPatch(e){const t=e.model||"";if(!t)return e;const o=normalizeModelName(t);return o.startsWith("qwen")&&(debug("Applying Qwen patch: use higher temperature for auto fixing"),e.temperature=Math.max(e.temperature||0,1),e.enable_thinking=!1),o.startsWith("claude")&&(debug("Applying Claude patch: disable thinking"),e.thinking={type:"disabled"},e.tool_choice==="required"?(debug('Applying Claude patch: convert tool_choice "required" to { type: "any" }'),e.tool_choice={type:"any"}):e.tool_choice?.function?.name&&(debug("Applying Claude patch: convert tool_choice format"),e.tool_choice={type:"tool",name:e.tool_choice.function.name})),o.startsWith("grok")&&(debug("Applying Grok patch: removing tool_choice"),delete e.tool_choice,debug("Applying Grok patch: disable reasoning and thinking"),e.thinking={type:"disabled",effort:"minimal"},e.reasoning={enabled:!1,effort:"low"}),o.startsWith("gpt")&&(debug("Applying GPT patch: set verbosity to low"),e.verbosity="low",o.startsWith("gpt-52")?(debug("Applying GPT-52 patch: disable reasoning"),e.reasoning_effort="none"):o.startsWith("gpt-51")?(debug("Applying GPT-51 patch: disable reasoning"),e.reasoning_effort="none"):o.startsWith("gpt-54")?(debug("Applying GPT-5.4 patch: skip reasoning_effort because chat/completions rejects it with function tools"),delete e.reasoning_effort):o.startsWith("gpt-5-mini")?(debug("Applying GPT-5-mini patch: set reasoning effort to low, temperature to 1"),e.reasoning_effort="low",e.temperature=1):o.startsWith("gpt-5")&&(debug("Applying GPT-5 patch: set reasoning effort to low"),e.reasoning_effort="low")),o.startsWith("gemini")&&(debug("Applying Gemini patch: set reasoning effort to minimal"),e.reasoning_effort="minimal"),e}a(modelPatch,"modelPatch");function normalizeModelName(e){let t=e.toLowerCase();return t.includes("/")&&(t=t.split("/")[1]),t=t.replace(/_/g,""),t=t.replace(/\./g,""),t}a(normalizeModelName,"normalizeModelName");const ct=class ct{config;fetch;constructor(t){this.config=t,this.fetch=t.customFetch}async invoke(t,o,n,r){const i=Object.entries(o).map(([v,k])=>zodToOpenAITool(v,k)),s={model:this.config.model,temperature:this.config.temperature,messages:t,tools:i,parallel_tool_calls:!1,tool_choice:r?.toolChoiceName?{type:"function",function:{name:r.toolChoiceName}}:"required"};modelPatch(s);let c;try{c=await this.fetch(`${this.config.baseURL}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(s),signal:n})}catch(v){const k=v?.name==="AbortError",O=k?"Network request aborted":"Network request failed";throw k||console.error(v),new InvokeError(InvokeErrorType.NETWORK_ERROR,O,v)}if(!c.ok){const v=await c.json().catch(),k=v.error?.message||c.statusText;throw c.status===401||c.status===403?new InvokeError(InvokeErrorType.AUTH_ERROR,`Authentication failed: ${k}`,v):c.status===429?new InvokeError(InvokeErrorType.RATE_LIMIT,`Rate limit exceeded: ${k}`,v):c.status>=500?new InvokeError(InvokeErrorType.SERVER_ERROR,`Server error: ${k}`,v):new InvokeError(InvokeErrorType.UNKNOWN,`HTTP ${c.status}: ${k}`,v)}const l=await c.json(),d=l.choices?.[0];if(!d)throw new InvokeError(InvokeErrorType.UNKNOWN,"No choices in response",l);switch(d.finish_reason){case"tool_calls":case"function_call":case"stop":break;case"length":throw new InvokeError(InvokeErrorType.CONTEXT_LENGTH,"Response truncated: max tokens reached",void 0,l);case"content_filter":throw new InvokeError(InvokeErrorType.CONTENT_FILTER,"Content filtered by safety system",void 0,l);default:throw new InvokeError(InvokeErrorType.UNKNOWN,`Unexpected finish_reason: ${d.finish_reason}`,void 0,l)}const f=(r?.normalizeResponse?r.normalizeResponse(l):l).choices?.[0],g=f?.message?.tool_calls?.[0]?.function?.name;if(!g)throw new InvokeError(InvokeErrorType.NO_TOOL_CALL,"No tool call found in response",void 0,l);const m=o[g];if(!m)throw new InvokeError(InvokeErrorType.UNKNOWN,`Tool "${g}" not found in tools`,void 0,l);const T=f.message?.tool_calls?.[0]?.function?.arguments;if(!T)throw new InvokeError(InvokeErrorType.INVALID_TOOL_ARGS,"No tool call arguments found",void 0,l);let I;try{I=JSON.parse(T)}catch(v){throw new InvokeError(InvokeErrorType.INVALID_TOOL_ARGS,"Failed to parse tool arguments as JSON",v,l)}const A=m.inputSchema.safeParse(I);if(!A.success)throw console.error(prettifyError(A.error)),new InvokeError(InvokeErrorType.INVALID_TOOL_ARGS,"Tool arguments validation failed",A.error,l);const C=A.data;let D;try{D=await m.execute(C)}catch(v){throw new InvokeError(InvokeErrorType.TOOL_EXECUTION_ERROR,`Tool execution failed: ${v.message}`,v,l)}return{toolCall:{name:g,args:C},toolResult:D,usage:{promptTokens:l.usage?.prompt_tokens??0,completionTokens:l.usage?.completion_tokens??0,totalTokens:l.usage?.total_tokens??0,cachedTokens:l.usage?.prompt_tokens_details?.cached_tokens,reasoningTokens:l.usage?.completion_tokens_details?.reasoning_tokens},rawResponse:l,rawRequest:s}}};a(ct,"OpenAIClient");let OpenAIClient=ct;const LLM_MAX_RETRIES=2,DEFAULT_TEMPERATURE=.7;function parseLLMConfig(e){if(!e.baseURL||!e.apiKey||!e.model)throw new Error("[PageAgent] LLM configuration required. Please provide: baseURL, apiKey, model. See: https://alibaba.github.io/page-agent/docs/features/models");return{baseURL:e.baseURL,apiKey:e.apiKey,model:e.model,temperature:e.temperature??DEFAULT_TEMPERATURE,maxRetries:e.maxRetries??LLM_MAX_RETRIES,customFetch:(e.customFetch??fetch).bind(globalThis)}}a(parseLLMConfig,"parseLLMConfig");const lt=class lt extends EventTarget{config;client;constructor(t){super(),this.config=parseLLMConfig(t),this.client=new OpenAIClient(this.config)}async invoke(t,o,n,r){return await withRetry(async()=>{if(n.aborted)throw new Error("AbortError");return await this.client.invoke(t,o,n,r)},{maxRetries:this.config.maxRetries,onRetry:a(i=>{this.dispatchEvent(new CustomEvent("retry",{detail:{attempt:i,maxAttempts:this.config.maxRetries}}))},"onRetry"),onError:a(i=>{this.dispatchEvent(new CustomEvent("error",{detail:{error:i}}))},"onError")})}};a(lt,"LLM");let LLM=lt;async function withRetry(e,t){let o=0,n=null;for(;o<=t.maxRetries;){o>0&&(t.onRetry(o),await new Promise(r=>setTimeout(r,100)));try{return await e()}catch(r){if(r?.rawError?.name==="AbortError"||(console.error(r),t.onError(r),r instanceof InvokeError&&!r.retryable))throw r;n=r,o++,await new Promise(i=>setTimeout(i,100))}}throw n}a(withRetry,"withRetry");const SYSTEM_PROMPT=`You are an AI agent designed to operate in an iterative loop to automate browser tasks. Your ultimate goal is accomplishing the task provided in <user_request>.

<intro>
You excel at following tasks:
1. Navigating complex websites and extracting precise information
2. Automating form submissions and interactive web actions
3. Gathering and saving information 
4. Operate effectively in an agent loop
5. Efficiently performing diverse web tasks
</intro>

<language_settings>
- Default working language: **English**
- Use the language that user is using. Return in user's language.
</language_settings>

<input>
At every step, your input will consist of: 
1. <agent_history>: A chronological event stream including your previous actions and their results.
2. <agent_state>: Current <user_request> and <step_info>.
3. <browser_state>: Current URL, interactive elements indexed for actions, and visible page content.
</input>

<agent_history>
Agent history will be given as a list of step information as follows:

<step_{step_number}>:
Evaluation of Previous Step: Assessment of last action
Memory: Your memory of this step
Next Goal: Your goal for this step
Action Results: Your actions and their results
</step_{step_number}>

and system messages wrapped in <sys> tag.
</agent_history>

<user_request>
USER REQUEST: This is your ultimate objective and always remains visible.
- This has the highest priority. Make the user happy.
- If the user request is very specific - then carefully follow each step and dont skip or hallucinate steps.
- If the task is open ended you can plan yourself how to get it done.
</user_request>

<browser_state>
1. Browser State will be given as:

Current URL: URL of the page you are currently viewing.
Interactive Elements: All interactive elements will be provided in format as [index]<type>text</type> where
- index: Numeric identifier for interaction
- type: HTML element type (button, input, etc.)
- text: Element description

Examples:
[33]<div>User form</div>
\\t*[35]<button aria-label='Submit form'>Submit</button>

Note that:
- Only elements with numeric indexes in [] are interactive
- (stacked) indentation (with \\t) is important and means that the element is a (html) child of the element above (with a lower index)
- Elements tagged with \`*[\` are the new clickable elements that appeared on the website since the last step - if url has not changed.
- Pure text elements without [] are not interactive.
</browser_state>

<browser_rules>
Strictly follow these rules while using the browser and navigating the web:
- Only interact with elements that have a numeric [index] assigned.
- Only use indexes that are explicitly provided.
- If the page changes after, for example, an input text action, analyze if you need to interact with new elements, e.g. selecting the right option from the list.
- By default, only elements in the visible viewport are listed. Use scrolling actions if you suspect relevant content is offscreen which you need to interact with. Scroll ONLY if there are more pixels below or above the page.
- You can scroll by a specific number of pages using the num_pages parameter (e.g., 0.5 for half page, 2.0 for two pages).
- All the elements that are scrollable are marked with \`data-scrollable\` attribute. Including the scrollable distance in every directions. You can scroll *the element* in case some area are overflowed.
- If a captcha appears, tell user you can not solve captcha. finished the task and ask user to solve it.
- If expected elements are missing, try scrolling, or navigating back.
- If the page is not fully loaded, use the \`wait\` action.
- Do not repeat one action for more than 3 times unless some conditions changed.
- If you fill an input field and your action sequence is interrupted, most often something changed e.g. suggestions popped up under the field.
- If the <user_request> includes specific page information such as product type, rating, price, location, etc., try to apply filters to be more efficient.
- The <user_request> is the ultimate goal. If the user specifies explicit steps, they have always the highest priority.
- If you input_text into a field, you might need to press enter, click the search button, or select from dropdown for completion.
- Don't login into a page if you don't have to. Don't login if you don't have the credentials. 
- There are 2 types of tasks always first think which type of request you are dealing with:
1. Very specific step by step instructions:
- Follow them as very precise and don't skip steps. Try to complete everything as requested.
2. Open ended tasks. Plan yourself, be creative in achieving them.
- If you get stuck e.g. with logins or captcha in open-ended tasks you can re-evaluate the task and try alternative ways, e.g. sometimes accidentally login pops up, even though there some part of the page is accessible or you get some information via web search.
</browser_rules>

<capability>
- You can only handle single page app. Do not jump out of current page.
- Do not click on link if it will open in a new page (etc. <a target="_blank">)
- It is ok to fail the task.
	- User can be wrong. If the request of user is not achievable, inappropriate or you do not have enough information or tools to achieve it. Tell user to make a better request.
	- Webpage can be broken. All webpages or apps have bugs. Some bug will make it hard for your job. It's encouraged to tell user the problem of current page. Your feedbacks (including failing) are valuable for user.
	- Trying to hard can be harmful. Repeating some action back and forth or pushing for a complex procedure with little knowledge can cause unwanted result and harmful side-effects. User would rather you to complete the task with a fail.
- If you do not have knowledge for the current webpage or task. You must require user to give specific instructions and detailed steps.
</capability>

<task_completion_rules>
You must call the \`done\` action in one of three cases:
- When you have fully completed the USER REQUEST.
- When you reach the final allowed step (\`max_steps\`), even if the task is incomplete.
- When you feel stuck or unable to solve user request. Or user request is not clear or contains inappropriate content.
- If it is ABSOLUTELY IMPOSSIBLE to continue.

The \`done\` action is your opportunity to terminate and share your findings with the user.
- Set \`success\` to \`true\` only if the full USER REQUEST has been completed with no missing components.
- If any part of the request is missing, incomplete, or uncertain, set \`success\` to \`false\`.
- You can use the \`text\` field of the \`done\` action to communicate your findings and to provide a coherent reply to the user and fulfill the USER REQUEST.
- You are ONLY ALLOWED to call \`done\` as a single action. Don't call it together with other actions.
- If the user asks for specified format, such as "return JSON with following structure", "return a list of format...", MAKE sure to use the right format in your answer.
- If the user asks for a structured output, your \`done\` action's schema may be modified. Take this schema into account when solving the task!
</task_completion_rules>

<reasoning_rules>
Exhibit the following reasoning patterns to successfully achieve the <user_request>:

- Reason about <agent_history> to track progress and context toward <user_request>.
- Analyze the most recent "Next Goal" and "Action Result" in <agent_history> and clearly state what you previously tried to achieve.
- Analyze all relevant items in <agent_history> and <browser_state> to understand your state.
- Explicitly judge success/failure/uncertainty of the last action. Never assume an action succeeded just because it appears to be executed in your last step in <agent_history>. If the expected change is missing, mark the last action as failed (or uncertain) and plan a recovery.
- Analyze whether you are stuck, e.g. when you repeat the same actions multiple times without any progress. Then consider alternative approaches e.g. scrolling for more context or ask user for help.
- Ask user for help if you have any difficulty. Keep user in the loop.
- If you see information relevant to <user_request>, plan saving the information to memory.
- Always reason about the <user_request>. Make sure to carefully analyze the specific steps and information required. E.g. specific filters, specific form fields, specific information to search. Make sure to always compare the current trajectory with the user request and think carefully if thats how the user requested it.
</reasoning_rules>

<examples>
Here are examples of good output patterns. Use them as reference but never copy them directly.

<evaluation_examples>
"evaluation_previous_goal": "Successfully navigated to the product page and found the target information. Verdict: Success"
"evaluation_previous_goal": "Clicked the login button and user authentication form appeared. Verdict: Success"
</evaluation_examples>

<memory_examples>
"memory": "Found many pending reports that need to be analyzed in the main page. Successfully processed the first 2 reports on quarterly sales data and moving on to inventory analysis and customer feedback reports."
</memory_examples>

<next_goal_examples>
"next_goal": "Click on the 'Add to Cart' button to proceed with the purchase flow."
</next_goal_examples>
</examples>

<output>
{
  "evaluation_previous_goal": "Concise one-sentence analysis of your last action. Clearly state success, failure, or uncertain.",
  "memory": "1-3 concise sentences of specific memory of this step and overall progress. You should put here everything that will help you track progress in future steps. Like counting pages visited, items found, etc.",
  "next_goal": "State the next immediate goal and action to achieve it, in one clear sentence.",
  "action":{
    "Action name": {// Action parameters}
  }
}
</output>
`,log=console.log.bind(console,chalk.yellow("[autoFixer]"));function normalizeResponse(e,t){let o=null;const n=e.choices?.[0];if(!n)throw new Error("No choices in response");const r=n.message;if(!r)throw new Error("No message in choice");const i=r.tool_calls?.[0];if(i?.function?.arguments)o=safeJsonParse(i.function.arguments),i.function.name&&i.function.name!=="AgentOutput"&&(log("#1: fixing tool_call"),o={action:safeJsonParse(o)});else if(r.content){const s=r.content.trim(),c=retrieveJsonFromString(s);if(c)o=safeJsonParse(c),o?.name==="AgentOutput"&&(log("#2: fixing tool_call"),o=safeJsonParse(o.arguments)),o?.type==="function"&&(log("#3: fixing tool_call"),o=safeJsonParse(o.function.arguments)),!o?.action&&!o?.evaluation_previous_goal&&!o?.memory&&!o?.next_goal&&!o?.thinking&&(log("#4: fixing tool_call"),o={action:safeJsonParse(o)});else throw new Error("No tool_call and the message content does not contain valid JSON")}else throw new Error("No tool_call nor message content is present");return o=safeJsonParse(o),o.action&&(o.action=safeJsonParse(o.action)),o.action&&t&&(o.action=validateAction(o.action,t)),o.action||(log("#5: fixing tool_call"),o.action={name:"wait",input:{seconds:1}}),{...e,choices:[{...n,message:{...r,tool_calls:[{...i||{},function:{...i?.function||{},name:"AgentOutput",arguments:JSON.stringify(o)}}]}}]}}a(normalizeResponse,"normalizeResponse");function validateAction(e,t){if(typeof e!="object"||e===null)return e;const o=Object.keys(e)[0];if(!o)return e;const n=t.get(o);if(!n){const c=Array.from(t.keys()).join(", ");throw new InvokeError(InvokeErrorType.INVALID_TOOL_ARGS,`Unknown action "${o}". Available: ${c}`)}let r=e[o];const i=n.inputSchema;if(i instanceof ZodObject&&r!==null&&typeof r!="object"){const c=Object.keys(i.shape).find(l=>!i.shape[l].safeParse(void 0).success);c&&(log(`coercing primitive action input for "${o}"`),r={[c]:r})}const s=i.safeParse(r);if(!s.success)throw new InvokeError(InvokeErrorType.INVALID_TOOL_ARGS,`Invalid input for action "${o}": ${prettifyError(s.error)}`);return{[o]:s.data}}a(validateAction,"validateAction");function safeJsonParse(e){if(typeof e=="string")try{return JSON.parse(e.trim())}catch{return e}return e}a(safeJsonParse,"safeJsonParse");function retrieveJsonFromString(e){try{const t=/({[\s\S]*})/.exec(e)??[];return t.length===0?null:JSON.parse(t[0])}catch{return null}}a(retrieveJsonFromString,"retrieveJsonFromString");async function waitFor$1(e){await new Promise(t=>setTimeout(t,e*1e3))}a(waitFor$1,"waitFor$1");function truncate$1(e,t){return e.length>t?e.substring(0,t)+"...":e}a(truncate$1,"truncate$1");function randomID(e){let t=Math.random().toString(36).substring(2,11);if(!e)return t;const o=1e3;let n=0;for(;e.includes(t);)if(t=Math.random().toString(36).substring(2,11),n++,n>o)throw new Error("randomID: too many try");return t}a(randomID,"randomID");const _global=globalThis;_global.__PAGE_AGENT_IDS__||(_global.__PAGE_AGENT_IDS__=[]);const ids=_global.__PAGE_AGENT_IDS__;function uid(){const e=randomID(ids);return ids.push(e),e}a(uid,"uid");const llmsTxtCache=new Map;async function fetchLlmsTxt(e){const t=new URL(e).origin;if(llmsTxtCache.has(t))return llmsTxtCache.get(t);const o=`${t}/llms.txt`;let n=null;try{console.log(chalk.gray(`[llms.txt] Fetching ${o}`));const r=await fetch(o,{signal:AbortSignal.timeout(3e3)});r.ok?(n=await r.text(),console.log(chalk.green(`[llms.txt] Found (${n.length} chars)`)),n.length>1e3&&(console.log(chalk.yellow("[llms.txt] Truncating to 1000 chars")),n=truncate$1(n,1e3))):console.debug(chalk.gray(`[llms.txt] ${r.status} for ${o}`))}catch(r){console.debug(chalk.gray(`[llms.txt] not found for ${o}`),r)}return llmsTxtCache.set(t,n),n}a(fetchLlmsTxt,"fetchLlmsTxt");function assert(e,t,o){if(!e){const n=t??"Assertion failed";throw console.error(chalk.red(`❌ assert: ${n}`)),new Error(n)}}a(assert,"assert");function tool(e){return e}a(tool,"tool");const tools=new Map;tools.set("done",{description:"Complete task. Text is your final response to the user — keep it concise unless the user explicitly asks for detail.",inputSchema:object({text:string(),success:boolean().default(!0)}),execute:a(async function(e){return Promise.resolve("Task completed")},"execute")}),tools.set("wait",{description:"Wait for x seconds. Can be used to wait until the page or data is fully loaded.",inputSchema:object({seconds:number().min(1).max(10).default(1)}),execute:a(async function(e){const t=await this.pageController.getLastUpdateTime(),o=Math.max(0,e.seconds-(Date.now()-t)/1e3);return console.log(`actualWaitTime: ${o} seconds`),await waitFor$1(o),`✅ Waited for ${e.seconds} seconds.`},"execute")}),tools.set("ask_user",{description:"Ask the user a question and wait for their answer. Use this if you need more information or clarification.",inputSchema:object({question:string()}),execute:a(async function(e){if(!this.onAskUser)throw new Error("ask_user tool requires onAskUser callback to be set");return`User answered: ${await this.onAskUser(e.question)}`},"execute")}),tools.set("click_element_by_index",{description:"Click element by index",inputSchema:object({index:int().min(0)}),execute:a(async function(e){return(await this.pageController.clickElement(e.index)).message},"execute")}),tools.set("input_text",{description:"Click and type text into an interactive input element",inputSchema:object({index:int().min(0),text:string()}),execute:a(async function(e){return(await this.pageController.inputText(e.index,e.text)).message},"execute")}),tools.set("select_dropdown_option",{description:"Select dropdown option for interactive element index by the text of the option you want to select",inputSchema:object({index:int().min(0),text:string()}),execute:a(async function(e){return(await this.pageController.selectOption(e.index,e.text)).message},"execute")}),tools.set("scroll",{description:"Scroll the page vertically. Use index for scroll elements (dropdowns/custom UI).",inputSchema:object({down:boolean().default(!0),num_pages:number().min(0).max(10).optional().default(.1),pixels:number().int().min(0).optional(),index:number().int().min(0).optional()}),execute:a(async function(e){return(await this.pageController.scroll({...e,numPages:e.num_pages})).message},"execute")}),tools.set("scroll_horizontally",{description:"Scroll the page horizontally, or within a specific element by index. Useful for wide tables.",inputSchema:object({right:boolean().default(!0),pixels:number().int().min(0),index:number().int().min(0).optional()}),execute:a(async function(e){return(await this.pageController.scrollHorizontally(e)).message},"execute")}),tools.set("execute_javascript",{description:"Execute JavaScript code on the current page. Supports async/await syntax. Use with caution!",inputSchema:object({script:string()}),execute:a(async function(e){return(await this.pageController.executeJavascript(e.script)).message},"execute")});const ut=class ut extends EventTarget{constructor(o){super();Z(this,R);oe(this,"id",uid());oe(this,"config");oe(this,"tools");oe(this,"pageController");oe(this,"task","");oe(this,"taskId","");oe(this,"history",[]);oe(this,"disposed",!1);oe(this,"onAskUser");Z(this,Ue,"idle");Z(this,Oe);Z(this,se,new AbortController);Z(this,Ee,[]);Z(this,X,{totalWaitTime:0,lastURL:"",browserState:null});if(this.config={...o,maxSteps:o.maxSteps??40},S(this,Oe,new LLM(this.config)),this.tools=new Map(tools),this.pageController=o.pageController,p(this,Oe).addEventListener("retry",n=>{const{attempt:r,maxAttempts:i}=n.detail;b(this,R,Me).call(this,{type:"retrying",attempt:r,maxAttempts:i}),this.history.push({type:"retry",message:`LLM retry attempt ${r} of ${i}`,attempt:r,maxAttempts:i}),b(this,R,Pe).call(this)}),p(this,Oe).addEventListener("error",n=>{const r=n.detail.error;if(r?.rawError?.name==="AbortError")return;const i=String(r);b(this,R,Me).call(this,{type:"error",message:i}),this.history.push({type:"error",message:i,rawResponse:r.rawResponse}),b(this,R,Pe).call(this)}),this.config.customTools)for(const[n,r]of Object.entries(this.config.customTools)){if(r===null){this.tools.delete(n);continue}this.tools.set(n,r)}this.config.experimentalScriptExecutionTool||this.tools.delete("execute_javascript")}get status(){return p(this,Ue)}pushObservation(o){p(this,Ee).push(o)}stop(){this.pageController.cleanUpHighlights(),this.pageController.hideMask(),p(this,se).abort()}async execute(o){if(this.disposed)throw new Error("PageAgent has been disposed. Create a new instance.");if(!o)throw new Error("Task is required");this.task=o,this.taskId=uid(),this.onAskUser||this.tools.delete("ask_user");const n=this.config.onBeforeStep,r=this.config.onAfterStep,i=this.config.onBeforeTask,s=this.config.onAfterTask;await i?.(this),await this.pageController.showMask(),p(this,se)&&(p(this,se).abort(),S(this,se,new AbortController)),this.history=[],b(this,R,_t).call(this,"running"),b(this,R,Pe).call(this),S(this,Ee,[]),S(this,X,{totalWaitTime:0,lastURL:"",browserState:null});let c=0;for(;;){try{console.group(`step: ${c}`),await n?.(this,c),console.log(chalk.blue.bold("👀 Observing...")),p(this,X).browserState=await this.pageController.getBrowserState(),await b(this,R,At).call(this,c);const l=[{role:"system",content:b(this,R,It).call(this)},{role:"user",content:await b(this,R,Pt).call(this)}],d={AgentOutput:b(this,R,Tt).call(this)};console.log(chalk.blue.bold("🧠 Thinking...")),b(this,R,Me).call(this,{type:"thinking"});const h=await p(this,Oe).invoke(l,d,p(this,se).signal,{toolChoiceName:"AgentOutput",normalizeResponse:a(C=>normalizeResponse(C,this.tools),"normalizeResponse")}),f=h.toolResult,g=f.input,m=f.output,T={evaluation_previous_goal:g.evaluation_previous_goal,memory:g.memory,next_goal:g.next_goal},I=Object.keys(g.action)[0],A={name:I,input:g.action[I],output:m};if(this.history.push({type:"step",stepIndex:c,reflection:T,action:A,usage:h.usage,rawResponse:h.rawResponse,rawRequest:h.rawRequest}),b(this,R,Pe).call(this),await r?.(this,this.history),console.groupEnd(),I==="done"){const C=A.input?.success??!1,D=A.input?.text||"no text provided";console.log(chalk.green.bold("Task completed"),C,D),b(this,R,st).call(this,C);const v={success:C,data:D,history:this.history};return await s?.(this,v),v}}catch(l){console.groupEnd();const d=l?.rawError?.name==="AbortError";console.error("Task failed",l);const h=d?"Task stopped":String(l);b(this,R,Me).call(this,{type:"error",message:h}),this.history.push({type:"error",message:h,rawResponse:l}),b(this,R,Pe).call(this),b(this,R,st).call(this,!1);const f={success:!1,data:h,history:this.history};return await s?.(this,f),f}if(c++,c>this.config.maxSteps){const l="Step count exceeded maximum limit";this.history.push({type:"error",message:l}),b(this,R,Pe).call(this),b(this,R,st).call(this,!1);const d={success:!1,data:l,history:this.history};return await s?.(this,d),d}await waitFor$1(.4)}}dispose(){console.log("Disposing PageAgent..."),this.disposed=!0,this.pageController.dispose(),p(this,se).abort(),this.dispatchEvent(new Event("dispose")),this.config.onDispose?.(this)}};Ue=new WeakMap,Oe=new WeakMap,se=new WeakMap,Ee=new WeakMap,X=new WeakMap,R=new WeakSet,St=a(function(){this.dispatchEvent(new Event("statuschange"))},"#emitStatusChange"),Pe=a(function(){this.dispatchEvent(new Event("historychange"))},"#emitHistoryChange"),Me=a(function(o){this.dispatchEvent(new CustomEvent("activity",{detail:o}))},"#emitActivity"),_t=a(function(o){p(this,Ue)!==o&&(S(this,Ue,o),b(this,R,St).call(this))},"#setStatus"),Tt=a(function(){const o=this.tools,n=Array.from(o.entries()).map(([s,c])=>object({[s]:c.inputSchema}).describe(c.description)),r=union(n);return{description:"You MUST call this tool every step!",inputSchema:object({evaluation_previous_goal:string().optional(),memory:string().optional(),next_goal:string().optional(),action:r}),execute:a(async s=>{if(p(this,se).signal.aborted)throw new Error("AbortError");console.log(chalk.blue.bold("MacroTool input"),s);const c=s.action,l=Object.keys(c)[0],d=c[l],h=[];s.evaluation_previous_goal&&h.push(`✅: ${s.evaluation_previous_goal}`),s.memory&&h.push(`💾: ${s.memory}`),s.next_goal&&h.push(`🎯: ${s.next_goal}`);const f=h.length>0?h.join(`
`):"";f&&console.log(f);const g=o.get(l);assert(g,`Tool ${l} not found`),console.log(chalk.blue.bold(`Executing tool: ${l}`),d),b(this,R,Me).call(this,{type:"executing",tool:l,input:d});const m=Date.now(),T=await g.execute.bind(this)(d),I=Date.now()-m;return console.log(chalk.green.bold(`Tool (${l}) executed for ${I}ms`),T),b(this,R,Me).call(this,{type:"executed",tool:l,input:d,output:T,duration:I}),l==="wait"?p(this,X).totalWaitTime+=d?.seconds||0:p(this,X).totalWaitTime=0,{input:s,output:T}},"execute")}},"#packMacroTool"),It=a(function(){if(this.config.customSystemPrompt)return this.config.customSystemPrompt;const o=this.config.language==="zh-CN"?"中文":"English";return SYSTEM_PROMPT.replace(/Default working language: \*\*.*?\*\*/,`Default working language: **${o}**`)},"#getSystemPrompt"),zt=a(async function(){const{instructions:o,experimentalLlmsTxt:n}=this.config,r=o?.system?.trim();let i;const s=p(this,X).browserState?.url||"";if(o?.getPageInstructions&&s)try{i=o.getPageInstructions(s)?.trim()}catch(d){console.error(chalk.red("[PageAgent] Failed to execute getPageInstructions callback:"),d)}const c=n&&s?await fetchLlmsTxt(s):void 0;if(!r&&!i&&!c)return"";let l=`<instructions>
`;return r&&(l+=`<system_instructions>
${r}
</system_instructions>
`),i&&(l+=`<page_instructions>
${i}
</page_instructions>
`),c&&(l+=`<llms_txt>
${c}
</llms_txt>
`),l+=`</instructions>

`,l},"#getInstructions"),At=a(async function(o){p(this,X).totalWaitTime>=3&&this.pushObservation(`You have waited ${p(this,X).totalWaitTime} seconds accumulatively. DO NOT wait any longer unless you have a good reason.`);const n=p(this,X).browserState?.url||"";n!==p(this,X).lastURL&&(this.pushObservation(`Page navigated to → ${n}`),p(this,X).lastURL=n,await waitFor$1(.5));const r=this.config.maxSteps-o;if(r===5?this.pushObservation(`⚠️ Only ${r} steps remaining. Consider wrapping up or calling done with partial results.`):r===2&&this.pushObservation(`⚠️ Critical: Only ${r} steps left! You must finish the task or call done immediately.`),p(this,Ee).length>0){for(const i of p(this,Ee))this.history.push({type:"observation",content:i}),console.log(chalk.cyan("Observation:"),i);S(this,Ee,[]),b(this,R,Pe).call(this)}},"#handleObservations"),Pt=a(async function(){const o=p(this,X).browserState;let n="";n+=await b(this,R,zt).call(this);const r=this.history.filter(c=>c.type==="step").length;n+=`<agent_state>
`,n+=`<user_request>
`,n+=`${this.task}
`,n+=`</user_request>
`,n+=`<step_info>
`,n+=`Step ${r+1} of ${this.config.maxSteps} max possible steps
`,n+=`Current time: ${new Date().toLocaleString()}
`,n+=`</step_info>
`,n+=`</agent_state>

`,n+=`<agent_history>
`;let i=0;for(const c of this.history)c.type==="step"?(i++,n+=`<step_${i}>
`,n+=`Evaluation of Previous Step: ${c.reflection.evaluation_previous_goal}
`,n+=`Memory: ${c.reflection.memory}
`,n+=`Next Goal: ${c.reflection.next_goal}
`,n+=`Action Results: ${c.action.output}
`,n+=`</step_${i}>
`):c.type==="observation"?n+=`<sys>${c.content}</sys>
`:c.type==="user_takeover"?n+=`<sys>User took over control and made changes to the page</sys>
`:c.type;n+=`</agent_history>

`;let s=o.content;return this.config.transformPageContent&&(s=await this.config.transformPageContent(s)),n+=`<browser_state>
`,n+=o.header+`
`,n+=s+`
`,n+=o.footer+`

`,n+=`</browser_state>

`,n},"#assembleUserPrompt"),st=a(function(o=!0){this.pageController.cleanUpHighlights(),this.pageController.hideMask(),b(this,R,_t).call(this,o?"completed":"error"),p(this,se).abort()},"#onDone"),a(ut,"PageAgentCore");let PageAgentCore=ut;async function waitFor(e){await new Promise(t=>setTimeout(t,e*1e3))}a(waitFor,"waitFor");async function movePointerToElement(e){const t=e.getBoundingClientRect(),o=t.left+t.width/2,n=t.top+t.height/2;window.dispatchEvent(new CustomEvent("PageAgent::MovePointerTo",{detail:{x:o,y:n}})),await waitFor(.3)}a(movePointerToElement,"movePointerToElement");function getElementByIndex(e,t){const o=e.get(t);if(!o)throw new Error(`No interactive element found at index ${t}`);const n=o.ref;if(!n)throw new Error(`Element at index ${t} does not have a reference`);if(!(n instanceof HTMLElement))throw new Error(`Element at index ${t} is not an HTMLElement`);return n}a(getElementByIndex,"getElementByIndex");let lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&(lastClickedElement.blur(),lastClickedElement.dispatchEvent(new MouseEvent("mouseout",{bubbles:!0,cancelable:!0})),lastClickedElement=null)}a(blurLastClickedElement,"blurLastClickedElement");async function clickElement(e){blurLastClickedElement(),lastClickedElement=e,await scrollIntoViewIfNeeded(e),await movePointerToElement(e),window.dispatchEvent(new CustomEvent("PageAgent::ClickPointer")),await waitFor(.1),e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:!0,cancelable:!0})),e.dispatchEvent(new MouseEvent("mouseover",{bubbles:!0,cancelable:!0})),e.dispatchEvent(new MouseEvent("mousedown",{bubbles:!0,cancelable:!0})),e.focus(),e.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0})),e.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0})),await waitFor(.2)}a(clickElement,"clickElement");const nativeInputValueSetter=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value").set,nativeTextAreaValueSetter=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value").set;async function inputTextElement(e,t){const o=e.isContentEditable;if(!(e instanceof HTMLInputElement)&&!(e instanceof HTMLTextAreaElement)&&!o)throw new Error("Element is not an input, textarea, or contenteditable");await clickElement(e),o?(e.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"deleteContent"}))&&(e.innerText="",e.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"deleteContent"}))),e.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"insertText",data:t}))&&(e.innerText=t,e.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"insertText",data:t}))),e.dispatchEvent(new Event("change",{bubbles:!0})),e.blur()):e instanceof HTMLTextAreaElement?nativeTextAreaValueSetter.call(e,t):nativeInputValueSetter.call(e,t),o||e.dispatchEvent(new Event("input",{bubbles:!0})),await waitFor(.1),blurLastClickedElement()}a(inputTextElement,"inputTextElement");async function selectOptionElement(e,t){if(!(e instanceof HTMLSelectElement))throw new Error("Element is not a select element");const n=Array.from(e.options).find(r=>r.textContent?.trim()===t.trim());if(!n)throw new Error(`Option with text "${t}" not found in select element`);e.value=n.value,e.dispatchEvent(new Event("change",{bubbles:!0})),await waitFor(.1)}a(selectOptionElement,"selectOptionElement");async function scrollIntoViewIfNeeded(e){const t=e;t.scrollIntoViewIfNeeded?t.scrollIntoViewIfNeeded():t.scrollIntoView({behavior:"auto",block:"center",inline:"nearest"})}a(scrollIntoViewIfNeeded,"scrollIntoViewIfNeeded");async function scrollVertically(e,t,o){if(o){const c=o;let l=c,d=!1,h=null,f=0,g=0;const m=t;for(;l&&g<10;){const T=window.getComputedStyle(l),I=/(auto|scroll|overlay)/.test(T.overflowY),A=l.scrollHeight>l.clientHeight;if(I&&A){const C=l.scrollTop,D=l.scrollHeight-l.clientHeight;let v=m/3;v>0?v=Math.min(v,D-C):v=Math.max(v,-C),l.scrollTop=C+v;const O=l.scrollTop-C;if(Math.abs(O)>.5){d=!0,h=l,f=O;break}}if(l===document.body||l===document.documentElement)break;l=l.parentElement,g++}return d?`Scrolled container (${h?.tagName}) by ${f}px`:`No scrollable container found for element (${c.tagName})`}const n=t,r=a(c=>c.clientHeight>=window.innerHeight*.5,"bigEnough"),i=a(c=>c&&/(auto|scroll|overlay)/.test(getComputedStyle(c).overflowY)&&c.scrollHeight>c.clientHeight&&r(c),"canScroll");let s=document.activeElement;for(;s&&!i(s)&&s!==document.body;)s=s.parentElement;if(s=i(s)?s:Array.from(document.querySelectorAll("*")).find(i)||document.scrollingElement||document.documentElement,s===document.scrollingElement||s===document.documentElement||s===document.body){const c=window.scrollY,l=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,n);const d=window.scrollY,h=d-c;if(Math.abs(h)<1)return n>0?"⚠️ Already at the bottom of the page, cannot scroll down further.":"⚠️ Already at the top of the page, cannot scroll up further.";const f=n>0&&d>=l-1,g=n<0&&d<=1;return f?`✅ Scrolled page by ${h}px. Reached the bottom of the page.`:g?`✅ Scrolled page by ${h}px. Reached the top of the page.`:`✅ Scrolled page by ${h}px.`}else{const c=s.scrollTop,l=s.scrollHeight-s.clientHeight;s.scrollBy({top:n,behavior:"smooth"}),await waitFor(.1);const d=s.scrollTop,h=d-c;if(Math.abs(h)<1)return n>0?`⚠️ Already at the bottom of container (${s.tagName}), cannot scroll down further.`:`⚠️ Already at the top of container (${s.tagName}), cannot scroll up further.`;const f=n>0&&d>=l-1,g=n<0&&d<=1;return f?`✅ Scrolled container (${s.tagName}) by ${h}px. Reached the bottom.`:g?`✅ Scrolled container (${s.tagName}) by ${h}px. Reached the top.`:`✅ Scrolled container (${s.tagName}) by ${h}px.`}}a(scrollVertically,"scrollVertically");async function scrollHorizontally(e,t,o){if(o){const c=o;let l=c,d=!1,h=null,f=0,g=0;const m=e?t:-t;for(;l&&g<10;){const T=window.getComputedStyle(l),I=/(auto|scroll|overlay)/.test(T.overflowX),A=l.scrollWidth>l.clientWidth;if(I&&A){const C=l.scrollLeft,D=l.scrollWidth-l.clientWidth;let v=m/3;v>0?v=Math.min(v,D-C):v=Math.max(v,-C),l.scrollLeft=C+v;const O=l.scrollLeft-C;if(Math.abs(O)>.5){d=!0,h=l,f=O;break}}if(l===document.body||l===document.documentElement)break;l=l.parentElement,g++}return d?`Scrolled container (${h?.tagName}) horizontally by ${f}px`:`No horizontally scrollable container found for element (${c.tagName})`}const n=e?t:-t,r=a(c=>c.clientWidth>=window.innerWidth*.5,"bigEnough"),i=a(c=>c&&/(auto|scroll|overlay)/.test(getComputedStyle(c).overflowX)&&c.scrollWidth>c.clientWidth&&r(c),"canScroll");let s=document.activeElement;for(;s&&!i(s)&&s!==document.body;)s=s.parentElement;if(s=i(s)?s:Array.from(document.querySelectorAll("*")).find(i)||document.scrollingElement||document.documentElement,s===document.scrollingElement||s===document.documentElement||s===document.body){const c=window.scrollX,l=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(n,0);const d=window.scrollX,h=d-c;if(Math.abs(h)<1)return n>0?"⚠️ Already at the right edge of the page, cannot scroll right further.":"⚠️ Already at the left edge of the page, cannot scroll left further.";const f=n>0&&d>=l-1,g=n<0&&d<=1;return f?`✅ Scrolled page by ${h}px. Reached the right edge of the page.`:g?`✅ Scrolled page by ${h}px. Reached the left edge of the page.`:`✅ Scrolled page horizontally by ${h}px.`}else{const c=s.scrollLeft,l=s.scrollWidth-s.clientWidth;s.scrollBy({left:n,behavior:"smooth"}),await waitFor(.1);const d=s.scrollLeft,h=d-c;if(Math.abs(h)<1)return n>0?`⚠️ Already at the right edge of container (${s.tagName}), cannot scroll right further.`:`⚠️ Already at the left edge of container (${s.tagName}), cannot scroll left further.`;const f=n>0&&d>=l-1,g=n<0&&d<=1;return f?`✅ Scrolled container (${s.tagName}) by ${h}px. Reached the right edge.`:g?`✅ Scrolled container (${s.tagName}) by ${h}px. Reached the left edge.`:`✅ Scrolled container (${s.tagName}) horizontally by ${h}px.`}}a(scrollHorizontally,"scrollHorizontally");const domTree=a((e={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{const{interactiveBlacklist:t,interactiveWhitelist:o,highlightOpacity:n,highlightLabelOpacity:r}=e,{doHighlightElements:i,focusHighlightIndex:s,viewportExpansion:c,debugMode:l}=e;let d=0;const h=new WeakMap;function f(u,y){!u||u.nodeType!==Node.ELEMENT_NODE||h.set(u,{...h.get(u),...y})}a(f,"addExtraData");const g={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:a(()=>{g.boundingRects=new WeakMap,g.clientRects=new WeakMap,g.computedStyles=new WeakMap},"clearCache")};function m(u){if(!u)return null;if(g.boundingRects.has(u))return g.boundingRects.get(u);const y=u.getBoundingClientRect();return y&&g.boundingRects.set(u,y),y}a(m,"getCachedBoundingRect");function T(u){if(!u)return null;if(g.computedStyles.has(u))return g.computedStyles.get(u);const y=window.getComputedStyle(u);return y&&g.computedStyles.set(u,y),y}a(T,"getCachedComputedStyle");function I(u){if(!u)return null;if(g.clientRects.has(u))return g.clientRects.get(u);const y=u.getClientRects();return y&&g.clientRects.set(u,y),y}a(I,"getCachedClientRects");const A={},C={current:0},D="playwright-highlight-container";function v(u,y,P=null){if(!u)return y;const w=[];let E=null,N=20,$=16,z=null;try{let x=document.getElementById(D);x||(x=document.createElement("div"),x.id=D,x.style.position="fixed",x.style.pointerEvents="none",x.style.top="0",x.style.left="0",x.style.width="100%",x.style.height="100%",x.style.zIndex="2147483640",x.style.backgroundColor="transparent",document.body.appendChild(x));const F=u.getClientRects();if(!F||F.length===0)return y;const K=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"],J=y%K.length;let ze=K[J];const ee=ze+Math.floor(n*255).toString(16).padStart(2,"0");ze=ze+Math.floor(r*255).toString(16).padStart(2,"0");let re={x:0,y:0};if(P){const V=P.getBoundingClientRect();re.x=V.left,re.y=V.top}const ge=document.createDocumentFragment();for(const V of F){if(V.width===0||V.height===0)continue;const G=document.createElement("div");G.style.position="fixed",G.style.border=`2px solid ${ze}`,G.style.backgroundColor=ee,G.style.pointerEvents="none",G.style.boxSizing="border-box";const U=V.top+re.y,ke=V.left+re.x;G.style.top=`${U}px`,G.style.left=`${ke}px`,G.style.width=`${V.width}px`,G.style.height=`${V.height}px`,ge.appendChild(G),w.push({element:G,initialRect:V})}const me=F[0];E=document.createElement("div"),E.className="playwright-highlight-label",E.style.position="fixed",E.style.background=ze,E.style.color="white",E.style.padding="1px 4px",E.style.borderRadius="4px",E.style.fontSize=`${Math.min(12,Math.max(8,me.height/2))}px`,E.textContent=y.toString(),N=E.offsetWidth>0?E.offsetWidth:N,$=E.offsetHeight>0?E.offsetHeight:$;const Le=me.top+re.y,et=me.left+re.x;let nt=Le+2,We=et+me.width-N-2;(me.width<N+4||me.height<$+4)&&(nt=Le-$-2,We=et+me.width-N,We<re.x&&(We=et)),nt=Math.max(0,Math.min(nt,window.innerHeight-$)),We=Math.max(0,Math.min(We,window.innerWidth-N)),E.style.top=`${nt}px`,E.style.left=`${We}px`,ge.appendChild(E);const rt=a((V,G)=>{let U=0;return(...ke)=>{const te=performance.now();if(!(te-U<G))return U=te,V(...ke)}},"throttleFunction")(a(()=>{const V=u.getClientRects();let G={x:0,y:0};if(P){const U=P.getBoundingClientRect();G.x=U.left,G.y=U.top}if(w.forEach((U,ke)=>{if(ke<V.length){const te=V[ke],Ve=te.top+G.y,Ae=te.left+G.x;U.element.style.top=`${Ve}px`,U.element.style.left=`${Ae}px`,U.element.style.width=`${te.width}px`,U.element.style.height=`${te.height}px`,U.element.style.display=te.width===0||te.height===0?"none":"block"}else U.element.style.display="none"}),V.length<w.length)for(let U=V.length;U<w.length;U++)w[U].element.style.display="none";if(E&&V.length>0){const U=V[0],ke=U.top+G.y,te=U.left+G.x;let Ve=ke+2,Ae=te+U.width-N-2;(U.width<N+4||U.height<$+4)&&(Ve=ke-$-2,Ae=te+U.width-N,Ae<G.x&&(Ae=te)),Ve=Math.max(0,Math.min(Ve,window.innerHeight-$)),Ae=Math.max(0,Math.min(Ae,window.innerWidth-N)),E.style.top=`${Ve}px`,E.style.left=`${Ae}px`,E.style.display="block"}else E&&(E.style.display="none")},"updatePositions"),16);return window.addEventListener("scroll",rt,!0),window.addEventListener("resize",rt),z=a(()=>{window.removeEventListener("scroll",rt,!0),window.removeEventListener("resize",rt),w.forEach(V=>V.element.remove()),E&&E.remove()},"cleanupFn"),x.appendChild(ge),y+1}finally{z&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(z)}}a(v,"highlightElement");function k(u){if(!u||u.nodeType!==Node.ELEMENT_NODE)return null;const y=T(u);if(!y)return null;const P=y.display;if(P==="inline"||P==="inline-block")return null;const w=y.overflowX,E=y.overflowY,N=w==="auto"||w==="scroll",$=E==="auto"||E==="scroll";if(!N&&!$)return null;const z=u.scrollWidth-u.clientWidth,x=u.scrollHeight-u.clientHeight,F=4;if(z<F&&x<F||!$&&z<F||!N&&x<F)return null;const K=u.scrollTop,J=u.scrollLeft,ze=u.scrollWidth-u.clientWidth-u.scrollLeft,ee=u.scrollHeight-u.clientHeight-u.scrollTop,re={top:K,right:ze,bottom:ee,left:J};return f(u,{scrollable:!0,scrollData:re}),re}a(k,"isScrollableElement");function O(u){try{if(c===-1){const $=u.parentElement;if(!$)return!1;try{return $.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const x=window.getComputedStyle($);return x.display!=="none"&&x.visibility!=="hidden"&&x.opacity!=="0"}}const y=document.createRange();y.selectNodeContents(u);const P=y.getClientRects();if(!P||P.length===0)return!1;let w=!1,E=!1;for(const $ of P)if($.width>0&&$.height>0&&(w=!0,!($.bottom<-c||$.top>window.innerHeight+c||$.right<-c||$.left>window.innerWidth+c))){E=!0;break}if(!w||!E)return!1;const N=u.parentElement;if(!N)return!1;try{return N.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const z=window.getComputedStyle(N);return z.display!=="none"&&z.visibility!=="hidden"&&z.opacity!=="0"}}catch(y){return console.warn("Error checking text node visibility:",y),!1}}a(O,"isTextNodeVisible");function Ie(u){if(!u||!u.tagName)return!1;const y=new Set(["body","div","main","article","section","nav","header","footer"]),P=u.tagName.toLowerCase();return y.has(P)?!0:!new Set(["svg","script","style","link","meta","noscript","template"]).has(P)}a(Ie,"isElementAccepted");function H(u){const y=T(u);return u.offsetWidth>0&&u.offsetHeight>0&&y?.visibility!=="hidden"&&y?.display!=="none"}a(H,"isElementVisible");function le(u){if(!u||u.nodeType!==Node.ELEMENT_NODE||t.includes(u))return!1;if(o.includes(u))return!0;const y=u.tagName.toLowerCase(),P=T(u),w=new Set(["pointer","move","text","grab","grabbing","cell","copy","alias","all-scroll","col-resize","context-menu","crosshair","e-resize","ew-resize","help","n-resize","ne-resize","nesw-resize","ns-resize","nw-resize","nwse-resize","row-resize","s-resize","se-resize","sw-resize","vertical-text","w-resize","zoom-in","zoom-out"]),E=new Set(["not-allowed","no-drop","wait","progress","initial","inherit"]);function N(ee){return ee.tagName.toLowerCase()==="html"?!1:!!(P?.cursor&&w.has(P.cursor))}if(a(N,"doesElementHaveInteractivePointer"),N(u))return!0;const z=new Set(["a","button","input","select","textarea","details","summary","label","option","optgroup","fieldset","legend"]),x=new Set(["disabled","readonly"]);if(z.has(y)){if(P?.cursor&&E.has(P.cursor))return!1;for(const ee of x)if(u.hasAttribute(ee)||u.getAttribute(ee)==="true"||u.getAttribute(ee)==="")return!1;return!(u.disabled||u.readOnly||u.inert)}const F=u.getAttribute("role"),K=u.getAttribute("aria-role");if(u.getAttribute("contenteditable")==="true"||u.isContentEditable||u.classList&&(u.classList.contains("button")||u.classList.contains("dropdown-toggle")||u.getAttribute("data-index")||u.getAttribute("data-toggle")==="dropdown"||u.getAttribute("aria-haspopup")==="true"))return!0;const J=new Set(["button","menu","menubar","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);if(z.has(y)||F&&J.has(F)||K&&J.has(K))return!0;try{if(typeof getEventListeners=="function"){const ge=getEventListeners(u),me=["click","mousedown","mouseup","dblclick"];for(const Le of me)if(ge[Le]&&ge[Le].length>0)return!0}const ee=u?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof ee=="function"){const ge=ee(u),me=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const Le of me)for(const et of ge)if(et.type===Le)return!0}const re=["onclick","onmousedown","onmouseup","ondblclick"];for(const ge of re)if(u.hasAttribute(ge)||typeof u[ge]=="function")return!0}catch{}return!!k(u)}a(le,"isInteractiveElement");function ue(u){if(c===-1)return!0;const y=I(u);if(!y||y.length===0)return!1;let P=!1;for(const x of y)if(x.width>0&&x.height>0&&!(x.bottom<-c||x.top>window.innerHeight+c||x.right<-c||x.left>window.innerWidth+c)){P=!0;break}if(!P)return!1;if(u.ownerDocument!==window.document)return!0;let E=Array.from(y).find(x=>x.width>0&&x.height>0);if(!E)return!1;const N=u.getRootNode();if(N instanceof ShadowRoot){const x=E.left+E.width/2,F=E.top+E.height/2;try{const K=N.elementFromPoint(x,F);if(!K)return!1;let J=K;for(;J&&J!==N;){if(J===u)return!0;J=J.parentElement}return!1}catch{return!0}}const $=5;return[{x:E.left+E.width/2,y:E.top+E.height/2},{x:E.left+$,y:E.top+$},{x:E.right-$,y:E.bottom-$}].some(({x,y:F})=>{try{const K=document.elementFromPoint(x,F);if(!K)return!1;let J=K;for(;J&&J!==document.documentElement;){if(J===u)return!0;J=J.parentElement}return!1}catch{return!0}})}a(ue,"isTopElement");function q(u,y){if(y===-1)return!0;const P=u.getClientRects();if(!P||P.length===0){const w=m(u);return!w||w.width===0||w.height===0?!1:!(w.bottom<-y||w.top>window.innerHeight+y||w.right<-y||w.left>window.innerWidth+y)}for(const w of P)if(!(w.width===0||w.height===0)&&!(w.bottom<-y||w.top>window.innerHeight+y||w.right<-y||w.left>window.innerWidth+y))return!0;return!1}a(q,"isInExpandedViewport");function de(u){if(!u||u.nodeType!==Node.ELEMENT_NODE)return!1;const y=u.tagName.toLowerCase();return new Set(["a","button","input","select","textarea","details","summary","label"]).has(y)?!0:u.hasAttribute("onclick")||u.hasAttribute("role")||u.hasAttribute("tabindex")||u.hasAttribute("aria-")||u.hasAttribute("data-action")||u.getAttribute("contenteditable")==="true"}a(de,"isInteractiveCandidate");const pe=new Set(["a","button","input","select","textarea","summary","details","label","option"]),Ke=new Set(["button","link","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);function he(u){if(!u||u.nodeType!==Node.ELEMENT_NODE||!H(u))return!1;const y=u.hasAttribute("role")||u.hasAttribute("tabindex")||u.hasAttribute("onclick")||typeof u.onclick=="function",P=/\b(btn|clickable|menu|item|entry|link)\b/i.test(u.className||""),w=!!u.closest('button,a,[role="button"],.menu,.dropdown,.list,.toolbar'),E=[...u.children].some(H),N=u.parentElement&&u.parentElement.isSameNode(document.body);return(le(u)||y||P)&&E&&w&&!N}a(he,"isHeuristicallyInteractive");function Xe(u){if(!u||u.nodeType!==Node.ELEMENT_NODE)return!1;const y=u.tagName.toLowerCase(),P=u.getAttribute("role");if(y==="iframe"||pe.has(y)||P&&Ke.has(P)||u.isContentEditable||u.getAttribute("contenteditable")==="true"||u.hasAttribute("data-testid")||u.hasAttribute("data-cy")||u.hasAttribute("data-test")||u.hasAttribute("onclick")||typeof u.onclick=="function")return!0;try{const w=u?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof w=="function"){const N=w(u),$=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const z of $)for(const x of N)if(x.type===z)return!0}if(["onmousedown","onmouseup","onkeydown","onkeyup","onsubmit","onchange","oninput","onfocus","onblur"].some(N=>u.hasAttribute(N)))return!0}catch{}return!!he(u)}a(Xe,"isElementDistinctInteraction");function Qe(u,y,P,w){if(!u.isInteractive)return!1;let E=!1;return w?Xe(y)?E=!0:E=!1:E=!0,E&&(u.isInViewport=q(y,c),(u.isInViewport||c===-1)&&(u.highlightIndex=d++,i))?(s>=0?s===u.highlightIndex&&v(y,u.highlightIndex,P):v(y,u.highlightIndex,P),!0):!1}a(Qe,"handleHighlighting");function _e(u,y=null,P=!1){if(!u||u.id===D||u.nodeType!==Node.ELEMENT_NODE&&u.nodeType!==Node.TEXT_NODE||!u||u.id===D||u.dataset?.browserUseIgnore==="true"||u.dataset?.pageAgentIgnore==="true"||u.getAttribute&&u.getAttribute("aria-hidden")==="true")return null;if(u===document.body){const $={tagName:"body",attributes:{},xpath:"/body",children:[]};for(const x of u.childNodes){const F=_e(x,y,!1);F&&$.children.push(F)}const z=`${C.current++}`;return A[z]=$,z}if(u.nodeType!==Node.ELEMENT_NODE&&u.nodeType!==Node.TEXT_NODE)return null;if(u.nodeType===Node.TEXT_NODE){const $=u.textContent?.trim();if(!$)return null;const z=u.parentElement;if(!z||z.tagName.toLowerCase()==="script")return null;const x=`${C.current++}`;return A[x]={type:"TEXT_NODE",text:$,isVisible:O(u)},x}if(u.nodeType===Node.ELEMENT_NODE&&!Ie(u))return null;if(c!==-1&&!u.shadowRoot){const $=m(u),z=T(u),x=z&&(z.position==="fixed"||z.position==="sticky"),F=u.offsetWidth>0||u.offsetHeight>0;if(!$||!x&&!F&&($.bottom<-c||$.top>window.innerHeight+c||$.right<-c||$.left>window.innerWidth+c))return null}const w={tagName:u.tagName.toLowerCase(),attributes:{},children:[]};if(de(u)||u.tagName.toLowerCase()==="iframe"||u.tagName.toLowerCase()==="body"){const $=u.getAttributeNames?.()||[];for(const z of $){const x=u.getAttribute(z);w.attributes[z]=x}u.tagName.toLowerCase()==="input"&&(u.type==="checkbox"||u.type==="radio")&&(w.attributes.checked=u.checked?"true":"false")}let E=!1;if(u.nodeType===Node.ELEMENT_NODE&&(w.isVisible=H(u),w.isVisible)){w.isTopElement=ue(u);const $=u.getAttribute("role"),z=$==="menu"||$==="menubar"||$==="listbox";(w.isTopElement||z)&&(w.isInteractive=le(u),E=Qe(w,u,y,P),w.ref=u)}if(u.tagName){const $=u.tagName.toLowerCase();if($==="iframe")try{const z=u.contentDocument||u.contentWindow?.document;if(z)for(const x of z.childNodes){const F=_e(x,u,!1);F&&w.children.push(F)}}catch(z){console.warn("Unable to access iframe:",z)}else if(u.isContentEditable||u.getAttribute("contenteditable")==="true"||u.id==="tinymce"||u.classList.contains("mce-content-body")||$==="body"&&u.getAttribute("data-id")?.startsWith("mce_"))for(const z of u.childNodes){const x=_e(z,y,E);x&&w.children.push(x)}else{if(u.shadowRoot){w.shadowRoot=!0;for(const z of u.shadowRoot.childNodes){const x=_e(z,y,E);x&&w.children.push(x)}}for(const z of u.childNodes){const F=_e(z,y,E||P);F&&w.children.push(F)}}}if(w.tagName==="a"&&w.children.length===0&&!w.attributes.href){const $=m(u);if(!($&&$.width>0&&$.height>0||u.offsetWidth>0||u.offsetHeight>0))return null}w.extra=h.get(u)||null;const N=`${C.current++}`;return A[N]=w,N}a(_e,"buildDomTree");const fe=_e(document.body);return g.clearCache(),{rootId:fe,map:A}},"domTree"),DEFAULT_VIEWPORT_EXPANSION=-1;function resolveViewportExpansion(e){return e??DEFAULT_VIEWPORT_EXPANSION}a(resolveViewportExpansion,"resolveViewportExpansion");const newElementsCache=new WeakMap;function getFlatTree(e){const t=resolveViewportExpansion(e.viewportExpansion),o=[];for(const s of e.interactiveBlacklist||[])typeof s=="function"?o.push(s()):o.push(s);const n=[];for(const s of e.interactiveWhitelist||[])typeof s=="function"?n.push(s()):n.push(s);const r=domTree({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:t,interactiveBlacklist:o,interactiveWhitelist:n,highlightOpacity:e.highlightOpacity??0,highlightLabelOpacity:e.highlightLabelOpacity??.1}),i=window.location.href;for(const s in r.map){const c=r.map[s];if(c.isInteractive&&c.ref){const l=c.ref;newElementsCache.has(l)||(newElementsCache.set(l,i),c.isNew=!0)}}return r}a(getFlatTree,"getFlatTree");const globRegexCache=new Map;function globToRegex(e){let t=globRegexCache.get(e);if(!t){const o=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");t=new RegExp(`^${o.replace(/\*/g,".*")}$`),globRegexCache.set(e,t)}return t}a(globToRegex,"globToRegex");function matchAttributes(e,t){const o={};for(const n of t)if(n.includes("*")){const r=globToRegex(n);for(const i of Object.keys(e))r.test(i)&&e[i].trim()&&(o[i]=e[i].trim())}else{const r=e[n];r&&r.trim()&&(o[n]=r.trim())}return o}a(matchAttributes,"matchAttributes");function flatTreeToString(e,t){const o=["title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","id","for","target","aria-haspopup","aria-controls","aria-owns","contenteditable"],n=[...t||[],...o],r=a((f,g)=>f.length>g?f.substring(0,g)+"...":f,"capTextLength"),i=a(f=>{const g=e.map[f];if(!g)return null;if(g.type==="TEXT_NODE"){const m=g;return{type:"text",text:m.text,isVisible:m.isVisible,parent:null,children:[]}}else{const m=g,T=[];if(m.children)for(const I of m.children){const A=i(I);A&&(A.parent=null,T.push(A))}return{type:"element",tagName:m.tagName,attributes:m.attributes??{},isVisible:m.isVisible??!1,isInteractive:m.isInteractive??!1,isTopElement:m.isTopElement??!1,isNew:m.isNew??!1,highlightIndex:m.highlightIndex,parent:null,children:T,extra:m.extra??{}}}},"buildTreeNode"),s=a((f,g=null)=>{f.parent=g;for(const m of f.children)s(m,f)},"setParentReferences"),c=i(e.rootId);if(!c)return"";s(c);const l=a(f=>{let g=f.parent;for(;g;){if(g.type==="element"&&g.highlightIndex!==void 0)return!0;g=g.parent}return!1},"hasParentWithHighlightIndex"),d=a((f,g,m)=>{let T=g;const I="	".repeat(g);if(f.type==="element"){if(f.highlightIndex!==void 0){T+=1;const A=getAllTextTillNextClickableElement(f);let C="";if(n.length>0&&f.attributes){const k=matchAttributes(f.attributes,n),O=Object.keys(k);if(O.length>1){const H=new Set,le={};for(const ue of O){const q=k[ue];q.length>5&&(q in le?H.add(ue):le[q]=ue)}for(const ue of H)delete k[ue]}k.role===f.tagName&&delete k.role;const Ie=["aria-label","placeholder","title"];for(const H of Ie)k[H]&&k[H].toLowerCase().trim()===A.toLowerCase().trim()&&delete k[H];Object.keys(k).length>0&&(C=Object.entries(k).map(([H,le])=>`${H}=${r(le,20)}`).join(" "))}const D=f.isNew?`*[${f.highlightIndex}]`:`[${f.highlightIndex}]`;let v=`${I}${D}<${f.tagName??""}`;if(C&&(v+=` ${C}`),f.extra&&f.extra.scrollable){let k="";f.extra.scrollData?.left&&(k+=`left=${f.extra.scrollData.left}, `),f.extra.scrollData?.top&&(k+=`top=${f.extra.scrollData.top}, `),f.extra.scrollData?.right&&(k+=`right=${f.extra.scrollData.right}, `),f.extra.scrollData?.bottom&&(k+=`bottom=${f.extra.scrollData.bottom}`),v+=` data-scrollable="${k}"`}if(A){const k=A.trim();C||(v+=" "),v+=`>${k}`}else C||(v+=" ");v+=" />",m.push(v)}for(const A of f.children)d(A,T,m)}else if(f.type==="text"){if(l(f))return;f.parent&&f.parent.type==="element"&&f.parent.isVisible&&f.parent.isTopElement&&m.push(`${I}${f.text??""}`)}},"processNode"),h=[];return d(c,0,h),h.join(`
`)}a(flatTreeToString,"flatTreeToString");const getAllTextTillNextClickableElement=a((e,t=-1)=>{const o=[],n=a((r,i)=>{if(!(t!==-1&&i>t)&&!(r.type==="element"&&r!==e&&r.highlightIndex!==void 0)){if(r.type==="text"&&r.text)o.push(r.text);else if(r.type==="element")for(const s of r.children)n(s,i+1)}},"collectText");return n(e,0),o.join(`
`).trim()},"getAllTextTillNextClickableElement");function getSelectorMap(e){const t=new Map,o=Object.keys(e.map);for(const n of o){const r=e.map[n];r.isInteractive&&typeof r.highlightIndex=="number"&&t.set(r.highlightIndex,r)}return t}a(getSelectorMap,"getSelectorMap");function getElementTextMap(e){const t=e.split(`
`).map(n=>n.trim()).filter(n=>n.length>0),o=new Map;for(const n of t){const i=/^\[(\d+)\]<[^>]+>([^<]*)/.exec(n);if(i){const s=parseInt(i[1],10);o.set(s,n)}}return o}a(getElementTextMap,"getElementTextMap");function cleanUpHighlights(){const e=window._highlightCleanupFunctions||[];for(const t of e)typeof t=="function"&&t();window._highlightCleanupFunctions=[]}a(cleanUpHighlights,"cleanUpHighlights"),window.addEventListener("popstate",()=>{cleanUpHighlights()}),window.addEventListener("hashchange",()=>{cleanUpHighlights()}),window.addEventListener("beforeunload",()=>{cleanUpHighlights()});const navigation=window.navigation;if(navigation&&typeof navigation.addEventListener=="function")navigation.addEventListener("navigate",()=>{cleanUpHighlights()});else{let e=window.location.href;setInterval(()=>{window.location.href!==e&&(e=window.location.href,cleanUpHighlights())},500)}function getPageInfo(){const e=window.innerWidth,t=window.innerHeight,o=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth||0),n=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight||0),r=window.scrollX||window.pageXOffset||document.documentElement.scrollLeft||0,i=window.scrollY||window.pageYOffset||document.documentElement.scrollTop||0,s=Math.max(0,n-(window.innerHeight+i)),c=Math.max(0,o-(window.innerWidth+r));return{viewport_width:e,viewport_height:t,page_width:o,page_height:n,scroll_x:r,scroll_y:i,pixels_above:i,pixels_below:s,pages_above:t>0?i/t:0,pages_below:t>0?s/t:0,total_pages:t>0?n/t:0,current_page_position:i/Math.max(1,n-t),pixels_left:r,pixels_right:c}}a(getPageInfo,"getPageInfo");function patchReact(e){const t=document.querySelectorAll('[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^="root-"], [id^="app-"], #adex-wrapper, #adex-root');for(const o of t)o.setAttribute("data-page-agent-not-interactive","true")}a(patchReact,"patchReact");const _PageController=class _PageController extends EventTarget{config;flatTree=null;selectorMap=new Map;elementTextMap=new Map;simplifiedHTML="<EMPTY>";lastTimeUpdate=0;isIndexed=!1;mask=null;maskReady=null;constructor(e={}){super(),this.config=e,patchReact(),e.enableMask&&this.initMask()}initMask(){this.maskReady===null&&(this.maskReady=(async()=>{const{SimulatorMask:e}=await Promise.resolve().then(()=>SimulatorMask$1);this.mask=new e})())}async getCurrentUrl(){return window.location.href}async getLastUpdateTime(){return this.lastTimeUpdate}async getBrowserState(){const e=window.location.href,t=document.title,o=getPageInfo(),n=resolveViewportExpansion(this.config.viewportExpansion);await this.updateTree();const r=this.simplifiedHTML,i=`Current Page: [${t}](${e})`,s=`Page info: ${o.viewport_width}x${o.viewport_height}px viewport, ${o.page_width}x${o.page_height}px total page size, ${o.pages_above.toFixed(1)} pages above, ${o.pages_below.toFixed(1)} pages below, ${o.total_pages.toFixed(1)} total pages, at ${(o.current_page_position*100).toFixed(0)}% of page`,c=n===-1?"Interactive elements from top layer of the current page (full page):":"Interactive elements from top layer of the current page inside the viewport:",d=o.pixels_above>4&&n!==-1?`... ${o.pixels_above} pixels above (${o.pages_above.toFixed(1)} pages) - scroll to see more ...`:"[Start of page]",h=`${i}
${s}

${c}

${d}`,g=o.pixels_below>4&&n!==-1?`... ${o.pixels_below} pixels below (${o.pages_below.toFixed(1)} pages) - scroll to see more ...`:"[End of page]";return{url:e,title:t,header:h,content:r,footer:g}}async updateTree(){this.dispatchEvent(new Event("beforeUpdate")),this.lastTimeUpdate=Date.now(),this.mask&&(this.mask.wrapper.style.pointerEvents="none"),cleanUpHighlights();const e=[...this.config.interactiveBlacklist||[],...document.querySelectorAll("[data-page-agent-not-interactive]").values()];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:e}),this.simplifiedHTML=flatTreeToString(this.flatTree,this.config.includeAttributes),this.selectorMap.clear(),this.selectorMap=getSelectorMap(this.flatTree),this.elementTextMap.clear(),this.elementTextMap=getElementTextMap(this.simplifiedHTML),this.isIndexed=!0,this.mask&&(this.mask.wrapper.style.pointerEvents="auto"),this.dispatchEvent(new Event("afterUpdate")),this.simplifiedHTML}async cleanUpHighlights(){cleanUpHighlights()}assertIndexed(){if(!this.isIndexed)throw new Error("DOM tree not indexed yet. Can not perform actions on elements.")}async clickElement(e){try{this.assertIndexed();const t=getElementByIndex(this.selectorMap,e),o=this.elementTextMap.get(e);return await clickElement(t),t instanceof HTMLAnchorElement&&t.target==="_blank"?{success:!0,message:`✅ Clicked element (${o??e}). ⚠️ Link opened in a new tab.`}:{success:!0,message:`✅ Clicked element (${o??e}).`}}catch(t){return{success:!1,message:`❌ Failed to click element: ${t}`}}}async inputText(e,t){try{this.assertIndexed();const o=getElementByIndex(this.selectorMap,e),n=this.elementTextMap.get(e);return await inputTextElement(o,t),{success:!0,message:`✅ Input text (${t}) into element (${n??e}).`}}catch(o){return{success:!1,message:`❌ Failed to input text: ${o}`}}}async selectOption(e,t){try{this.assertIndexed();const o=getElementByIndex(this.selectorMap,e),n=this.elementTextMap.get(e);return await selectOptionElement(o,t),{success:!0,message:`✅ Selected option (${t}) in element (${n??e}).`}}catch(o){return{success:!1,message:`❌ Failed to select option: ${o}`}}}async scroll(e){try{const{down:t,numPages:o,pixels:n,index:r}=e;this.assertIndexed();const i=n??o*(t?1:-1)*window.innerHeight,s=r!==void 0?getElementByIndex(this.selectorMap,r):null;return{success:!0,message:await scrollVertically(t,i,s)}}catch(t){return{success:!1,message:`❌ Failed to scroll: ${t}`}}}async scrollHorizontally(e){try{const{right:t,pixels:o,index:n}=e;this.assertIndexed();const r=o*(t?1:-1),i=n!==void 0?getElementByIndex(this.selectorMap,n):null;return{success:!0,message:await scrollHorizontally(t,r,i)}}catch(t){return{success:!1,message:`❌ Failed to scroll horizontally: ${t}`}}}async executeJavascript(script){try{const asyncFunction=eval(`(async () => { ${script} })`),result=await asyncFunction();return{success:!0,message:`✅ Executed JavaScript. Result: ${result}`}}catch(e){return{success:!1,message:`❌ Error executing JavaScript: ${e}`}}}async showMask(){await this.maskReady,this.mask?.show()}async hideMask(){await this.maskReady,this.mask?.hide()}dispose(){cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML="<EMPTY>",this.isIndexed=!1,this.mask?.dispose(),this.mask=null}};a(_PageController,"PageController");let PageController=_PageController;const enUS={ui:{panel:{ready:"Ready",thinking:"Thinking...",taskInput:"Enter new task, describe steps in detail, press Enter to submit",userAnswerPrompt:"Please answer the question above, press Enter to submit",taskTerminated:"Task terminated",taskCompleted:"Task completed",userAnswer:"User answer: {{input}}",question:"Question: {{question}}",waitingPlaceholder:"Waiting for task to start...",stop:"Stop",close:"Close",expand:"Expand history",collapse:"Collapse history",step:"Step {{number}}"},tools:{clicking:"Clicking element [{{index}}]...",inputting:"Inputting text to element [{{index}}]...",selecting:'Selecting option "{{text}}"...',scrolling:"Scrolling page...",waiting:"Waiting {{seconds}} seconds...",askingUser:"Asking user...",done:"Task done",clicked:"🖱️ Clicked element [{{index}}]",inputted:'⌨️ Inputted text "{{text}}"',selected:'☑️ Selected option "{{text}}"',scrolled:"🛞 Page scrolled",waited:"⌛️ Wait completed",executing:"Executing {{toolName}}...",resultSuccess:"success",resultFailure:"failed",resultError:"error"},errors:{elementNotFound:"No interactive element found at index {{index}}",taskRequired:"Task description is required",executionFailed:"Task execution failed",notInputElement:"Element is not an input or textarea",notSelectElement:"Element is not a select element",optionNotFound:'Option "{{text}}" not found'}}},zhCN={ui:{panel:{ready:"准备就绪",thinking:"正在思考...",taskInput:"输入新任务,详细描述步骤,回车提交",userAnswerPrompt:"请回答上面问题,回车提交",taskTerminated:"任务已终止",taskCompleted:"任务结束",userAnswer:"用户回答: {{input}}",question:"询问: {{question}}",waitingPlaceholder:"等待任务开始...",stop:"终止",close:"关闭",expand:"展开历史",collapse:"收起历史",step:"步骤 {{number}}"},tools:{clicking:"正在点击元素 [{{index}}]...",inputting:"正在输入文本到元素 [{{index}}]...",selecting:'正在选择选项 "{{text}}"...',scrolling:"正在滚动页面...",waiting:"等待 {{seconds}} 秒...",askingUser:"正在询问用户...",done:"结束任务",clicked:"🖱️ 已点击元素 [{{index}}]",inputted:'⌨️ 已输入文本 "{{text}}"',selected:'☑️ 已选择选项 "{{text}}"',scrolled:"🛞 页面滚动完成",waited:"⌛️ 等待完成",executing:"正在执行 {{toolName}}...",resultSuccess:"成功",resultFailure:"失败",resultError:"错误"},errors:{elementNotFound:"未找到索引为 {{index}} 的交互元素",taskRequired:"任务描述不能为空",executionFailed:"任务执行失败",notInputElement:"元素不是输入框或文本域",notSelectElement:"元素不是选择框",optionNotFound:'未找到选项 "{{text}}"'}}},locales={"en-US":enUS,"zh-CN":zhCN},dt=class dt{language;translations;constructor(t="en-US"){this.language=t in locales?t:"en-US",this.translations=locales[this.language]}t(t,o){const n=this.getNestedValue(this.translations,t);return n?o?this.interpolate(n,o):n:(console.warn(`Translation key "${t}" not found for language "${this.language}"`),t)}getNestedValue(t,o){return o.split(".").reduce((n,r)=>n?.[r],t)}interpolate(t,o){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>o[r]!=null?o[r].toString():n)}getLanguage(){return this.language}};a(dt,"I18n");let I18n=dt;function truncate(e,t){return e.length>t?e.substring(0,t)+"...":e}a(truncate,"truncate");function escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}a(escapeHtml,"escapeHtml");const wrapper$1="_wrapper_gtdpc_1",background="_background_gtdpc_39",header="_header_gtdpc_99",pulse="_pulse_gtdpc_1",retryPulse="_retryPulse_gtdpc_1",statusTextFadeOut="_statusTextFadeOut_gtdpc_1",statusTextFadeIn="_statusTextFadeIn_gtdpc_1",statusSection="_statusSection_gtdpc_121",indicator="_indicator_gtdpc_128",thinking="_thinking_gtdpc_137",tool_executing="_tool_executing_gtdpc_142",retry="_retry_gtdpc_147",completed="_completed_gtdpc_153",input="_input_gtdpc_154",output="_output_gtdpc_155",error="_error_gtdpc_160",statusText="_statusText_gtdpc_166",fadeOut="_fadeOut_gtdpc_178",fadeIn="_fadeIn_gtdpc_182",controls="_controls_gtdpc_188",controlButton="_controlButton_gtdpc_193",stopButton="_stopButton_gtdpc_212",historySectionWrapper="_historySectionWrapper_gtdpc_246",shimmer="_shimmer_gtdpc_1",celebrate="_celebrate_gtdpc_1",expanded="_expanded_gtdpc_278",historySection="_historySection_gtdpc_246",historyItem="_historyItem_gtdpc_297",observation="_observation_gtdpc_355",question="_question_gtdpc_360",doneSuccess="_doneSuccess_gtdpc_366",historyContent="_historyContent_gtdpc_402",statusIcon="_statusIcon_gtdpc_403",doneError="_doneError_gtdpc_412",reflectionLines="_reflectionLines_gtdpc_462",historyMeta="_historyMeta_gtdpc_469",inputSectionWrapper="_inputSectionWrapper_gtdpc_539",hidden="_hidden_gtdpc_562",inputSection="_inputSection_gtdpc_539",taskInput="_taskInput_gtdpc_573",styles$1={wrapper:wrapper$1,"mask-running":"_mask-running_gtdpc_1",background,header,pulse,retryPulse,statusTextFadeOut,statusTextFadeIn,statusSection,indicator,thinking,tool_executing,retry,completed,input,output,error,statusText,fadeOut,fadeIn,controls,controlButton,stopButton,historySectionWrapper,shimmer,celebrate,expanded,historySection,historyItem,observation,question,doneSuccess,historyContent,statusIcon,doneError,reflectionLines,historyMeta,inputSectionWrapper,hidden,inputSection,taskInput};function createCard({icon:e,content:t,meta:o,type:n}){const r=n?styles$1[n]:"",i=Array.isArray(t)?`<div class="${styles$1.reflectionLines}">${t.map(s=>`<span>${escapeHtml(s)}</span>`).join("")}</div>`:`<span>${escapeHtml(t)}</span>`;return`
		<div class="${styles$1.historyItem} ${r}">
			<div class="${styles$1.historyContent}">
				<span class="${styles$1.statusIcon}">${e}</span>
				${i}
			</div>
			${o?`<div class="${styles$1.historyMeta}">${o}</div>`:""}
		</div>
	`}a(createCard,"createCard");function createReflectionLines(e){const t=[];return e.evaluation_previous_goal&&t.push(`🔍 ${e.evaluation_previous_goal}`),e.memory&&t.push(`💾 ${e.memory}`),e.next_goal&&t.push(`🎯 ${e.next_goal}`),t}a(createReflectionLines,"createReflectionLines");const pt=class pt{constructor(t,o={}){Z(this,_);Z(this,ne);Z(this,je);Z(this,ie);Z(this,ye);Z(this,Ce);Z(this,be);Z(this,Re);Z(this,we);Z(this,B);Z(this,Ge);Z(this,$e,!1);Z(this,j);Z(this,xe,null);Z(this,ve,!1);Z(this,Ze,null);Z(this,Q,null);Z(this,Be,!1);Z(this,He,a(()=>b(this,_,Ot).call(this),"#onStatusChange"));Z(this,Je,a(()=>b(this,_,Ct).call(this),"#onHistoryChange"));Z(this,Ye,a(t=>b(this,_,Rt).call(this,t.detail),"#onActivity"));Z(this,qe,a(()=>this.dispose(),"#onAgentDispose"));S(this,B,t),S(this,Ge,o),S(this,j,new I18n(o.language??"en-US")),p(this,B).onAskUser=n=>b(this,_,Zt).call(this,n),S(this,ne,b(this,_,Dt).call(this)),S(this,je,p(this,ne).querySelector(`.${styles$1.indicator}`)),S(this,ie,p(this,ne).querySelector(`.${styles$1.statusText}`)),S(this,ye,p(this,ne).querySelector(`.${styles$1.historySection}`)),S(this,Ce,p(this,ne).querySelector(`.${styles$1.expandButton}`)),S(this,be,p(this,ne).querySelector(`.${styles$1.stopButton}`)),S(this,Re,p(this,ne).querySelector(`.${styles$1.inputSectionWrapper}`)),S(this,we,p(this,ne).querySelector(`.${styles$1.taskInput}`)),p(this,B).addEventListener("statuschange",p(this,He)),p(this,B).addEventListener("historychange",p(this,Je)),p(this,B).addEventListener("activity",p(this,Ye)),p(this,B).addEventListener("dispose",p(this,qe)),b(this,_,Ut).call(this),b(this,_,jt).call(this),b(this,_,tt).call(this),this.hide()}get wrapper(){return p(this,ne)}show(){this.wrapper.style.display="block",this.wrapper.offsetHeight,this.wrapper.style.opacity="1",this.wrapper.style.transform="translateX(-50%) translateY(0)"}hide(){this.wrapper.style.opacity="0",this.wrapper.style.transform="translateX(-50%) translateY(20px)",this.wrapper.style.display="none"}reset(){p(this,ie).textContent=p(this,j).t("ui.panel.ready"),b(this,_,Fe).call(this,"thinking"),b(this,_,kt).call(this),b(this,_,it).call(this),S(this,ve,!1),S(this,xe,null),b(this,_,tt).call(this)}expand(){b(this,_,ot).call(this)}collapse(){b(this,_,it).call(this)}dispose(){p(this,B).removeEventListener("statuschange",p(this,He)),p(this,B).removeEventListener("historychange",p(this,Je)),p(this,B).removeEventListener("activity",p(this,Ye)),p(this,B).removeEventListener("dispose",p(this,qe)),S(this,ve,!1),b(this,_,Bt).call(this),this.wrapper.remove()}};ne=new WeakMap,je=new WeakMap,ie=new WeakMap,ye=new WeakMap,Ce=new WeakMap,be=new WeakMap,Re=new WeakMap,we=new WeakMap,B=new WeakMap,Ge=new WeakMap,$e=new WeakMap,j=new WeakMap,xe=new WeakMap,ve=new WeakMap,Ze=new WeakMap,Q=new WeakMap,Be=new WeakMap,He=new WeakMap,Je=new WeakMap,Ye=new WeakMap,qe=new WeakMap,_=new WeakSet,Ot=a(function(){const t=p(this,B).status,o=t==="running"||t==="idle"?"thinking":t;b(this,_,Fe).call(this,o),t==="running"?(p(this,be).textContent="■",p(this,be).title=p(this,j).t("ui.panel.stop")):(p(this,be).textContent="X",p(this,be).title=p(this,j).t("ui.panel.close")),t==="running"&&(this.show(),b(this,_,bt).call(this)),(t==="completed"||t==="error")&&(p(this,$e)||b(this,_,ot).call(this),b(this,_,Ft).call(this)&&b(this,_,tt).call(this))},"#handleStatusChange"),Ct=a(function(){b(this,_,kt).call(this)},"#handleHistoryChange"),Rt=a(function(t){switch(t.type){case"thinking":S(this,Q,p(this,j).t("ui.panel.thinking")),b(this,_,Fe).call(this,"thinking");break;case"executing":S(this,Q,b(this,_,yt).call(this,t.tool,t.input)),b(this,_,Fe).call(this,"executing");break;case"executed":S(this,Q,truncate(t.output,50));break;case"retrying":S(this,Q,`Retrying (${t.attempt}/${t.maxAttempts})`),b(this,_,Fe).call(this,"retrying");break;case"error":S(this,Q,truncate(t.message,50)),b(this,_,Fe).call(this,"error");break}},"#handleActivity"),Zt=a(function(t){return new Promise(o=>{S(this,ve,!0),S(this,xe,o),p(this,$e)||b(this,_,ot).call(this);const n=document.createElement("div");n.innerHTML=createCard({icon:"❓",content:`Question: ${t}`,type:"question"});const r=n.firstElementChild;r.setAttribute("data-temp-card","true"),p(this,ye).appendChild(r),b(this,_,vt).call(this),b(this,_,tt).call(this,p(this,j).t("ui.panel.userAnswerPrompt"))})},"#askUser"),yt=a(function(t,o){const n=o;switch(t){case"click_element_by_index":return p(this,j).t("ui.tools.clicking",{index:n.index});case"input_text":return p(this,j).t("ui.tools.inputting",{index:n.index});case"select_dropdown_option":return p(this,j).t("ui.tools.selecting",{text:n.text});case"scroll":return p(this,j).t("ui.tools.scrolling");case"wait":return p(this,j).t("ui.tools.waiting",{seconds:n.seconds});case"ask_user":return p(this,j).t("ui.tools.askingUser");case"done":return p(this,j).t("ui.tools.done");default:return p(this,j).t("ui.tools.executing",{toolName:t})}},"#getToolExecutingText"),Nt=a(function(){p(this,B).status==="running"?p(this,B).stop():p(this,B).dispose()},"#handleActionButton"),Lt=a(function(){const t=p(this,we).value.trim();t&&(b(this,_,bt).call(this),p(this,ve)?b(this,_,Mt).call(this,t):p(this,B).execute(t))},"#submitTask"),Mt=a(function(t){Array.from(p(this,ye).children).forEach(o=>{o.getAttribute("data-temp-card")==="true"&&o.remove()}),S(this,ve,!1),p(this,xe)&&(p(this,xe).call(this,t),S(this,xe,null))},"#handleUserAnswer"),tt=a(function(t){p(this,we).value="",p(this,we).placeholder=t||p(this,j).t("ui.panel.taskInput"),p(this,Re).classList.remove(styles$1.hidden),setTimeout(()=>{p(this,we).focus()},100)},"#showInputArea"),bt=a(function(){p(this,Re).classList.add(styles$1.hidden)},"#hideInputArea"),Ft=a(function(){if(p(this,ve)||p(this,B).history.length===0)return!0;const o=p(this,B).status;return o==="completed"||o==="error"?p(this,Ge).promptForNextTask??!0:!1},"#shouldShowInputArea"),Dt=a(function(){const t=document.createElement("div");return t.id="page-agent-runtime_agent-panel",t.className=styles$1.wrapper,t.setAttribute("data-browser-use-ignore","true"),t.setAttribute("data-page-agent-ignore","true"),t.innerHTML=`
			<div class="${styles$1.background}"></div>
			<div class="${styles$1.historySectionWrapper}">
				<div class="${styles$1.historySection}">
					<div class="${styles$1.historyItem}">
						<div class="${styles$1.historyContent}">
							<span class="${styles$1.statusIcon}">🧠</span>
							<span>${p(this,j).t("ui.panel.waitingPlaceholder")}</span>
						</div>
					</div>
				</div>
			</div>
			<div class="${styles$1.header}">
				<div class="${styles$1.statusSection}">
					<div class="${styles$1.indicator} ${styles$1.thinking}"></div>
					<div class="${styles$1.statusText}">${p(this,j).t("ui.panel.ready")}</div>
				</div>
				<div class="${styles$1.controls}">
					<button class="${styles$1.controlButton} ${styles$1.expandButton}" title="${p(this,j).t("ui.panel.expand")}">
						▼
					</button>
					<button class="${styles$1.controlButton} ${styles$1.stopButton}" title="${p(this,j).t("ui.panel.close")}">
						X
					</button>
				</div>
			</div>
			<div class="${styles$1.inputSectionWrapper} ${styles$1.hidden}">
				<div class="${styles$1.inputSection}">
					<input 
						type="text" 
						class="${styles$1.taskInput}" 
						maxlength="200"
					/>
				</div>
			</div>
		`,document.body.appendChild(t),t},"#createWrapper"),Ut=a(function(){this.wrapper.querySelector(`.${styles$1.header}`).addEventListener("click",o=>{o.target.closest(`.${styles$1.controlButton}`)||b(this,_,wt).call(this)}),p(this,Ce).addEventListener("click",o=>{o.stopPropagation(),b(this,_,wt).call(this)}),p(this,be).addEventListener("click",o=>{o.stopPropagation(),b(this,_,Nt).call(this)}),p(this,we).addEventListener("keydown",o=>{o.isComposing||o.key==="Enter"&&(o.preventDefault(),b(this,_,Lt).call(this))}),p(this,Re).addEventListener("click",o=>{o.stopPropagation()})},"#setupEventListeners"),wt=a(function(){p(this,$e)?b(this,_,it).call(this):b(this,_,ot).call(this)},"#toggle"),ot=a(function(){S(this,$e,!0),this.wrapper.classList.add(styles$1.expanded),p(this,Ce).textContent="▲"},"#expand"),it=a(function(){S(this,$e,!1),this.wrapper.classList.remove(styles$1.expanded),p(this,Ce).textContent="▼"},"#collapse"),jt=a(function(){S(this,Ze,setInterval(()=>{b(this,_,Wt).call(this)},450))},"#startHeaderUpdateLoop"),Bt=a(function(){p(this,Ze)&&(clearInterval(p(this,Ze)),S(this,Ze,null))},"#stopHeaderUpdateLoop"),Wt=a(function(){if(!p(this,Q)||p(this,Be))return;if(p(this,ie).textContent===p(this,Q)){S(this,Q,null);return}const t=p(this,Q);S(this,Q,null),b(this,_,Vt).call(this,t)},"#checkAndUpdateHeader"),Vt=a(function(t){S(this,Be,!0),p(this,ie).classList.add(styles$1.fadeOut),setTimeout(()=>{p(this,ie).textContent=t,p(this,ie).classList.remove(styles$1.fadeOut),p(this,ie).classList.add(styles$1.fadeIn),setTimeout(()=>{p(this,ie).classList.remove(styles$1.fadeIn),S(this,Be,!1)},300)},150)},"#animateTextChange"),Fe=a(function(t){p(this,je).className=styles$1.indicator,p(this,je).classList.add(styles$1[t])},"#updateStatusIndicator"),vt=a(function(){setTimeout(()=>{p(this,ye).scrollTop=p(this,ye).scrollHeight},0)},"#scrollToBottom"),kt=a(function(){const t=[],o=p(this,B).task;o&&t.push(b(this,_,Gt).call(this,o));const n=p(this,B).history;for(const r of n)t.push(...b(this,_,Ht).call(this,r));p(this,ye).innerHTML=t.join(""),b(this,_,vt).call(this)},"#renderHistory"),Gt=a(function(t){return createCard({icon:"🎯",content:t,type:"input"})},"#createTaskCard"),Ht=a(function(t){const o=[],n=t.type==="step"&&t.stepIndex!==void 0?p(this,j).t("ui.panel.step",{number:(t.stepIndex+1).toString()}):void 0;if(t.type==="step"){if(t.reflection){const i=createReflectionLines(t.reflection);i.length>0&&o.push(createCard({icon:"🧠",content:i,meta:n}))}const r=t.action;r&&o.push(...b(this,_,Jt).call(this,r,n))}else if(t.type==="observation")o.push(createCard({icon:"👁️",content:t.content||"",meta:n,type:"observation"}));else if(t.type==="user_takeover")o.push(createCard({icon:"👤",content:"User takeover",meta:n,type:"input"}));else if(t.type==="retry"){const r=`${t.message||"Retrying"} (${t.attempt}/${t.maxAttempts})`;o.push(createCard({icon:"🔄",content:r,meta:n,type:"observation"}))}else t.type==="error"&&o.push(createCard({icon:"❌",content:t.message||"Error",meta:n,type:"observation"}));return o},"#createHistoryCards"),Jt=a(function(t,o){const n=[];if(t.name==="done"){const i=t.input.text||t.output||"";i&&n.push(createCard({icon:"🤖",content:i,meta:o,type:"output"}))}else if(t.name==="ask_user"){const r=t.input,i=t.output.replace(/^User answered:\s*/i,"");n.push(createCard({icon:"❓",content:`Question: ${r.question||""}`,meta:o,type:"question"})),n.push(createCard({icon:"💬",content:`Answer: ${i}`,meta:o,type:"input"}))}else{const r=b(this,_,yt).call(this,t.name,t.input);n.push(createCard({icon:"🔨",content:r,meta:o})),t.output?.length>0&&n.push(createCard({icon:"🔨",content:t.output,meta:o,type:"output"}))}return n},"#createActionCards"),a(pt,"Panel");let Panel=pt;const ht=class ht extends PageAgentCore{panel;constructor(t){const o=new PageController({...t,enableMask:t.enableMask??!0});super({...t,pageController:o}),this.panel=new Panel(this,{language:t.language})}};a(ht,"PageAgent");let PageAgent=ht;window.pageAgent&&window.pageAgent.dispose(),window.PageAgent=PageAgent,console.log("🚀 page-agent.js loaded!");/* SiteAgent: auto-init removed */function computeBorderGeometry(e,t,o,n){const r=Math.max(1,Math.min(e,t)),i=Math.min(o,20),c=Math.min(i+n,r),l=Math.min(c,Math.floor(e/2)),d=Math.min(c,Math.floor(t/2)),h=a(w=>w/e*2-1,"toClipX"),f=a(w=>w/t*2-1,"toClipY"),g=0,m=e,T=0,I=t,A=l,C=e-l,D=d,v=t-d,k=h(g),O=h(m),Ie=f(T),H=f(I),le=h(A),ue=h(C),q=f(D),de=f(v),pe=0,Ke=0,he=1,Xe=1,Qe=l/e,_e=1-l/e,fe=d/t,u=1-d/t,y=new Float32Array([k,Ie,O,Ie,k,q,k,q,O,Ie,O,q,k,de,O,de,k,H,k,H,O,de,O,H,k,q,le,q,k,de,k,de,le,q,le,de,ue,q,O,q,ue,de,ue,de,O,q,O,de]),P=new Float32Array([pe,Ke,he,Ke,pe,fe,pe,fe,he,Ke,he,fe,pe,u,he,u,pe,Xe,pe,Xe,he,u,he,Xe,pe,fe,Qe,fe,pe,u,pe,u,Qe,fe,Qe,u,_e,fe,he,fe,_e,u,_e,u,he,fe,he,u]);return{positions:y,uvs:P}}a(computeBorderGeometry,"computeBorderGeometry");function compileShader(e,t,o){const n=e.createShader(t);if(!n)throw new Error("Failed to create shader");if(e.shaderSource(n,o),e.compileShader(n),!e.getShaderParameter(n,e.COMPILE_STATUS)){const r=e.getShaderInfoLog(n)||"Unknown shader error";throw e.deleteShader(n),new Error(r)}return n}a(compileShader,"compileShader");function createProgram(e,t,o){const n=compileShader(e,e.VERTEX_SHADER,t),r=compileShader(e,e.FRAGMENT_SHADER,o),i=e.createProgram();if(!i)throw new Error("Failed to create program");if(e.attachShader(i,n),e.attachShader(i,r),e.linkProgram(i),!e.getProgramParameter(i,e.LINK_STATUS)){const s=e.getProgramInfoLog(i)||"Unknown link error";throw e.deleteProgram(i),e.deleteShader(n),e.deleteShader(r),new Error(s)}return e.deleteShader(n),e.deleteShader(r),i}a(createProgram,"createProgram");const fragmentShaderSource=`#version 300 es
precision lowp float;
in vec2 vUV;
out vec4 outColor;
uniform vec2 uResolution;
uniform float uTime;
uniform float uBorderWidth;
uniform float uGlowWidth;
uniform float uBorderRadius;
uniform vec3 uColors[4];
uniform float uGlowExponent;
uniform float uGlowFactor;
const float PI = 3.14159265359;
const float TWO_PI = 2.0 * PI;
const float HALF_PI = 0.5 * PI;
const vec4 startPositions = vec4(0.0, PI, HALF_PI, 1.5 * PI);
const vec4 speeds = vec4(-1.9, -1.9, -1.5, 2.1);
const vec4 innerRadius = vec4(PI * 0.8, PI * 0.7, PI * 0.3, PI * 0.1);
const vec4 outerRadius = vec4(PI * 1.2, PI * 0.9, PI * 0.6, PI * 0.4);
float random(vec2 st) {
return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453123);
}
vec2 random2(vec2 st) {
return vec2(random(st), random(st + 1.0));
}
float aaStep(float edge, float d) {
float width = fwidth(d);
return smoothstep(edge - width * 0.5, edge + width * 0.5, d);
}
float aaFract(float x) {
float f = fract(x);
float w = fwidth(x);
float smooth_f = f * (1.0 - smoothstep(1.0 - w, 1.0, f));
return smooth_f;
}
float sdRoundedBox(in vec2 p, in vec2 b, in float r) {
vec2 q = abs(p) - b + r;
return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r;
}
float getInnerGlow(vec2 p, vec2 b, float radius) {
float dist_x = b.x - abs(p.x);
float dist_y = b.y - abs(p.y);
float glow_x = smoothstep(radius, 0.0, dist_x);
float glow_y = smoothstep(radius, 0.0, dist_y);
return 1.0 - (1.0 - glow_x) * (1.0 - glow_y);
}
float getVignette(vec2 uv) {
vec2 vignetteUv = uv;
vignetteUv = vignetteUv * (1.0 - vignetteUv);
float vignette = vignetteUv.x * vignetteUv.y * 25.0;
vignette = pow(vignette, 0.16);
vignette = 1.0 - vignette;
return vignette;
}
float uvToAngle(vec2 uv) {
vec2 center = vec2(0.5);
vec2 dir = uv - center;
return atan(dir.y, dir.x) + PI;
}
void main() {
vec2 uv = vUV;
vec2 pos = uv * uResolution;
vec2 centeredPos = pos - uResolution * 0.5;
vec2 size = uResolution - uBorderWidth;
vec2 halfSize = size * 0.5;
float dBorderBox = sdRoundedBox(centeredPos, halfSize, uBorderRadius);
float border = aaStep(0.0, dBorderBox);
float glow = getInnerGlow(centeredPos, halfSize, uGlowWidth);
float vignette = getVignette(uv);
glow *= vignette;
float posAngle = uvToAngle(uv);
vec4 lightCenter = mod(startPositions + speeds * uTime, TWO_PI);
vec4 angleDist = abs(posAngle - lightCenter);
vec4 disToLight = min(angleDist, TWO_PI - angleDist) / TWO_PI;
float intensityBorder[4];
intensityBorder[0] = 1.0;
intensityBorder[1] = smoothstep(0.4, 0.0, disToLight.y);
intensityBorder[2] = smoothstep(0.4, 0.0, disToLight.z);
intensityBorder[3] = smoothstep(0.2, 0.0, disToLight.w) * 0.5;
vec3 borderColor = vec3(0.0);
for(int i = 0; i < 4; i++) {
borderColor = mix(borderColor, uColors[i], intensityBorder[i]);
}
borderColor *= 1.1;
borderColor = clamp(borderColor, 0.0, 1.0);
float intensityGlow[4];
intensityGlow[0] = smoothstep(0.9, 0.0, disToLight.x);
intensityGlow[1] = smoothstep(0.7, 0.0, disToLight.y);
intensityGlow[2] = smoothstep(0.4, 0.0, disToLight.z);
intensityGlow[3] = smoothstep(0.1, 0.0, disToLight.w) * 0.7;
vec4 breath = smoothstep(0.0, 1.0, sin(uTime * 1.0 + startPositions * PI) * 0.2 + 0.8);
vec3 glowColor = vec3(0.0);
glowColor += uColors[0] * intensityGlow[0] * breath.x;
glowColor += uColors[1] * intensityGlow[1] * breath.y;
glowColor += uColors[2] * intensityGlow[2] * breath.z;
glowColor += uColors[3] * intensityGlow[3] * breath.w * glow;
glow = pow(glow, uGlowExponent);
glow *= random(pos + uTime) * 0.1 + 1.0;
glowColor *= glow * uGlowFactor;
glowColor = clamp(glowColor, 0.0, 1.0);
vec3 color = mix(glowColor, borderColor + glowColor * 0.2, border);
float alpha = mix(glow, 1.0, border);
outColor = vec4(color, alpha);
}`,vertexShaderSource=`#version 300 es
in vec2 aPosition;
in vec2 aUV;
out vec2 vUV;
void main() {
vUV = aUV;
gl_Position = vec4(aPosition, 0.0, 1.0);
}`;const DEFAULT_COLORS=["rgb(57, 182, 255)","rgb(189, 69, 251)","rgb(255, 87, 51)","rgb(255, 214, 0)"];function parseColor(e){const t=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!t)throw new Error(`Invalid color format: ${e}`);const[,o,n,r]=t;return[parseInt(o)/255,parseInt(n)/255,parseInt(r)/255]}a(parseColor,"parseColor");const ft=class ft{element;canvas;options;running=!1;disposed=!1;startTime=0;lastTime=0;rafId=null;glr;observer;constructor(t={}){this.options={width:t.width??600,height:t.height??600,ratio:t.ratio??window.devicePixelRatio??1,borderWidth:t.borderWidth??8,glowWidth:t.glowWidth??200,borderRadius:t.borderRadius??8,mode:t.mode??"light",...t},this.canvas=document.createElement("canvas"),this.options.classNames&&(this.canvas.className=this.options.classNames),this.options.styles&&Object.assign(this.canvas.style,this.options.styles),this.canvas.style.display="block",this.canvas.style.transformOrigin="center",this.canvas.style.pointerEvents="none",this.element=this.canvas,this.setupGL(),this.options.skipGreeting||this.greet()}start(){if(this.disposed)throw new Error("Motion instance has been disposed.");if(this.running)return;if(!this.glr){console.error("WebGL resources are not initialized.");return}this.running=!0,this.startTime=performance.now(),this.resize(this.options.width??600,this.options.height??600,this.options.ratio),this.glr.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.glr.gl.useProgram(this.glr.program),this.glr.gl.uniform2f(this.glr.uResolution,this.canvas.width,this.canvas.height),this.checkGLError(this.glr.gl,"start: after initial setup");const t=a(()=>{if(!this.running||!this.glr)return;this.rafId=requestAnimationFrame(t);const o=performance.now();if(o-this.lastTime<1e3/32)return;this.lastTime=o;const r=(o-this.startTime)*.001;this.render(r)},"loop");this.rafId=requestAnimationFrame(t)}pause(){if(this.disposed)throw new Error("Motion instance has been disposed.");this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId)}dispose(){if(this.disposed)return;this.disposed=!0,this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId);const{gl:t,vao:o,positionBuffer:n,uvBuffer:r,program:i}=this.glr;o&&t.deleteVertexArray(o),n&&t.deleteBuffer(n),r&&t.deleteBuffer(r),t.deleteProgram(i),this.observer&&this.observer.disconnect(),this.canvas.remove()}resize(t,o,n){if(this.disposed)throw new Error("Motion instance has been disposed.");if(this.options.width=t,this.options.height=o,n&&(this.options.ratio=n),!this.running)return;const{gl:r,program:i,vao:s,positionBuffer:c,uvBuffer:l,uResolution:d}=this.glr,h=n??this.options.ratio??window.devicePixelRatio??1,f=Math.max(1,Math.floor(t*h)),g=Math.max(1,Math.floor(o*h));this.canvas.style.width=`${t}px`,this.canvas.style.height=`${o}px`,(this.canvas.width!==f||this.canvas.height!==g)&&(this.canvas.width=f,this.canvas.height=g),r.viewport(0,0,this.canvas.width,this.canvas.height),this.checkGLError(r,"resize: after viewport setup");const{positions:m,uvs:T}=computeBorderGeometry(this.canvas.width,this.canvas.height,this.options.borderWidth*h,this.options.glowWidth*h);r.bindVertexArray(s),r.bindBuffer(r.ARRAY_BUFFER,c),r.bufferData(r.ARRAY_BUFFER,m,r.STATIC_DRAW);const I=r.getAttribLocation(i,"aPosition");r.enableVertexAttribArray(I),r.vertexAttribPointer(I,2,r.FLOAT,!1,0,0),this.checkGLError(r,"resize: after position buffer update"),r.bindBuffer(r.ARRAY_BUFFER,l),r.bufferData(r.ARRAY_BUFFER,T,r.STATIC_DRAW);const A=r.getAttribLocation(i,"aUV");r.enableVertexAttribArray(A),r.vertexAttribPointer(A,2,r.FLOAT,!1,0,0),this.checkGLError(r,"resize: after UV buffer update"),r.useProgram(i),r.uniform2f(d,this.canvas.width,this.canvas.height),r.uniform1f(this.glr.uBorderWidth,this.options.borderWidth*h),r.uniform1f(this.glr.uGlowWidth,this.options.glowWidth*h),r.uniform1f(this.glr.uBorderRadius,this.options.borderRadius*h),this.checkGLError(r,"resize: after uniform updates");const C=performance.now();this.lastTime=C;const D=(C-this.startTime)*.001;this.render(D)}autoResize(t){this.observer&&this.observer.disconnect(),this.observer=new ResizeObserver(()=>{const o=t.getBoundingClientRect();this.resize(o.width,o.height)}),this.observer.observe(t)}fadeIn(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((t,o)=>{const n=this.canvas.animate([{opacity:0,transform:"scale(1.2)"},{opacity:1,transform:"scale(1)"}],{duration:300,easing:"ease-out",fill:"forwards"});n.onfinish=()=>t(),n.oncancel=()=>o("canceled")})}fadeOut(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((t,o)=>{const n=this.canvas.animate([{opacity:1,transform:"scale(1)"},{opacity:0,transform:"scale(1.2)"}],{duration:300,easing:"ease-in",fill:"forwards"});n.onfinish=()=>t(),n.oncancel=()=>o("canceled")})}checkGLError(t,o){let n=t.getError();if(n!==t.NO_ERROR){for(console.group(`🔴 WebGL Error in ${o}`);n!==t.NO_ERROR;){const r=this.getGLErrorName(t,n);console.error(`${r} (0x${n.toString(16)})`),n=t.getError()}console.groupEnd()}}getGLErrorName(t,o){switch(o){case t.INVALID_ENUM:return"INVALID_ENUM";case t.INVALID_VALUE:return"INVALID_VALUE";case t.INVALID_OPERATION:return"INVALID_OPERATION";case t.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case t.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case t.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"UNKNOWN_ERROR"}}setupGL(){const t=this.canvas.getContext("webgl2",{antialias:!1,alpha:!0});if(!t)throw new Error("WebGL2 is required but not available.");const o=createProgram(t,vertexShaderSource,fragmentShaderSource);this.checkGLError(t,"setupGL: after createProgram");const n=t.createVertexArray();t.bindVertexArray(n),this.checkGLError(t,"setupGL: after VAO creation");const r=this.canvas.width||2,i=this.canvas.height||2,{positions:s,uvs:c}=computeBorderGeometry(r,i,this.options.borderWidth,this.options.glowWidth),l=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,l),t.bufferData(t.ARRAY_BUFFER,s,t.STATIC_DRAW);const d=t.getAttribLocation(o,"aPosition");t.enableVertexAttribArray(d),t.vertexAttribPointer(d,2,t.FLOAT,!1,0,0),this.checkGLError(t,"setupGL: after position buffer setup");const h=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,h),t.bufferData(t.ARRAY_BUFFER,c,t.STATIC_DRAW);const f=t.getAttribLocation(o,"aUV");t.enableVertexAttribArray(f),t.vertexAttribPointer(f,2,t.FLOAT,!1,0,0),this.checkGLError(t,"setupGL: after UV buffer setup");const g=t.getUniformLocation(o,"uResolution"),m=t.getUniformLocation(o,"uTime"),T=t.getUniformLocation(o,"uBorderWidth"),I=t.getUniformLocation(o,"uGlowWidth"),A=t.getUniformLocation(o,"uBorderRadius"),C=t.getUniformLocation(o,"uColors"),D=t.getUniformLocation(o,"uGlowExponent"),v=t.getUniformLocation(o,"uGlowFactor");t.useProgram(o),t.uniform1f(T,this.options.borderWidth),t.uniform1f(I,this.options.glowWidth),t.uniform1f(A,this.options.borderRadius),this.options.mode==="dark"?(t.uniform1f(D,2),t.uniform1f(v,1.8)):(t.uniform1f(D,1),t.uniform1f(v,1));const k=(this.options.colors||DEFAULT_COLORS).map(parseColor);for(let O=0;O<k.length;O++)t.uniform3f(t.getUniformLocation(o,`uColors[${O}]`),...k[O]);this.checkGLError(t,"setupGL: after uniform setup"),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),this.glr={gl:t,program:o,vao:n,positionBuffer:l,uvBuffer:h,uResolution:g,uTime:m,uBorderWidth:T,uGlowWidth:I,uBorderRadius:A,uColors:C}}render(t){if(!this.glr)return;const{gl:o,program:n,vao:r,uTime:i}=this.glr;o.useProgram(n),o.bindVertexArray(r),o.uniform1f(i,t),o.disable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clearColor(0,0,0,0),o.clear(o.COLOR_BUFFER_BIT),o.drawArrays(o.TRIANGLES,0,24),this.checkGLError(o,"render: after draw call"),o.bindVertexArray(null)}greet(){console.log("%c🌈 ai-motion 0.4.8 🌈","background: linear-gradient(90deg, #39b6ff, #bd45fb, #ff5733, #ffd600); color: white; text-shadow: 0 0 2px rgba(0, 0, 0, 0.2); font-weight: bold; font-size: 1em; padding: 2px 12px; border-radius: 6px;")}};a(ft,"Motion");let Motion=ft;function hasDarkModeClass(){const e=["dark","dark-mode","theme-dark","night","night-mode"],t=document.documentElement,o=document.body||document.documentElement;for(const r of e)if(t.classList.contains(r)||o?.classList.contains(r))return!0;return!!t.getAttribute("data-theme")?.toLowerCase().includes("dark")}a(hasDarkModeClass,"hasDarkModeClass");function parseRgbColor(e){const t=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(e);return t?{r:parseInt(t[1]),g:parseInt(t[2]),b:parseInt(t[3])}:null}a(parseRgbColor,"parseRgbColor");function isColorDark(e,t=128){if(!e||e==="transparent"||e.startsWith("rgba(0, 0, 0, 0)"))return!1;const o=parseRgbColor(e);return o?.299*o.r+.587*o.g+.114*o.b<t:!1}a(isColorDark,"isColorDark");function isBackgroundDark(){const e=window.getComputedStyle(document.documentElement),t=window.getComputedStyle(document.body||document.documentElement),o=e.backgroundColor,n=t.backgroundColor;return isColorDark(n)?!0:n==="transparent"||n.startsWith("rgba(0, 0, 0, 0)")?isColorDark(o):!1}a(isBackgroundDark,"isBackgroundDark");function isPageDark(){try{return!!(hasDarkModeClass()||isBackgroundDark())}catch(e){return console.warn("Error determining if page is dark:",e),!1}}a(isPageDark,"isPageDark");const wrapper="_wrapper_gf8tz_1",styles={wrapper},cursor="_cursor_1dgwb_2",cursorBorder="_cursorBorder_1dgwb_10",cursorFilling="_cursorFilling_1dgwb_25",cursorRipple="_cursorRipple_1dgwb_39",clicking="_clicking_1dgwb_57",cursorStyles={cursor,cursorBorder,cursorFilling,cursorRipple,clicking},gt=class gt{constructor(){Z(this,Ne);oe(this,"shown",!1);oe(this,"wrapper",document.createElement("div"));oe(this,"motion",null);Z(this,Y,document.createElement("div"));Z(this,ae,0);Z(this,ce,0);Z(this,Se,0);Z(this,Te,0);this.wrapper.id="page-agent-runtime_simulator-mask",this.wrapper.className=styles.wrapper,this.wrapper.setAttribute("data-browser-use-ignore","true"),this.wrapper.setAttribute("data-page-agent-ignore","true");try{const t=new Motion({mode:isPageDark()?"dark":"light",styles:{position:"absolute",inset:"0"}});this.motion=t,this.wrapper.appendChild(t.element),t.autoResize(this.wrapper)}catch(t){console.warn("[SimulatorMask] Motion overlay unavailable:",t)}this.wrapper.addEventListener("click",t=>{t.stopPropagation(),t.preventDefault()}),this.wrapper.addEventListener("mousedown",t=>{t.stopPropagation(),t.preventDefault()}),this.wrapper.addEventListener("mouseup",t=>{t.stopPropagation(),t.preventDefault()}),this.wrapper.addEventListener("mousemove",t=>{t.stopPropagation(),t.preventDefault()}),this.wrapper.addEventListener("wheel",t=>{t.stopPropagation(),t.preventDefault()}),this.wrapper.addEventListener("keydown",t=>{t.stopPropagation(),t.preventDefault()}),this.wrapper.addEventListener("keyup",t=>{t.stopPropagation(),t.preventDefault()}),b(this,Ne,Yt).call(this),document.body.appendChild(this.wrapper),b(this,Ne,Et).call(this),window.addEventListener("PageAgent::MovePointerTo",t=>{const{x:o,y:n}=t.detail;this.setCursorPosition(o,n)}),window.addEventListener("PageAgent::ClickPointer",t=>{this.triggerClickAnimation()})}setCursorPosition(t,o){S(this,Se,t),S(this,Te,o)}triggerClickAnimation(){p(this,Y).classList.remove(cursorStyles.clicking),p(this,Y).offsetHeight,p(this,Y).classList.add(cursorStyles.clicking)}show(){this.shown||(this.shown=!0,this.motion?.start(),this.motion?.fadeIn(),this.wrapper.style.display="block",S(this,ae,window.innerWidth/2),S(this,ce,window.innerHeight/2),S(this,Se,p(this,ae)),S(this,Te,p(this,ce)),p(this,Y).style.left=`${p(this,ae)}px`,p(this,Y).style.top=`${p(this,ce)}px`)}hide(){this.shown&&(this.shown=!1,this.motion?.fadeOut(),this.motion?.pause(),p(this,Y).classList.remove(cursorStyles.clicking),setTimeout(()=>{this.wrapper.style.display="none"},800))}dispose(){this.motion?.dispose(),this.wrapper.remove()}};Y=new WeakMap,ae=new WeakMap,ce=new WeakMap,Se=new WeakMap,Te=new WeakMap,Ne=new WeakSet,Yt=a(function(){p(this,Y).className=cursorStyles.cursor;const t=document.createElement("div");t.className=cursorStyles.cursorRipple,p(this,Y).appendChild(t);const o=document.createElement("div");o.className=cursorStyles.cursorFilling,p(this,Y).appendChild(o);const n=document.createElement("div");n.className=cursorStyles.cursorBorder,p(this,Y).appendChild(n),this.wrapper.appendChild(p(this,Y))},"#createCursor"),Et=a(function(){const t=p(this,ae)+(p(this,Se)-p(this,ae))*.2,o=p(this,ce)+(p(this,Te)-p(this,ce))*.2,n=Math.abs(t-p(this,Se));n>0&&(n<2?S(this,ae,p(this,Se)):S(this,ae,t),p(this,Y).style.left=`${p(this,ae)}px`);const r=Math.abs(o-p(this,Te));r>0&&(r<2?S(this,ce,p(this,Te)):S(this,ce,o),p(this,Y).style.top=`${p(this,ce)}px`),requestAnimationFrame(()=>b(this,Ne,Et).call(this))},"#moveCursorToTarget"),a(gt,"SimulatorMask");let SimulatorMask=gt;const SimulatorMask$1=Object.freeze(Object.defineProperty({__proto__:null,SimulatorMask},Symbol.toStringTag,{value:"Module"}))})();
;

;
/* ═══════════════════════════════════════════════════════
   SiteAgent Custom UI v3 — visionOS Glassmorphism
   Created by Ginigen AI (지니젠AI)
   - 설정 패널 (사용자 API 키)
   - 멀티스텝 결과 누적
   - 대화 초기화
   - 트래킹 (/api/track)
   ═══════════════════════════════════════════════════════ */
(function(){
if(window.__SA_UI_LOADED) return;
/* ═══ SiteAgent Spotlight System v1.0 (inline) ═══ */
(function(){
'use strict';
if(window.__SA_SPOTLIGHT)return;
var css=document.createElement('style');css.id='__sa_spotlight_css';
css.textContent='#__sa_spot_ring{position:fixed;z-index:2147483643;pointer-events:none;border-radius:8px;opacity:0;transform:scale(1.06);transition:opacity .3s ease,transform .4s cubic-bezier(.34,1.56,.64,1),top .35s cubic-bezier(.22,1,.36,1),left .35s cubic-bezier(.22,1,.36,1),width .25s ease,height .25s ease;box-shadow:0 0 0 2px rgba(88,86,214,.85),0 0 0 5px rgba(88,86,214,.22),0 0 28px 4px rgba(88,86,214,.32),inset 0 0 12px rgba(88,86,214,.06)}#__sa_spot_ring.active{opacity:1;transform:scale(1);animation:__sa_breathe 2.2s ease-in-out infinite}@keyframes __sa_breathe{0%,100%{box-shadow:0 0 0 2px rgba(88,86,214,.85),0 0 0 5px rgba(88,86,214,.22),0 0 28px 4px rgba(88,86,214,.32),inset 0 0 12px rgba(88,86,214,.06)}50%{box-shadow:0 0 0 2.5px rgba(88,86,214,.65),0 0 0 8px rgba(88,86,214,.12),0 0 40px 8px rgba(88,86,214,.22),inset 0 0 16px rgba(88,86,214,.04)}}#__sa_spot_ring.clicking::after{content:"";position:absolute;inset:-10px;border:2px solid rgba(88,86,214,.5);border-radius:inherit;animation:__sa_click_ripple .55s ease-out forwards;pointer-events:none}@keyframes __sa_click_ripple{0%{transform:scale(.97);opacity:1}100%{transform:scale(1.18);opacity:0}}#__sa_spot_dim{position:fixed;inset:0;z-index:2147483638;background:rgba(0,0,0,.06);pointer-events:none;opacity:0;transition:opacity .4s ease}#__sa_spot_dim.active{opacity:1}#__sa_step_bar{position:fixed;top:16px;left:50%;transform:translateX(-50%) translateY(-64px);z-index:2147483644;background:rgba(28,28,30,.88);backdrop-filter:blur(24px) saturate(180%);-webkit-backdrop-filter:blur(24px) saturate(180%);color:#f5f5f7;padding:10px 22px 10px 16px;border-radius:100px;font-size:13px;font-weight:600;font-family:-apple-system,BlinkMacSystemFont,"Pretendard","Noto Sans KR",sans-serif;box-shadow:0 6px 28px rgba(0,0,0,.28),0 0 0 .5px rgba(255,255,255,.06) inset;transition:transform .5s cubic-bezier(.34,1.56,.64,1),opacity .3s ease;opacity:0;display:flex;align-items:center;gap:10px;pointer-events:none;user-select:none;-webkit-user-select:none;letter-spacing:-.2px;max-width:88vw;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}#__sa_step_bar.visible{transform:translateX(-50%) translateY(0);opacity:1}#__sa_step_bar .sb_dot{width:6px;height:6px;border-radius:50%;background:#5856D6;flex-shrink:0;animation:__sa_dot_beat 1.2s ease-in-out infinite}@keyframes __sa_dot_beat{0%,100%{opacity:1;transform:scale(1)}50%{opacity:.3;transform:scale(.7)}}#__sa_step_bar .sb_ico{font-size:15px;flex-shrink:0;line-height:1}#__sa_step_bar .sb_txt{overflow:hidden;text-overflow:ellipsis}#__sa_step_bar .sb_cnt{display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:50%;background:rgba(88,86,214,.25);color:#a5a3ff;font-size:10px;font-weight:800;flex-shrink:0}#__sa_step_bar.done{background:rgba(34,197,94,.9);box-shadow:0 6px 28px rgba(34,197,94,.3),0 0 0 .5px rgba(255,255,255,.1) inset}#__sa_step_bar.fail{background:rgba(239,68,68,.9);box-shadow:0 6px 28px rgba(239,68,68,.3),0 0 0 .5px rgba(255,255,255,.1) inset}';
document.head.appendChild(css);
var ring=document.createElement('div');ring.id='__sa_spot_ring';ring.setAttribute('data-page-agent-ignore','true');ring.setAttribute('data-browser-use-ignore','true');
var dim=document.createElement('div');dim.id='__sa_spot_dim';dim.setAttribute('data-page-agent-ignore','true');
var bar=document.createElement('div');bar.id='__sa_step_bar';bar.setAttribute('data-page-agent-ignore','true');bar.setAttribute('data-browser-use-ignore','true');
bar.innerHTML='<span class="sb_dot"></span><span class="sb_cnt"></span><span class="sb_ico"></span><span class="sb_txt"></span>';
function mount(){if(!document.body)return;if(!ring.parentElement)document.body.appendChild(dim);if(!ring.parentElement)document.body.appendChild(ring);if(!bar.parentElement)document.body.appendChild(bar);}
mount();if(!document.body)document.addEventListener('DOMContentLoaded',mount);
var _spotTimer=null,_dimTimer=null,_stepCount=0,_barHideTimer=null;
function spotlightAt(x,y){mount();var el=document.elementFromPoint(x,y);if(!el||el===ring||el===bar||el===dim)return;var r=el.getBoundingClientRect();var pad=6;ring.style.top=(r.top-pad)+'px';ring.style.left=(r.left-pad)+'px';ring.style.width=(r.width+pad*2)+'px';ring.style.height=(r.height+pad*2)+'px';try{var cs=window.getComputedStyle(el);var br=parseInt(cs.borderRadius)||0;ring.style.borderRadius=Math.max(br+2,6)+'px';}catch(e){ring.style.borderRadius='8px';}ring.classList.add('active');ring.classList.remove('clicking');dim.classList.add('active');clearTimeout(_dimTimer);clearTimeout(_spotTimer);_spotTimer=setTimeout(function(){ring.classList.remove('active');_dimTimer=setTimeout(function(){dim.classList.remove('active');},300);},2800);}
function clickEffect(){ring.classList.remove('clicking');void ring.offsetHeight;ring.classList.add('clicking');}
function clearSpotlight(){ring.classList.remove('active','clicking');dim.classList.remove('active');clearTimeout(_spotTimer);clearTimeout(_dimTimer);}
function showStep(icon,text,type){mount();bar.querySelector('.sb_ico').textContent=icon||'';bar.querySelector('.sb_txt').textContent=text||'';bar.querySelector('.sb_cnt').textContent=_stepCount||'';bar.className='';bar.id='__sa_step_bar';if(type==='done')bar.classList.add('done');if(type==='fail')bar.classList.add('fail');clearTimeout(_barHideTimer);requestAnimationFrame(function(){bar.classList.add('visible');});}
function hideStep(delay){clearTimeout(_barHideTimer);_barHideTimer=setTimeout(function(){bar.classList.remove('visible');},delay||0);}
function getLabel(tool,input){var inp=input||{};switch(tool){case 'click_element_by_index':return['🖱️','요소 클릭 중...'];case 'input_text':var t=(inp.text||'').slice(0,24);return['⌨️',t?'"'+t+'" 입력 중...':'텍스트 입력 중...'];case 'select_dropdown_option':var o=(inp.text||'').slice(0,20);return['☑️',o?'"'+o+'" 선택 중...':'옵션 선택 중...'];case 'scroll':return['📜',inp.down===false?'위로 스크롤 중...':'아래로 스크롤 중...'];case 'scroll_horizontally':return['↔️','가로 스크롤 중...'];case 'wait':return['⏳',(inp.seconds||1)+'초 대기 중...'];case 'execute_javascript':return['⚡','스크립트 실행 중...'];case 'ask_user':return['💬','사용자 응답 대기 중...'];case 'done':return['✅',inp.success===false?'작업이 중단되었습니다':'작업 완료!'];default:return['🔧',tool+' 실행 중...'];}}
window.addEventListener('PageAgent::MovePointerTo',function(e){if(e.detail)spotlightAt(e.detail.x,e.detail.y);});
window.addEventListener('PageAgent::ClickPointer',function(){clickEffect();});
window.addEventListener('popstate',clearSpotlight);window.addEventListener('hashchange',clearSpotlight);
window.addEventListener('beforeunload',function(){clearSpotlight();hideStep(0);});
function hookAgent(ag){if(!ag)return;
if(ag.pageController){ag.pageController.addEventListener('afterUpdate',function(){var fns=window._highlightCleanupFunctions||[];for(var i=0;i<fns.length;i++){try{if(typeof fns[i]==='function')fns[i]();}catch(e){}}window._highlightCleanupFunctions=[];var container=document.getElementById('playwright-highlight-container');if(container)container.innerHTML='';});}
_stepCount=0;
ag.addEventListener('activity',function(e){var d=e.detail;if(!d)return;switch(d.type){case 'thinking':showStep('🧠','페이지 분석 중...','');break;case 'executing':_stepCount++;var label=getLabel(d.tool,d.input);showStep(label[0],label[1],'');break;case 'retrying':showStep('🔄','재시도 중... ('+(d.attempt||'')+'/'+(d.maxAttempts||'')+')','');break;case 'error':showStep('❌','오류 발생','fail');hideStep(4000);break;}});
ag.addEventListener('statuschange',function(){var s=ag.status;if(s==='completed'){clearSpotlight();showStep('✅','작업이 완료되었습니다!','done');hideStep(3500);_stepCount=0;}else if(s==='error'){clearSpotlight();showStep('❌','작업 중 오류가 발생했습니다','fail');hideStep(4000);_stepCount=0;}});
ag.addEventListener('dispose',function(){clearSpotlight();hideStep(0);_stepCount=0;});}
window.__SA_SPOTLIGHT={hookAgent:hookAgent,spotlight:spotlightAt,click:clickEffect,clear:clearSpotlight,showStep:showStep,hideStep:hideStep,dispose:function(){clearSpotlight();hideStep(0);css.remove();ring.remove();dim.remove();bar.remove();}};
})();
/* ═══ End Spotlight System ═══ */

window.__SA_UI_LOADED = true;

window.__SA_INIT_UI = function(agent){
  console.log('[SA-UI] INIT called');
  if(window.__SA_SPOTLIGHT) window.__SA_SPOTLIGHT.hookAgent(agent);
  initUI(agent);
};
console.log('[SA-UI] __SA_INIT_UI registered');

function initUI(SA){

/* ── 기본 UI 숨기기 ── */
function hidePA(){
  ['._wrapper_gtdpc_1','._historySectionWrapper_gtdpc_246',
   '._inputSectionWrapper_gtdpc_539','._wrapper_gf8tz_1'].forEach(function(s){
    document.querySelectorAll(s).forEach(function(el){
      el.style.cssText='opacity:0!important;pointer-events:none!important;position:fixed!important;left:-9999px!important;top:-9999px!important;width:1px!important;height:1px!important;overflow:hidden!important;';
    });
  });
}
hidePA();
new MutationObserver(hidePA).observe(document.body,{childList:true,subtree:true});
var _hc=0,_hi=setInterval(function(){hidePA();if(++_hc>6)clearInterval(_hi);},250);

/* Panel 무력화 */
try{
  if(SA.panel){SA.panel.show=function(){};SA.panel.hide=function(){};SA.panel.expand=function(){};SA.panel.collapse=function(){};if(SA.panel.wrapper)SA.panel.wrapper.remove();}
}catch(ex){}

/* ── 트래킹 ── */
var _BASE = window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space';
function _logTask(type,input,output){
  try{var em=window.__SA_USER_EMAIL||'';if(!em||!input)return;
  fetch(_BASE+'/api/task/log',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email:em,type:type,input:(input||'').substring(0,1000),output:(output||'').substring(0,1000),url:location.href||'',title:document.title||''}),mode:'cors'}).catch(function(){});}catch(e){}
}
var _SID = 'sa_'+Math.random().toString(36).substr(2,9)+'_'+Date.now();

/* ── 디바이스 환경 수집 (1회) ── */
var _saDeviceInfo = (function(){
  var ua = navigator.userAgent || '';
  var os = 'unknown';
  if(/Windows/.test(ua)) os='Windows';
  else if(/Mac/.test(ua)) os='macOS';
  else if(/Linux/.test(ua)) os='Linux';
  else if(/Android/.test(ua)) os='Android';
  else if(/iPhone|iPad/.test(ua)) os='iOS';
  else if(/CrOS/.test(ua)) os='ChromeOS';
  var br = 'unknown';
  if(/Edg\//.test(ua)) br='Edge';
  else if(/Chrome\//.test(ua)) br='Chrome';
  else if(/Firefox\//.test(ua)) br='Firefox';
  else if(/Safari\//.test(ua)&&!/Chrome/.test(ua)) br='Safari';
  else if(/OPR\//.test(ua)) br='Opera';
  var scr = screen.width+'x'+screen.height;
  var tz = ''; try{tz=Intl.DateTimeFormat().resolvedOptions().timeZone;}catch(e){}
  var lang = navigator.language||'';
  var client = (window.__SA_BASE && !window.chrome?.runtime?.id) ? 'bookmarklet' : (navigator.userAgent.includes('Edg') ? 'edge-ext' : 'chrome-ext');
  return {os:os,browser:br,screen:scr,timezone:tz,language:lang,client:client,referrer:document.referrer||''};
})();

/* ── 종합 분석 이벤트 전송 (스로틀링: 3초당 1회) ── */
var _saAnaQueue=[];
var _saAnaTimer=null;
function _saAna(event, extra){
  try{
    var d = {
      event: event,
      email: window.__SA_USER_EMAIL||'',
      domain: location.hostname,
      url: location.href.substr(0,500),
      session_id: _SID,
      provider: (typeof settings!=='undefined' && settings.provider) || 'demo',
      os: _saDeviceInfo.os,
      browser: _saDeviceInfo.browser,
      screen: _saDeviceInfo.screen,
      timezone: _saDeviceInfo.timezone,
      language: _saDeviceInfo.language,
      client: _saDeviceInfo.client,
      referrer: _saDeviceInfo.referrer
    };
    if(extra)for(var k in extra)d[k]=extra[k];
    _saAnaQueue.push(d);
    if(!_saAnaTimer){
      _saAnaTimer=setTimeout(function(){
        var batch=_saAnaQueue.splice(0,5);
        batch.forEach(function(item){
          try{
            var body=JSON.stringify(item);
            if(navigator.sendBeacon) navigator.sendBeacon(_BASE+'/api/analytics', body);
            else fetch(_BASE+'/api/analytics',{method:'POST',body:body,headers:{'Content-Type':'application/json'},keepalive:true,mode:'cors'}).catch(function(){});
          }catch(e){}
        });
        _saAnaTimer=null;
        if(_saAnaQueue.length) _saAna('_flush');
      },3000);
    }
  }catch(e){}
}

function track(evt, extra){
  try{
    var d={event:evt,session_id:_SID,domain:location.hostname,ts:new Date().toISOString(),
           browser:navigator.userAgent.substr(0,60),lang:navigator.language};
    if(extra)for(var k in extra)d[k]=extra[k];
    navigator.sendBeacon?navigator.sendBeacon(_BASE+'/api/track',JSON.stringify(d)):
    fetch(_BASE+'/api/track',{method:'POST',body:JSON.stringify(d),headers:{'Content-Type':'application/json'},keepalive:true});
  }catch(e){}
}
track('install');
_saAna('page_view');

/* ── 설정 ── */
var LS_SET='__sa_settings3';
function loadSettings(){
  try{return JSON.assign({provider:'demo',apiKey:'',model:'',baseURL:'',language:'ko-KR'},JSON.parse(localStorage.getItem(LS_SET)||'{}'));}
  catch(e){return{provider:'demo',language:'ko-KR'};}
}
// fix: Object.assign
function loadSettings(){
  try{return Object.assign({provider:'demo',apiKey:'',model:'',baseURL:'',language:'ko-KR',marl_insight:false,marl_emergence:false,marl_engine:'invent'},JSON.parse(localStorage.getItem(LS_SET)||'{}'));}
  catch(e){return{provider:'demo',language:'ko-KR'};}
}
var settings=loadSettings();

/* ═══ Session Persistence (window.name + server) ═══ */
var _SA_SESSION_KEY = '__SA_SES__';
var _SA_SESSION_TTL = 30 * 60 * 1000; /* 30분 */

/* ── window.name에서 복원 ── */
function _sesRestore(){
  try{
    var raw = window.name || '';
    var idx = raw.indexOf(_SA_SESSION_KEY);
    if(idx === -1) return null;
    var json = raw.substring(idx + _SA_SESSION_KEY.length);
    var d = JSON.parse(json);
    if(!d || !d.ts) return null;
    if(Date.now() - d.ts > _SA_SESSION_TTL) return null; /* 만료 */
    console.log('[SiteAgent] Session restored from window.name', d.ts);
    return d;
  }catch(e){ return null; }
}

/* ── window.name에 저장 ── */
function _sesSave(chatHTML, lastCmd, viewMode){
  try{
    var d = {
      chat: (chatHTML||'').substring(0, 50000), /* 50KB 제한 */
      cmd: lastCmd || '',
      view: viewMode || 'main',
      url: location.href,
      title: document.title,
      ts: Date.now()
    };
    /* window.name에서 기존 세션 데이터 제거 후 추가 */
    var raw = window.name || '';
    var idx = raw.indexOf(_SA_SESSION_KEY);
    if(idx !== -1) raw = raw.substring(0, idx);
    window.name = raw + _SA_SESSION_KEY + JSON.stringify(d);
  }catch(e){}
}

/* ── 서버 세션 저장 ── */
function _sesSaveServer(chatHTML, lastCmd){
  var email = window.__SA_USER_EMAIL || '';
  if(!email || !_BASE) return;
  try{
    var payload = JSON.stringify({
      email: email,
      chat: (chatHTML||'').substring(0, 50000),
      cmd: lastCmd || '',
      url: location.href,
      title: document.title
    });
    if(navigator.sendBeacon){
      navigator.sendBeacon(_BASE + '/api/session/save', payload);
    } else {
      fetch(_BASE + '/api/session/save', {
        method:'POST', body:payload,
        headers:{'Content-Type':'application/json'},
        keepalive:true, mode:'cors'
      }).catch(function(){});
    }
  }catch(e){}
}

/* ── 서버 세션 로드 ── */
function _sesLoadServer(callback){
  var email = window.__SA_USER_EMAIL || '';
  if(!email || !_BASE){ callback(null); return; }
  fetch(_BASE + '/api/session/load?email=' + encodeURIComponent(email), {mode:'cors'})
  .then(function(r){ return r.ok ? r.json() : null; })
  .then(function(d){
    if(d && d.chat && d.ts && (Date.now() - d.ts*1000) < _SA_SESSION_TTL){
      console.log('[SiteAgent] Session restored from server');
      callback(d);
    } else { callback(null); }
  }).catch(function(){ callback(null); });
}

/* ── 이전 세션 복원 시도 ── */
var _restored = _sesRestore(); /* window.name 우선 */

/* ── beforeunload / visibilitychange 에서 저장 ── */
window.addEventListener('beforeunload', function(){
  var hist = document.getElementById('__sa_H');
  var chat = hist ? hist.innerHTML : '';
  var cmd = window.__SA_LAST_CMD || '';
  _sesSave(chat, cmd, _viewMode);
  _sesSaveServer(chat, cmd);
});
window.addEventListener('visibilitychange', function(){
  if(document.visibilityState === 'hidden'){
    var hist = document.getElementById('__sa_H');
    var chat = hist ? hist.innerHTML : '';
    var cmd = window.__SA_LAST_CMD || '';
    _sesSave(chat, cmd, _viewMode);
    _sesSaveServer(chat, cmd);
  }
});

/* ── 주기적 서버 동기화 (60초) ── */
setInterval(function(){
  var hist = document.getElementById('__sa_H');
  if(!hist) return;
  var chat = hist.innerHTML || '';
  if(chat.indexOf('text-align:center') !== -1 && !chat.includes('sa ')) return; /* 빈 상태 skip */
  _sesSaveServer(chat, window.__SA_LAST_CMD || '');
}, 60000);

/* ═══ End Session Persistence ═══ */

/* ── 팔레트 ── */
var C={
  fab1:'#5856D6',fab2:'#007AFF',
  glow:'rgba(88,86,214,.45)',glowHover:'rgba(88,86,214,.65)',
  accent:'#5856D6',accent2:'#007AFF',accentLight:'rgba(88,86,214,.1)',accentBorder:'rgba(88,86,214,.2)',
  green:'#30D158',orange:'#FF9F0A',red:'#FF453A',
  text:'#1c1c1e',sub:'#8e8e93',bg:'rgba(255,255,255,.82)',bgPanel:'rgba(248,248,250,.78)'
};

/* ── 사이트별 텍스트 추출 (Polaris Office 전용 + 범용) ── */
function _saExtractPageText(maxLen){
  maxLen=maxLen||8000;
  var host=location.hostname||'';
  var txt='';
  /* ── Polaris Office HWP 웹 에디터 ── */
  if(host.indexOf('polarisoffice.com')>=0){
    /* ★ 최우선: iframe 브릿지에서 수신한 텍스트 (cross-origin iframe 해결) */
    if(window.__SA_FRAME_TEXT&&window.__SA_FRAME_TEXT.length>30){
      return window.__SA_FRAME_TEXT.substring(0,maxLen);
    }
    /* S1: contenteditable (같은 origin인 경우) */
    var ce=document.querySelectorAll('[contenteditable="true"]');
    if(ce.length){ce.forEach(function(el){txt+=el.innerText+'\n';});}
    /* S2: 텍스트 레이어 */
    if(txt.length<50){
      var sels=['.text-layer','.textLayer','.page-text',
        'div[class*="text-layer"]','div[class*="editor-content"]',
        'div[class*="document-content"]','div[class*="page-content"]',
        'div[class*="page"]','div[class*="doc"]','div[class*="editor"]',
        'div[class*="para"]','div[class*="content"]','div[class*="viewer"]',
        'div[class*="hwp"]','div[class*="sheet"]','div[class*="cell"]'];
      var best='';
      sels.forEach(function(s){document.querySelectorAll(s).forEach(function(el){var t=el.innerText||'';if(t.length>best.length)best=t;});});
      if(best.length>30) txt=best;
    }
    /* S3: 사용자 선택 영역 */
    if(txt.length<50){var sel=window.getSelection();if(sel&&sel.toString().length>10)txt=sel.toString();}
    /* S4: #root 클린업 */
    if(txt.length<50){
      var root=document.querySelector('#root,#app,[id*="editor"],[id*="viewer"]');
      if(root){
        var cl=root.cloneNode(true);
        cl.querySelectorAll('header,nav,footer,button,[role="toolbar"],[role="menubar"],[class*="toolbar"],[class*="header"],[class*="menu"],[class*="sidebar"],[class*="footer"],[class*="modal"],[class*="ribbon"],[class*="status"]').forEach(function(e){e.remove();});
        txt=cl.innerText||'';
      }
    }
    if(txt.length>30) return txt.replace(/\s+/g,' ').trim().substring(0,maxLen);
  }
  /* ── Google Docs ── */
  if(host.indexOf('docs.google.com')>=0){
    var gd=document.querySelectorAll('.kix-paragraphrenderer');
    if(gd.length){gd.forEach(function(el){txt+=el.innerText+'\n';});}
    if(txt.length>30) return txt.replace(/\s+/g,' ').trim().substring(0,maxLen);
  }
  /* ── 범용 추출 ── */
  txt='';
  /* 브릿지 데이터가 있으면 우선 사용 (어떤 사이트든) */
  if(window.__SA_FRAME_TEXT&&window.__SA_FRAME_TEXT.length>30){
    return window.__SA_FRAME_TEXT.substring(0,maxLen);
  }
  var els=document.querySelectorAll('article,main,[role="main"],.content,.post,.entry');
  if(els.length){els.forEach(function(el){txt+=el.innerText+'\n';});}
  if(txt.length<100) txt=document.body.innerText||'';
  return txt.replace(/\s+/g,' ').trim().substring(0,maxLen);
}

/* ── CSS ── */
var sty=document.createElement('style');sty.id='__sa_css3';
sty.textContent=[
  '@keyframes saRing{0%{box-shadow:0 0 0 0 '+C.glow+',0 4px 20px '+C.glow+'}70%{box-shadow:0 0 0 10px rgba(88,86,214,0),0 4px 20px '+C.glow+'}100%{box-shadow:0 0 0 0 rgba(88,86,214,0),0 4px 20px '+C.glow+'}}',
  '#__sa_F{animation:saRing 2.5s ease infinite;}',
  '#__sa_F:hover{transform:scale(1.1)!important;}',
  '#__sa_F:active{transform:scale(0.92)!important;}',
  '#__sa_P{font-family:-apple-system,BlinkMacSystemFont,"SF Pro Display","Helvetica Neue",sans-serif!important;transition:opacity .25s,transform .25s;}',
  '#__sa_P *{box-sizing:border-box;font-family:inherit;}',
  '#__sa_P.sa-hidden{opacity:0!important;transform:translateY(8px) scale(.97)!important;pointer-events:none!important;}',
  '#__sa_P.sa-visible{opacity:1!important;transform:translateY(0) scale(1)!important;pointer-events:auto!important;}',
  '#__sa_H::-webkit-scrollbar{width:4px;}',
  '#__sa_H::-webkit-scrollbar-thumb{background:rgba(0,0,0,.1);border-radius:4px;}',
  '.su{padding:10px 14px;margin-bottom:8px;background:linear-gradient(135deg,rgba(88,86,214,.1),rgba(0,122,255,.06));border-radius:18px 18px 4px 18px;font-size:13px;color:'+C.text+';line-height:1.6;}',
  '.sa{padding:12px 14px;margin-bottom:10px;background:'+C.bg+';border-radius:4px 18px 18px 18px;font-size:13px;color:'+C.text+';line-height:1.7;box-shadow:0 2px 12px rgba(0,0,0,.06);border:.5px solid rgba(0,0,0,.04);}',
  '.sa p{margin:0 0 10px;line-height:1.8;}.sa p:last-child{margin:0;}',
  '.sa strong,.sa b{font-weight:700;color:#1a1a2e;}',
  '.sa blockquote{margin:8px 0 12px;padding:8px 12px;border-left:3px solid #5856D6;background:rgba(88,86,214,.03);border-radius:0 8px 8px 0;font-size:12px;color:#444;}',
  '.sa hr{margin:14px 0;border:none;height:1px;background:rgba(0,0,0,.06);}',
  '.sa pre{margin:8px 0;padding:10px;background:#1e1e2e;border-radius:8px;overflow-x:auto;}.sa pre code{font-size:11px;color:#e0e0e0;white-space:pre-wrap;}',
  '.sa code{background:rgba(88,86,214,.06);padding:1px 5px;border-radius:4px;font-size:11px;color:#5856D6;}',
  '.sa h1,.sa h2,.sa h3{font-weight:800;margin:16px 0 8px;font-size:14px;color:#1a1a2e;border-bottom:1.5px solid rgba(88,86,214,.08);padding-bottom:5px;display:block;clear:both;}',
  '.sa h3{font-size:12.5px;border:none;padding:0;margin:14px 0 6px;color:#333;}',
  '.sa ul{margin:8px 0 12px;padding:0;list-style:none;}.sa ul li{padding:4px 0 4px 16px;position:relative;line-height:1.7;margin-bottom:2px;}.sa ul li::before{content:"";position:absolute;left:2px;top:12px;width:5px;height:5px;border-radius:50%;background:'+C.accent+';}',
  '.sa ol{margin:6px 0;padding-left:20px;}.sa ol li{padding:3px 0;}',
  '.sa code{background:rgba(88,86,214,.06);border-radius:5px;padding:1px 6px;font-size:11.5px;font-family:"SF Mono",Menlo,monospace;color:#5856D6;}',
  '.sa pre{background:linear-gradient(135deg,#1c1c1e,#2c2c2e);border-radius:12px;padding:14px;overflow-x:auto;margin:8px 0;color:#e5e5ea;font-size:11.5px;font-family:"SF Mono",Menlo,monospace;line-height:1.55;}',
  '.sa pre code{background:none;color:inherit;padding:0;}',
  '.sa blockquote{border-left:3px solid '+C.accent+';margin:8px 0;padding:6px 12px;color:#636366;background:rgba(88,86,214,.03);border-radius:0 10px 10px 0;}',
  '.sa table{width:100%;border-collapse:separate;border-spacing:0;font-size:12px;margin:8px 0;border-radius:8px;overflow:hidden;border:1px solid rgba(0,0,0,.06);}',
  '.sa th{background:rgba(88,86,214,.06);padding:8px 10px;font-weight:700;text-align:left;color:'+C.accent+';}',
  '.sa td{padding:7px 10px;border-top:1px solid rgba(0,0,0,.04);}',
  '.sa tr:nth-child(even) td{background:rgba(0,0,0,.015);}',
  '.sa a{color:'+C.accent2+';text-decoration:none;border-bottom:1px solid rgba(0,122,255,.2);}',
  '.sa hr{border:none;height:1px;background:linear-gradient(90deg,transparent,rgba(88,86,214,.2),transparent);margin:12px 0;}',
  /* 스텝 카드 */
  '.ss{padding:6px 10px;margin-bottom:4px;background:rgba(88,86,214,.04);border-radius:8px;font-size:11px;color:'+C.sub+';border-left:2px solid '+C.accentBorder+';}',
  /* 로딩 */
  '.sd{display:flex;align-items:center;gap:5px;}',
  '.sd i{display:inline-block;width:7px;height:7px;border-radius:50%;background:linear-gradient(135deg,'+C.fab1+','+C.fab2+');animation:sdB .65s ease infinite;}',
  '.sd i:nth-child(2){animation-delay:.15s;}.sd i:nth-child(3){animation-delay:.3s;}',
  '@keyframes sdB{0%,100%{opacity:1;transform:scale(1)}50%{opacity:.25;transform:scale(.6);}}',
  '@keyframes saRec{0%,100%{box-shadow:0 0 0 0 rgba(255,69,58,.4)}50%{box-shadow:0 0 0 8px rgba(255,69,58,0)}}',
  '#__sa_mic.recording{background:#FF453A!important;animation:saRec 1.2s ease infinite!important;}',
  '.sa table{width:100%;border-collapse:collapse;margin:8px 0;font-size:11px;border-radius:8px;overflow:hidden;border:1px solid rgba(0,0,0,.08);}',
  '.sa thead{background:rgba(88,86,214,.06);}',
  '.sa th{padding:6px 10px;text-align:left;font-weight:700;color:#1c1c1e;border-bottom:1.5px solid rgba(88,86,214,.15);font-size:10px;white-space:nowrap;}',
  '.sa td{padding:5px 10px;border-bottom:1px solid rgba(0,0,0,.04);color:#333;line-height:1.5;}',
  '.sa tr:last-child td{border-bottom:none;}',
  '.sa tr:hover td{background:rgba(88,86,214,.03);}',
  '.fin-back{border:none;background:none;font-size:22px;color:#8e8e93;cursor:pointer;padding:0;line-height:1;}',
  '.fin-tabs{display:flex;gap:0;border-bottom:1px solid rgba(0,0,0,.06);margin-bottom:8px;}',
  '.fin-tab{flex:1;border:none;background:none;padding:8px 4px;font-size:10px;font-weight:600;color:#8e8e93;cursor:pointer;border-bottom:2px solid transparent;transition:all .15s;text-align:center;}',
  '.fin-tab.active{color:#5856D6;border-bottom-color:#5856D6;background:rgba(88,86,214,.04);}',
  '.fin-widget{width:100%;border-radius:10px;overflow:hidden;margin-bottom:8px;border:1px solid rgba(0,0,0,.04);}',
  '.fin-section{margin-bottom:12px;}',
  '.fin-label{font-size:9px;color:#8e8e93;font-weight:600;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px;padding:0 2px;}',
  '.xr-item{display:flex;justify-content:space-between;align-items:center;padding:5px 0;border-bottom:1px solid rgba(0,0,0,.03);font-size:11px;}',
  '.xr-label{color:#666;}',
  '.xr-val{font-weight:700;font-family:monospace;}',
  '.xr-good{color:#16a34a;}','.xr-warn{color:#d97706;}','.xr-bad{color:#e11d48;}',
  '.xr-section{margin-bottom:12px;}',
  '.xr-stitle{font-size:10px;font-weight:700;color:#5856D6;margin-bottom:4px;padding-bottom:3px;border-bottom:1.5px solid rgba(88,86,214,.1);}',
  '.tmr-display{font-family:monospace;font-size:48px;font-weight:800;text-align:center;color:#1c1c1e;margin:20px 0 10px;}',
  '.tmr-label{text-align:center;font-size:12px;color:#8e8e93;margin-bottom:16px;}',
  '.tmr-btns{display:flex;gap:8px;justify-content:center;margin-bottom:12px;}',
  '.tmr-btn{padding:8px 20px;border:none;border-radius:10px;font-size:12px;font-weight:700;cursor:pointer;transition:all .15s;}',
  '.tmr-preset{display:flex;gap:6px;justify-content:center;flex-wrap:wrap;margin-bottom:12px;}',
  '.tmr-p{padding:4px 10px;border:1px solid rgba(0,0,0,.08);border-radius:8px;font-size:10px;cursor:pointer;background:none;color:#666;transition:all .15s;}',
  '.tmr-p:hover{border-color:#5856D6;color:#5856D6;}',
  '.wth-card{background:rgba(88,86,214,.04);border-radius:12px;padding:14px;margin-bottom:8px;border:1px solid rgba(88,86,214,.06);}',
  '.wth-temp{font-size:36px;font-weight:800;color:#1c1c1e;}',
  '.wth-desc{font-size:12px;color:#666;margin-top:2px;}',
  '.wth-detail{display:flex;gap:12px;margin-top:8px;font-size:10px;color:#8e8e93;}',
  '.wth-fc{display:flex;gap:6px;overflow-x:auto;padding:4px 0;}',
  '.wth-fday{text-align:center;min-width:60px;padding:6px;border-radius:8px;background:rgba(0,0,0,.02);font-size:10px;}',
  '.ait-card{background:rgba(88,86,214,.03);border:1px solid rgba(88,86,214,.06);border-radius:12px;padding:14px;margin-bottom:10px;cursor:pointer;transition:all .15s;}',
  '.ait-card:hover{border-color:#5856D6;box-shadow:0 2px 12px rgba(88,86,214,.1);}',
  '.ait-icon{font-size:28px;margin-bottom:6px;}',
  '.ait-name{font-size:12px;font-weight:700;color:#1c1c1e;}',
  '.ait-desc{font-size:10px;color:#8e8e93;margin-top:2px;line-height:1.4;}',
  '.img-gen-input{width:100%;min-height:80px;padding:10px;border:1px solid rgba(0,0,0,.08);border-radius:10px;font-size:12px;resize:vertical;outline:none;font-family:inherit;line-height:1.5;}',
  '.img-gen-input:focus{border-color:#5856D6;box-shadow:0 0 0 3px rgba(88,86,214,.08);}',
  '.img-gen-btn{width:100%;padding:12px;background:linear-gradient(135deg,#5856D6,#4f46e5);border:none;border-radius:12px;color:#fff;font-size:13px;font-weight:700;cursor:pointer;transition:all .15s;}',
  '.img-gen-btn:hover{box-shadow:0 4px 16px rgba(88,86,214,.3);}',
  '.img-gen-btn:disabled{opacity:.5;cursor:not-allowed;}',
  '.img-result{width:100%;border-radius:10px;margin-top:8px;box-shadow:0 2px 12px rgba(0,0,0,.08);}',
  '.img-dl-btn{display:inline-flex;align-items:center;gap:4px;padding:6px 14px;background:#5856D6;color:#fff;border:none;border-radius:8px;font-size:11px;font-weight:600;cursor:pointer;margin-top:6px;}',
  '.sa-actions{display:flex;gap:4px;justify-content:flex-end;margin-top:8px;padding-top:6px;border-top:1px solid rgba(0,0,0,.04);}',
  '.sa-actions button{border:none;border-radius:8px;background:rgba(118,118,128,.08);color:#8e8e93;font-size:12px;padding:4px 10px;cursor:pointer;transition:all .15s;display:flex;align-items:center;gap:4px;}',
  '.sa-actions button:hover{background:rgba(88,86,214,.1);color:#5856D6;}',
  '.sa-actions button.active{background:rgba(88,86,214,.15);color:#5856D6;}'
].join('\n');
document.head.appendChild(sty);

/* ── helpers ── */
function h(t,c,x){var e=document.createElement(t);if(t==='button')e.type='button';if(c)e.style.cssText=c;if(x)e.textContent=x;return e;}
function esc(s){return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');}

/* ── FAB ── */
var fabSvg='<svg width="26" height="26" viewBox="0 0 26 26" fill="none"><path d="M4 2L4 18L8 14L10.5 20.5L13 19.5L10.5 13L15.5 13Z" fill="white" stroke="rgba(255,255,255,.3)" stroke-width=".5" stroke-linejoin="round"/><text x="15.5" y="9" font-size="7.5" font-weight="800" fill="rgba(255,255,255,.95)">AI</text><circle cx="16.5" cy="14.5" r="1.3" fill="rgba(255,255,255,.9)"/><circle cx="19.8" cy="14.5" r="1.3" fill="rgba(255,255,255,.6)"/><circle cx="23.1" cy="14.5" r="1.3" fill="rgba(255,255,255,.35)"/></svg>';
var fabChev='<svg width="22" height="22" viewBox="0 0 20 20" fill="none"><path d="M5 7L10 12L15 7" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>';
var F=document.createElement('button');F.type='button';F.id='__sa_F';
F.setAttribute('data-page-agent-ignore','true');F.setAttribute('data-browser-use-ignore','true');
F.style.cssText='position:fixed!important;z-index:2147483647!important;width:56px!important;height:56px!important;border-radius:50%!important;background:linear-gradient(145deg,'+C.fab1+','+C.fab2+')!important;box-shadow:0 6px 24px '+C.glow+',0 2px 8px rgba(0,0,0,.12)!important;cursor:pointer!important;border:none!important;padding:0!important;outline:none!important;display:flex!important;align-items:center!important;justify-content:center!important;user-select:none!important;transition:transform .2s cubic-bezier(.34,1.56,.64,1),box-shadow .2s!important;';
F.innerHTML=fabSvg;
document.body.appendChild(F);

var LF='__sa_fp',LP='__sa_pp',LO='__sa_o3';
var fp=null;try{fp=JSON.parse(localStorage.getItem(LF));}catch(e){}
function setFP(x,y){x=Math.max(4,Math.min(x,innerWidth-60));y=Math.max(4,Math.min(y,innerHeight-60));F.style.left=x+'px';F.style.top=y+'px';F.style.right='auto';F.style.bottom='auto';return{x:x,y:y};}
var fpos=fp?setFP(fp.x,fp.y):setFP(innerWidth-80,innerHeight-80);

/* ── PANEL ── */
var P=document.createElement('div');P.id='__sa_P';P.className='sa-hidden';
P.setAttribute('data-page-agent-ignore','true');P.setAttribute('data-browser-use-ignore','true');
/* ★ 패널 내 모든 키 이벤트 페이지 전파 차단 */
['keydown','keyup','keypress','input','compositionstart','compositionend','compositionupdate'].forEach(function(evt){
  P.addEventListener(evt,function(e){e.stopPropagation();},true);
});
P.style.cssText='position:fixed!important;z-index:2147483646!important;width:370px!important;max-width:calc(100vw - 20px)!important;border-radius:24px!important;background:'+C.bgPanel+'!important;backdrop-filter:blur(60px) saturate(190%)!important;-webkit-backdrop-filter:blur(60px) saturate(190%)!important;box-shadow:0 24px 80px rgba(0,0,0,.12),0 4px 16px rgba(0,0,0,.06),inset 0 .5px 0 rgba(255,255,255,.95),0 0 0 .5px rgba(0,0,0,.04)!important;display:flex!important;flex-direction:column!important;overflow:hidden!important;max-height:80vh!important;';
document.body.appendChild(P);

var pp=null;try{pp=JSON.parse(localStorage.getItem(LP));}catch(e){}
var ppos=pp||null;
function setPP(x,y){x=Math.max(4,Math.min(x,innerWidth-380));y=Math.max(4,Math.min(y,innerHeight-200));P.style.left=x+'px';P.style.top=y+'px';P.style.right='auto';P.style.bottom='auto';return{x:x,y:y};}
function autoPP(){var fx=parseInt(F.style.left)||fpos.x,fy=parseInt(F.style.top)||fpos.y;var px=fx+66+370>innerWidth?fx-378:fx+66;px=Math.max(8,px);var py=Math.max(8,Math.min(fy-40,innerHeight-500));return setPP(px,py);}

/* ── 열기/닫기 ── */
var isOpen=false;try{isOpen=localStorage.getItem(LO)==='1';}catch(e){}
var _viewMode='main'; // 'main' | 'settings'
function openP(){isOpen=true;try{localStorage.setItem(LO,'1');}catch(e){}F.innerHTML=fabChev;if(!ppos)ppos=autoPP();else setPP(ppos.x,ppos.y);P.className='sa-visible';if(_viewMode==='settings')renderSettings();else renderMain();}
function closeP(){isOpen=false;try{localStorage.setItem(LO,'0');}catch(e){}F.innerHTML=fabSvg;P.className='sa-hidden';}
window.__sa_panel_open=openP;

/* ── FAB 드래그 ── */
var fd=false,fm=false,fsx,fsy,fox,foy;
F.addEventListener('mousedown',function(e){if(e.button)return;fd=true;fm=false;fsx=e.clientX;fsy=e.clientY;fox=parseInt(F.style.left)||fpos.x;foy=parseInt(F.style.top)||fpos.y;e.stopPropagation();e.preventDefault();},true);
document.addEventListener('mousemove',function(e){if(!fd)return;var dx=e.clientX-fsx,dy=e.clientY-fsy;if(Math.abs(dx)>4||Math.abs(dy)>4){fm=true;fpos=setFP(fox+dx,foy+dy);}});
document.addEventListener('mouseup',function(){if(!fd)return;fd=false;if(!fm){isOpen?closeP():openP();}else try{localStorage.setItem(LF,JSON.stringify(fpos));}catch(e){}fm=false;});
F.addEventListener('touchstart',function(e){var t=e.touches[0];fd=true;fm=false;fsx=t.clientX;fsy=t.clientY;fox=parseInt(F.style.left)||fpos.x;foy=parseInt(F.style.top)||fpos.y;},{passive:true});
document.addEventListener('touchmove',function(e){if(!fd)return;var t=e.touches[0],dx=t.clientX-fsx,dy=t.clientY-fsy;if(Math.abs(dx)>4||Math.abs(dy)>4){fm=true;fpos=setFP(fox+dx,foy+dy);e.preventDefault();}},{passive:false});
document.addEventListener('touchend',function(){if(!fd)return;fd=false;if(!fm){isOpen?closeP():openP();}else try{localStorage.setItem(LF,JSON.stringify(fpos));}catch(e){}fm=false;});

/* ── 패널 드래그 ── */
var pd=false,psx,psy,pox,poy;
function initPDrag(hdr){
  hdr.style.cursor='grab';
  hdr.addEventListener('mousedown',function(e){if(e.target.tagName==='BUTTON')return;pd=true;psx=e.clientX;psy=e.clientY;pox=parseInt(P.style.left)||0;poy=parseInt(P.style.top)||0;hdr.style.cursor='grabbing';e.preventDefault();e.stopPropagation();});
  document.addEventListener('mousemove',function(e){if(!pd)return;ppos=setPP(pox+(e.clientX-psx),poy+(e.clientY-psy));});
  document.addEventListener('mouseup',function(){if(!pd)return;pd=false;hdr.style.cursor='grab';try{localStorage.setItem(LP,JSON.stringify(ppos));}catch(e){}});
  hdr.addEventListener('touchstart',function(e){if(e.target.tagName==='BUTTON')return;var t=e.touches[0];pd=true;psx=t.clientX;psy=t.clientY;pox=parseInt(P.style.left)||0;poy=parseInt(P.style.top)||0;},{passive:true});
  document.addEventListener('touchmove',function(e){if(!pd)return;var t=e.touches[0];ppos=setPP(pox+(t.clientX-psx),poy+(t.clientY-psy));e.preventDefault();},{passive:false});
  document.addEventListener('touchend',function(){if(!pd)return;pd=false;try{localStorage.setItem(LP,JSON.stringify(ppos));}catch(e){}});
}

/* ── 대화 히스토리 저장 (세션 복원 우선) ── */
var _chatHTML = window.__SA_PREV_CHAT || (_restored ? _restored.chat : '') || '';
var _restoredCmd = _restored ? _restored.cmd : '';
if(_restoredCmd && !window.__SA_LAST_CMD) window.__SA_LAST_CMD = _restoredCmd;

/* 서버 세션도 비동기 시도 (window.name 없을 때 폴백) */
if(!_chatHTML){
  _sesLoadServer(function(d){
    if(!d || !d.chat) return;
    _chatHTML = d.chat;
    if(d.cmd && !window.__SA_LAST_CMD) window.__SA_LAST_CMD = d.cmd;
    /* 이미 렌더된 히스토리 영역 업데이트 */
    var hist = document.getElementById('__sa_H');
    if(hist && hist.innerHTML.indexOf('text-align:center') !== -1){
      hist.innerHTML = _chatHTML;
      hist.scrollTop = hist.scrollHeight;
    }
  });
}

/* ── 메인 렌더 ── */
function renderMain(){
  _viewMode='main';P.innerHTML='';
  /* 헤더 */
  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;user-select:none;');
  var lft=h('div','display:flex;align-items:center;gap:8px;');
  var ico=h('div','width:24px;height:24px;border-radius:8px;background:linear-gradient(135deg,'+C.fab1+','+C.fab2+');display:flex;align-items:center;justify-content:center;box-shadow:0 2px 8px '+C.glow+';');
  ico.innerHTML='<svg width="12" height="12" viewBox="0 0 26 26" fill="none"><path d="M4 2L4 18L8 14L10.5 20.5L13 19.5L10.5 13L15.5 13Z" fill="white"/></svg>';
  lft.appendChild(ico);
  lft.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','SiteAgent'));
  lft.appendChild(h('span','font-size:10px;color:'+C.sub+';max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;',location.hostname.replace(/^www\./,'')));
  var rgt=h('div','display:flex;align-items:center;gap:6px;');
  var dot=h('div','width:8px;height:8px;border-radius:50%;background:'+C.green+';box-shadow:0 0 6px rgba(48,209,88,.5);');dot.id='__sa_dot';rgt.appendChild(dot);
  /* 🗑 클리어 */
  var clr=h('button','width:28px;height:28px;border:none;border-radius:8px;background:rgba(0,0,0,.04);color:'+C.sub+';font-size:14px;cursor:pointer;padding:0;transition:background .15s;','🗑');
  clr.title='대화 초기화';clr.onmouseenter=function(){this.style.background='rgba(0,0,0,.1)';};clr.onmouseleave=function(){this.style.background='rgba(0,0,0,.04)';};
  clr.onclick=function(){_chatHTML='';var hh=document.getElementById('__sa_H');if(hh)hh.innerHTML='<div style="padding:32px 16px;text-align:center;color:'+C.sub+';font-size:12px;line-height:1.7;">명령을 입력하거나<br>위 버튼을 눌러 시작하세요</div>';};
  rgt.appendChild(clr);
  /* ⚙ 설정 */
  var gear=h('button','width:28px;height:28px;border:none;border-radius:8px;background:rgba(0,0,0,.04);color:'+C.sub+';font-size:14px;cursor:pointer;padding:0;transition:background .15s;','⚙');
  gear.title='설정';gear.onmouseenter=function(){this.style.background='rgba(0,0,0,.1)';};gear.onmouseleave=function(){this.style.background='rgba(0,0,0,.04)';};
  gear.onclick=function(){renderSettings();};rgt.appendChild(gear);
  /* ✕ 닫기 */
  var xb=h('button','width:28px;height:28px;border:none;border-radius:50%;background:rgba(255,69,58,.06);color:'+C.red+';font-size:18px;cursor:pointer;padding:0;line-height:1;','×');
  xb.onclick=closeP;rgt.appendChild(xb);
  hdr.appendChild(lft);hdr.appendChild(rgt);P.appendChild(hdr);
  initPDrag(hdr);

  /* 페이지 컨텍스트 */
  var title=document.title||'';
  if(title){var ctx=h('div','padding:7px 16px;background:linear-gradient(90deg,rgba(88,86,214,.04),rgba(0,122,255,.02));border-bottom:1px solid rgba(0,0,0,.03);font-size:11px;color:#636366;flex-shrink:0;');ctx.innerHTML='<span style="font-weight:700;color:'+C.accent+';margin-right:5px;font-size:10px;text-transform:uppercase;letter-spacing:.5px;">Page</span>'+esc(title.substring(0,55));P.appendChild(ctx);}

  /* 빠른 명령 */
  var qc=h('div','display:flex;gap:6px;padding:9px 16px;border-bottom:1px solid rgba(0,0,0,.03);flex-wrap:wrap;flex-shrink:0;');
  [{l:'📝 요약',c:'__QUICK_SUMMARY__'},{l:'📸 분석',c:'__QUICK_ANALYZE__'},{l:'🌐 번역',c:'__QUICK_TRANSLATE__'},{l:'🔍 검색',c:'__SEARCH__'},{l:'🧠 딥분석',c:'__INSIGHT__'},{l:'💡 아이디어',c:'__EMERGENCE__'},{l:'📊 금융',c:'__FINANCE__'},{l:'📷 캡처',c:'__CAPTURE__'},{l:'🎬 녹화',c:'__RECORD__'},{l:'📌 클립',c:'__CLIPS__'},{l:'🔮 사주',c:'__SAJU__'},{l:'✍️ 글쓰기',c:'__WRITER__'},{l:'🛒 쇼핑',c:'__SHOPPING__'},{l:'👤 페이스',c:'__FACE__'},{l:'💬 채팅',c:'__CHAT__'},{l:'🤖 AI도구',c:'__AITOOLS__'},{l:'🔐 시크릿AI',c:'__SECRET__'}].forEach(function(cm){
    var b=h('button','border:none;border-radius:20px;background:'+C.accentLight+';color:'+C.accent+';font-size:11px;font-weight:600;padding:5px 12px;cursor:pointer;white-space:nowrap;border:.5px solid '+C.accentBorder+';transition:all .15s;',cm.l);
    b.onmouseenter=function(){this.style.background='rgba(88,86,214,.18)';};b.onmouseleave=function(){this.style.background=C.accentLight;};
    b.onclick=function(){
      _saFeature(cm.l.replace(/[^\w가-힣]/g,''));
      if(cm.c==='__QUICK_SUMMARY__'){
        _runQuickAI('현재 페이지 핵심 내용을 3줄로 요약해줘','📝 요약');
        return;
      }
      if(cm.c==='__QUICK_ANALYZE__'){
        _runQuickAI('현재 보이는 화면 내용을 심층 분석해줘','📸 분석');
        return;
      }
      if(cm.c==='__QUICK_TRANSLATE__'){
        _runQuickAI('현재 페이지 주요 내용을 영어로 번역해줘','🌐 번역');
        return;
      }
      if(cm.c==='__SEARCH__'){
        inp.value='';inp.placeholder='🔍 검색할 내용을 입력하세요...';inp.focus();
        inp._searchMode=true;
        return;
      }
      if(cm.c==='__INSIGHT__'){
        renderDeepAnalysis();
        return;
      }
      if(cm.c==='__EMERGENCE__'){
        renderIdeaGen();
        return;
      }
      if(cm.c==='__FINANCE__'){
        renderFinance();
        return;
      }
      if(cm.c==='__AITOOLS__'){
        renderAITools();
        return;
      }
      if(cm.c==='__CAPTURE__'){
        runScreenCapture();
        return;
      }
      if(cm.c==='__RECORD__'){
        runScreenRecord();
        return;
      }
      if(cm.c==='__CLIPS__'){
        renderClips();
        return;
      }
      if(cm.c==='__SAJU__'){
        renderSaju();
        return;
      }
      if(cm.c==='__WRITER__'){
        renderWriter();
        return;
      }
      if(cm.c==='__SHOPPING__'){
        renderShopping();
        return;
      }
      if(cm.c==='__FACE__'){
        renderFace();
        return;
      }
      if(cm.c==='__CHAT__'){
        renderChat();
        return;
      }
      if(cm.c==='__SECRET__'){
        if(window.__SA_SECRET&&window.__SA_SECRET.render){window.__SA_SECRET.render();}
        else{alert('시크릿AI 메신저 모듈이 로드되지 않았습니다.');}
        return;
      }
      runTask(cm.c);
    };qc.appendChild(b);
  });
  P.appendChild(qc);

  /* 예제 템플릿 */
  var exWrap=h('div','padding:0 16px 8px;border-bottom:1px solid rgba(0,0,0,.03);flex-shrink:0;');
  var exToggle=h('button','border:none;background:none;color:'+C.sub+';font-size:11px;cursor:pointer;padding:4px 0;width:100%;text-align:left;font-weight:600;','💡 이런 것도 해보세요 ▾');
  var exList=h('div','display:none;margin-top:6px;');
  exToggle.onclick=function(){
    if(exList.style.display==='none'){exList.style.display='block';exToggle.textContent='💡 이런 것도 해보세요 ▴';}
    else{exList.style.display='none';exToggle.textContent='💡 이런 것도 해보세요 ▾';}
  };
  var EXAMPLES=[
    {site:'코레일 KTX',url:'https://www.korail.com/ticket/search/general#',cmd:'KTX, 2026년 4월 14일, 13시~17시, 서울 출발, 부산 도착, 성인 2명 검색해줘'},
    {site:'네이버지도',url:'https://map.naver.com',cmd:'강남역 타코 식당, 신분당선 4번출구 가장 가까운 식당 찾아라'},
    {site:'쿠팡',url:'https://www.coupang.com',cmd:'아이패드 프로 검색해서 가격순 정렬하고 최저가 3개 알려줘'},
    {site:'유튜브',url:'https://www.youtube.com',cmd:'노래 아파트 오피셜(ROSÉ & Bruno Mars) 비디오 재생해. 광고는 건너띄기로 제거해'},
    {site:'네이버뉴스',url:'https://news.naver.com',cmd:'오늘 IT 뉴스 탭 들어가서 AI 관련 기사 3개 제목과 요약 알려줘'},
    {site:'네이버부동산',url:'https://land.naver.com',cmd:'성남시 분당구 10억 이하 아파트 매물만 알려줘'}
  ];
  EXAMPLES.forEach(function(ex){
    var row=h('div','display:flex;align-items:center;gap:6px;padding:5px 0;border-bottom:1px solid rgba(0,0,0,.02);cursor:pointer;');
    row.innerHTML='<span style="font-size:11px;font-weight:700;color:'+C.accent+';white-space:nowrap;min-width:65px;">'+esc(ex.site)+'</span><span style="font-size:10px;color:#636366;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;">'+esc(ex.cmd)+'</span>';
    row.onmouseenter=function(){this.style.background='rgba(88,86,214,.04)';this.style.borderRadius='8px';};
    row.onmouseleave=function(){this.style.background='none';};
    row.onclick=function(){
      /* 해당 사이트가 현재 페이지면 바로 실행, 아니면 새 탭 */
      if(location.href.indexOf(new URL(ex.url).hostname)>=0){
        runTask(ex.cmd);
      }else{
        /* 클립보드에 명령 복사 + 새 탭 열기 */
        try{navigator.clipboard.writeText(ex.cmd);}catch(e){}
        window.open(ex.url,'_blank');
        var hist=document.getElementById('__sa_H');
        if(hist){
          var notice=document.createElement('div');notice.className='ss';
          notice.innerHTML='📋 명령이 복사되었습니다. 새 탭에서 SiteAgent를 실행하고 붙여넣기(Ctrl+V)하세요.';
          hist.appendChild(notice);_scrollH();
        }
      }
    };
    exList.appendChild(row);
  });
  exWrap.appendChild(exToggle);exWrap.appendChild(exList);P.appendChild(exWrap);

  /* 히스토리 */
  var hist=h('div','flex:1;overflow-y:auto;padding:10px;min-height:80px;');hist.id='__sa_H';
  if(_chatHTML){hist.innerHTML=_chatHTML;}
  else{hist.innerHTML='<div style="padding:32px 16px;text-align:center;color:'+C.sub+';font-size:12px;line-height:1.7;">명령을 입력하거나<br>위 버튼을 눌러 시작하세요</div>';}
  P.appendChild(hist);

  /* 입력 */
  var iw=h('div','display:flex;align-items:center;gap:8px;padding:10px 14px 14px;border-top:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.6);backdrop-filter:blur(20px);-webkit-backdrop-filter:blur(20px);border-radius:0 0 24px 24px;');
  var inp=document.createElement('input');inp.type='text';inp.id='__sa_I';inp.placeholder='무엇이든 물어보세요...';
  inp.style.cssText='flex:1;background:rgba(118,118,128,.08);border:1px solid rgba(0,0,0,.04);border-radius:14px;padding:0 14px;height:38px;font-size:13px;color:'+C.text+';outline:none;transition:all .2s;';
  inp.onfocus=function(){this.style.borderColor='rgba(88,86,214,.3)';this.style.boxShadow='0 0 0 3px rgba(88,86,214,.08)';};
  inp.onblur=function(){this.style.borderColor='rgba(0,0,0,.04)';this.style.boxShadow='none';};
  /* ★ 모든 키 이벤트 버블링 차단 (네이버 등 사이트 검색창 가로채기 방지) */
  ['keydown','keyup','keypress','input','compositionstart','compositionend','compositionupdate'].forEach(function(evt){
    inp.addEventListener(evt,function(e){e.stopPropagation();e.stopImmediatePropagation();},true);
  });
  inp.addEventListener('keydown',function(e){if(e.key!=='Enter'||e.isComposing)return;e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();var v=inp.value.trim();if(!v)return;inp.value='';if(inp._searchMode){inp._searchMode=false;inp.placeholder='무엇이든 물어보세요...';runSearch(v);}else{runTask(v);}});
  var sBtn=h('button','width:36px;height:36px;border:none;border-radius:50%;background:linear-gradient(135deg,'+C.fab1+','+C.fab2+');color:#fff;font-size:16px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:transform .15s;box-shadow:0 2px 8px '+C.glow+';','↑');
  sBtn.id='__sa_send';
  var _isRunning=false;
  window._setSendMode=function(running){
    _isRunning=running;
    if(running){sBtn.textContent='⏹';sBtn.style.background='linear-gradient(135deg,#FF453A,#FF6961)';sBtn.title='중지';}
    else{sBtn.textContent='↑';sBtn.style.background='linear-gradient(135deg,'+C.fab1+','+C.fab2+')';sBtn.title='보내기';}
  }
  sBtn.onclick=function(){
    if(_isRunning){/* 중지 */try{SA.stop();}catch(e){}var aC2=document.querySelector('#__sa_H .sa:last-child');if(aC2&&aC2.querySelector('.sd'))aC2.innerHTML='<p style="color:'+C.orange+';font-weight:600;">⏹ 사용자에 의해 중지됨</p>';_setSendMode(false);var dot2=document.getElementById('__sa_dot');if(dot2){dot2.style.background=C.orange;dot2.style.boxShadow='none';}return;}
    var v=inp.value.trim();if(!v)return;inp.value='';
    if(inp._searchMode){inp._searchMode=false;inp.placeholder='무엇이든 물어보세요...';runSearch(v);}
    else{runTask(v);}
  };
  /* 🎤 마이크 버튼 */
  var micBtn=h('button','width:36px;height:36px;border:none;border-radius:50%;background:rgba(118,118,128,.08);color:#8e8e93;font-size:16px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .2s;flex-shrink:0;','🎤');
  micBtn.id='__sa_mic';micBtn.title='음성 입력';
  var _micActive=false,_recognition=null;

  micBtn.onclick=function(){
    if(_micActive){_stopMic();return;}
    if(!('webkitSpeechRecognition' in window)&&!('SpeechRecognition' in window)){
      alert('이 브라우저는 음성 인식을 지원하지 않습니다. 크롬 브라우저를 사용해주세요.');return;
    }
    var SR=window.SpeechRecognition||window.webkitSpeechRecognition;
    _recognition=new SR();
    _recognition.lang='ko-KR';
    _recognition.continuous=false;
    _recognition.interimResults=true;
    _recognition.maxAlternatives=1;

    _recognition.onstart=function(){
      _micActive=true;
      micBtn.classList.add('recording');
      micBtn.textContent='⏺';
      inp.placeholder='🎤 말씀하세요...';
      inp.value='';
    };
    _recognition.onresult=function(ev){
      var transcript='';
      for(var i=ev.resultIndex;i<ev.results.length;i++){
        transcript+=ev.results[i][0].transcript;
      }
      inp.value=transcript;
      /* 최종 결과면 자동 실행 */
      if(ev.results[ev.results.length-1].isFinal){
        _stopMic();
        var v=inp.value.trim();
        if(v){inp.value='';runTask(v);}
      }
    };
    _recognition.onerror=function(ev){
      console.log('[SA-MIC] error:',ev.error);
      _stopMic();
      if(ev.error==='not-allowed')inp.placeholder='마이크 권한을 허용해주세요';
    };
    _recognition.onend=function(){_stopMic();};
    _recognition.start();
  };

  function _stopMic(){
    _micActive=false;
    if(_recognition){try{_recognition.stop();}catch(e){}_recognition=null;}
    micBtn.classList.remove('recording');
    micBtn.textContent='🎤';
    inp.placeholder='무엇이든 물어보세요...';
  }

  iw.appendChild(inp);iw.appendChild(micBtn);iw.appendChild(sBtn);P.appendChild(iw);
}

/* ── 🧠 딥분석 (심층 다단계 조사) ── */
var _userEmail=window.__SA_USER_EMAIL||'';
(function(){
  if(_userEmail) return;
  var _emailCheck=setInterval(function(){
    if(window.__SA_USER_EMAIL){
      _userEmail=window.__SA_USER_EMAIL;
      clearInterval(_emailCheck);
      console.log('[SA] email detected:',_userEmail);
      _logActivity('visit');
    }
  },1000);
  setTimeout(function(){clearInterval(_emailCheck);},30000);
})();
function _logActivity(action, extra){
  if(!_userEmail) return;
  var body=Object.assign({email:_userEmail,action:action,url:location.href,title:document.title}, extra||{});
  try{fetch((window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space')+'/api/user/log',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body),mode:'cors'}).catch(function(){});}catch(e){}
}
function _saAiDone(feature, startMs, ok, extra){
  var ms = Date.now() - startMs;
  _saAna(ok ? 'ai_response' : 'ai_error', Object.assign({
    feature:feature, response_ms:ms, success:ok,
    error_msg:(extra && extra.error_msg)||'',
    model:(typeof settings!=='undefined' && settings.model)||'gpt-oss-120b'
  }, extra||{}));
}
function _saTimedFetch(url, opts, feature, extra){
  var t0=Date.now();
  return fetch(url, opts).then(function(r){
    if(!r.ok) return r.text().then(function(t){throw new Error('HTTP '+r.status+': '+t.substring(0,100));});
    return r.text().then(function(t){try{return JSON.parse(t);}catch(e){throw new Error('파싱 실패');}});
  }).then(function(d){
    _saAiDone(feature, t0, !d.error, extra||{});
    return d;
  }).catch(function(e){
    _saAiDone(feature, t0, false, Object.assign({error_msg:e.message||''}, extra||{}));
    throw e;
  });
}
function _saFeature(name, extra){
  _saAna('feature_use', Object.assign({feature:name}, extra||{}));
}
if(_userEmail) _logActivity('visit');
function _runQuickAI(task, label){
  var hist=document.getElementById('__sa_H');if(!hist)return;
  if(hist.querySelector('div[style*="text-align:center"]'))hist.innerHTML='';
  var uC=document.createElement('div');uC.className='su';
  uC.innerHTML='<span style="opacity:.7;margin-right:4px;">'+label.charAt(0)+'</span> '+esc(task);
  hist.appendChild(uC);
  var aC=document.createElement('div');aC.className='sa';
  aC.innerHTML='<div style="display:flex;align-items:center;gap:6px;"><div class="sd"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></div><span style="font-size:11px;color:#5856D6;font-weight:600;">'+esc(label)+' 처리 중...</span></div>';
  hist.appendChild(aC);_scrollH();
  var pageText='';
  try{
    pageText=_saExtractPageText();
  }catch(e){pageText=document.title||location.href;}
  var fullPrompt='['+task+']\n\n[현재 페이지 제목] '+(document.title||'없음')+'\n[URL] '+location.href+'\n\n[페이지 내용 ('+pageText.length+'자)]\n'+pageText;
  var BASE=window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space';
  var _t0=Date.now();
  fetch(BASE+'/api/marl',{
    method:'POST',headers:{'Content-Type':'application/json'},
    body:JSON.stringify({prompt:fullPrompt,mode:'insight',engine:'invent',sa_email:window.__SA_USER_EMAIL||'',sa_url:location.href||'',system:'반드시 한국어로 답변하라. 표(table/마크다운 표)는 어떤 경우에도 절대 사용 금지. 개조식 서술형으로 작성. 핵심은 **볼드** 강조. 섹션은 ## 헤딩.'}),
    mode:'cors'
  }).then(function(r){
    if(!r.ok)return r.text().then(function(t){throw new Error('HTTP '+r.status);});
    return r.json();
  }).then(function(d){
    _saAiDone('quick_'+label,_t0,!d.error);
    if(d.error){aC.innerHTML='<p style="color:#e11d48;">❌ '+esc(d.error)+'</p>';_scrollH();_chatHTML=hist.innerHTML;return;}
    var text=d.answer||'';
    if(!text||text.length<5){aC.innerHTML='<p style="color:#d97706;">⚠️ 결과가 비어있습니다.</p>';_scrollH();_chatHTML=hist.innerHTML;return;}
    _logTask('MARL_'+label,fullPrompt,text);
    var el=d.elapsed||0;
    aC.innerHTML='<div style="margin-bottom:6px;display:flex;align-items:center;gap:6px;flex-wrap:wrap;">'
      +'<span style="font-size:10px;font-weight:700;color:#5856D6;">'+esc(label)+' 완료</span>'
      +'<span style="font-size:9px;color:#8e8e93;">'+el+'초</span></div>'
      +toHTML(text);
    var _pt=text.replace(/<[^>]*>/g,'').trim();
    var actDiv=document.createElement('div');actDiv.className='sa-actions';
    var tBtn=document.createElement('button');tBtn.innerHTML='🔊 읽기';var _tp=false;
    tBtn.onclick=function(){if(_tp){speechSynthesis.cancel();_tp=false;tBtn.innerHTML='🔊 읽기';return;}var u=new SpeechSynthesisUtterance(_pt);u.lang='ko-KR';u.rate=1.1;u.onend=function(){_tp=false;tBtn.innerHTML='🔊 읽기';};speechSynthesis.speak(u);_tp=true;tBtn.innerHTML='⏹ 멈춤';};
    actDiv.appendChild(tBtn);
    var cBtn=document.createElement('button');cBtn.innerHTML='📋 복사';
    cBtn.onclick=function(){navigator.clipboard.writeText(_pt).then(function(){cBtn.innerHTML='✅ 복사됨';setTimeout(function(){cBtn.innerHTML='📋 복사';},1500);});};
    actDiv.appendChild(cBtn);
    aC.appendChild(actDiv);
    _scrollH();_chatHTML=hist.innerHTML;
  }).catch(function(e){
    _saAiDone('quick_'+label,_t0,false,{error_msg:e.message});
    aC.innerHTML='<p style="color:#e11d48;">❌ '+esc(e.message)+'</p>';
    _scrollH();_chatHTML=hist.innerHTML;
  });
}
function renderDeepAnalysis(){
  _viewMode='deep';P.innerHTML='';

  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','🧠 딥분석'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','×');
  back.onclick=function(){_viewMode='main';renderMain();};
  hdr.appendChild(back);P.appendChild(hdr);

  var wrap=h('div','padding:12px;overflow-y:auto;flex:1;');

  wrap.innerHTML='<div style="padding:8px 10px;background:rgba(88,86,214,.04);border-radius:8px;margin-bottom:10px;font-size:10px;color:#555;line-height:1.6;border:1px solid rgba(88,86,214,.06);">'
    +'🧠 <b>MARL 5단계 파이프라인</b> + <b>웹 검색 강화</b><br>'
    +'가설→해결→감사→검증→정제 · 할루시네이션 70%↓ · 다단계 심층 조사</div>'
    +'<label style="font-size:10px;color:#8e8e93;font-weight:600;display:block;margin-bottom:4px;">분석 주제를 입력하세요</label>'
    +'<textarea id="__sa_deep_q" class="img-gen-input" style="min-height:60px;" placeholder="분석하고 싶은 주제나 질문을 입력하세요..."></textarea>'
    +'<div style="margin:8px 0 6px;font-size:9px;color:#8e8e93;font-weight:600;">💡 예제 (클릭하면 입력됩니다)</div>'
    +'<div id="__sa_deep_ex" style="display:flex;flex-wrap:wrap;gap:4px;margin-bottom:10px;"></div>'
    +'<button id="__sa_deep_go" class="img-gen-btn">🧠 딥분석 시작 (10~20초)</button>'
    +'<div id="__sa_deep_result" style="margin-top:10px;"></div>';

  P.appendChild(wrap);

  /* 예제 */
  var examples=[
    '2026년 글로벌 AI 반도체 시장 전망과 핵심 플레이어 분석',
    '한국 스타트업의 실리콘밸리 진출 전략과 성공/실패 요인',
    '전고체 배터리 상용화 현황과 투자 관점 분석',
    'MCP(Model Context Protocol)의 기술적 의미와 산업 영향',
    '소형 언어 모델(SLM)이 엔터프라이즈 시장에서 갖는 경쟁력'
  ];
  var exWrap=document.getElementById('__sa_deep_ex');
  examples.forEach(function(ex){
    var btn=document.createElement('button');
    btn.textContent=ex.length>30?ex.substring(0,28)+'…':ex;
    btn.title=ex;
    btn.style.cssText='padding:3px 8px;border:1px solid rgba(0,0,0,.06);border-radius:6px;font-size:9px;cursor:pointer;background:rgba(88,86,214,.03);color:#555;text-align:left;';
    btn.onclick=function(){document.getElementById('__sa_deep_q').value=ex;};
    exWrap.appendChild(btn);
  });

  /* 실행 */
  document.getElementById('__sa_deep_go').onclick=function(){
    var q=document.getElementById('__sa_deep_q').value.trim();
    if(!q){alert('분석 주제를 입력하세요');return;}

    /* 메인 뷰로 전환 + 히스토리에 추가 */
    _viewMode='main';renderMain();
    var hist=document.getElementById('__sa_H');if(!hist)return;
    if(hist.querySelector('div[style*="text-align:center"]'))hist.innerHTML='';

    /* 사용자 질문 카드 */
    var uC=document.createElement('div');uC.className='su';
    uC.innerHTML='<span style="opacity:.7;margin-right:4px;">🧠</span> '+esc(q);
    hist.appendChild(uC);

    /* 로딩 카드 */
    var aC=document.createElement('div');aC.className='sa';
    aC.innerHTML='<div style="display:flex;align-items:center;gap:6px;"><div class="sd"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></div><span style="font-size:11px;color:#5856D6;font-weight:600;">🧠 딥분석 처리 중... (10~20초)</span></div>';
    hist.appendChild(aC);_scrollH();

    
    var fullPrompt='[심층 분석 요청]\n'+q+'\n\n[지시] 반드시 웹 검색을 활용하여 최신 정보를 포함하라. 다각도로 분석하고 근거를 제시하라. 핵심 인사이트를 도출하라.';
    var BASE=window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space';
    var _t0_ins=Date.now();
    fetch(BASE+'/api/marl',{
      method:'POST',headers:{'Content-Type':'application/json'},
      body:JSON.stringify({prompt:fullPrompt, mode:'insight', engine:'invent', sa_email:window.__SA_USER_EMAIL||'', sa_url:location.href||'', system:'반드시 한국어로 답변하라. 표(table/마크다운 표)는 어떤 경우에도 절대 사용 금지. 개조식 서술형으로 작성. 핵심은 **볼드** 강조. 섹션은 ## 헤딩. 최신 정보 반영. 근거와 출처 명시.'}),
      mode:'cors'
    }).then(function(r){
      if(!r.ok)return r.text().then(function(t){throw new Error('HTTP '+r.status+': '+t.substring(0,100));});
      return r.text().then(function(t){try{return JSON.parse(t);}catch(e){throw new Error('파싱 실패');}});
    }).then(function(d){
      _saAiDone('deep_analysis',_t0_ins,!d.error,{mode:'insight',engine:'invent'});
      if(d.error){aC.innerHTML='<p style="color:#e11d48;">❌ '+esc(d.error)+'</p>';_scrollH();_chatHTML=hist.innerHTML;return;}
      var text=d.answer||'';
      if(!text||text.length<5){aC.innerHTML='<p style="color:#d97706;">⚠️ 결과가 비어있습니다.</p>';_scrollH();_chatHTML=hist.innerHTML;return;}
      _logTask('딥분석',fullPrompt,text);
      var el=d.elapsed||0;
      aC.innerHTML='<div style="margin-bottom:6px;display:flex;align-items:center;gap:6px;flex-wrap:wrap;">'
        +'<span style="font-size:10px;font-weight:700;color:#5856D6;">🧠 딥분석 완료</span>'
        +'<span style="font-size:9px;color:#8e8e93;">'+el+'초 · MARL 5단계</span></div>'
        +toHTML(text);
      /* 읽기+복사 */
      var _pt=text.replace(/<[^>]*>/g,'').trim();
      var actDiv=document.createElement('div');actDiv.className='sa-actions';
      var tBtn=document.createElement('button');tBtn.innerHTML='🔊 읽기';var _tp=false;
      tBtn.onclick=function(){if(_tp){speechSynthesis.cancel();_tp=false;tBtn.innerHTML='🔊 읽기';return;}var u=new SpeechSynthesisUtterance(_pt);u.lang='ko-KR';u.rate=1.1;u.onend=function(){_tp=false;tBtn.innerHTML='🔊 읽기';};speechSynthesis.speak(u);_tp=true;tBtn.innerHTML='⏹ 멈춤';};
      actDiv.appendChild(tBtn);
      var cBtn=document.createElement('button');cBtn.innerHTML='📋 복사';
      cBtn.onclick=function(){navigator.clipboard.writeText(_pt).then(function(){cBtn.innerHTML='✅ 복사됨';setTimeout(function(){cBtn.innerHTML='📋 복사';},1500);});};
      actDiv.appendChild(cBtn);
      aC.appendChild(actDiv);
      _scrollH();_chatHTML=hist.innerHTML;
    }).catch(function(e){
      aC.innerHTML='<p style="color:#e11d48;">❌ '+esc(e.message)+'</p>';
      _scrollH();_chatHTML=hist.innerHTML;
    });
  };

  /* 키보드 차단 */
  var ta=document.getElementById('__sa_deep_q');
  if(ta){ta.addEventListener('keydown',function(e){e.stopPropagation();e.stopImmediatePropagation();},{capture:true});
    ta.addEventListener('keypress',function(e){e.stopPropagation();e.stopImmediatePropagation();},{capture:true});}
}

/* ── 💡 아이디어 (9개 전문 엔진) ── */
function renderIdeaGen(){
  _viewMode='idea';P.innerHTML='';

  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','💡 아이디어'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','×');
  back.onclick=function(){_viewMode='main';renderMain();};
  hdr.appendChild(back);P.appendChild(hdr);

  var wrap=h('div','padding:12px;overflow-y:auto;flex:1;');

  var engines=[
    {id:'invent',icon:'🔬',name:'발명',desc:'5,538개 기술 시드 × TRIZ'},
    {id:'create',icon:'🎨',name:'창작',desc:'트로프 반전 × 역설 × 장르 연금술'},
    {id:'document',icon:'📄',name:'문서',desc:'구조화된 보고서/제안서'},
    {id:'recipe',icon:'🍳',name:'레시피',desc:'조리법 × 텍스처 × 문화 퓨전'},
    {id:'pharma',icon:'💊',name:'제약',desc:'신약 타겟 × 메커니즘 × 전달'},
    {id:'genomics',icon:'🧬',name:'유전체',desc:'유전자 × 경로 × 표현형'},
    {id:'chemistry',icon:'⚗️',name:'화학',desc:'원소 × 구조 × 물성 × 응용'},
    {id:'ecology',icon:'🌿',name:'생태',desc:'종 × 생태계 × 보전전략'},
    {id:'law',icon:'⚖️',name:'법률',desc:'법역 × 규제 × 분쟁해결'}
  ];

  var radioHtml='<div style="display:flex;flex-wrap:wrap;gap:4px;margin-bottom:10px;">';
  engines.forEach(function(eng,i){
    radioHtml+='<label style="display:flex;align-items:center;gap:3px;padding:4px 8px;border:1px solid rgba(0,0,0,.06);border-radius:8px;font-size:10px;cursor:pointer;background:rgba(0,0,0,.01);transition:all .15s;" title="'+esc(eng.desc)+'">'
      +'<input type="radio" name="__sa_idea_eng" value="'+eng.id+'"'+(i===0?' checked':'')+' style="width:12px;height:12px;accent-color:#5856D6;" />'
      +'<span>'+eng.icon+' '+eng.name+'</span></label>';
  });
  radioHtml+='</div>';

  wrap.innerHTML='<div style="padding:8px 10px;background:rgba(13,148,136,.04);border-radius:8px;margin-bottom:10px;font-size:10px;color:#555;line-height:1.6;border:1px solid rgba(13,148,136,.06);">'
    +'💡 <b>9개 전문 분야 아이디어 엔진</b><br>'
    +'분야를 선택하고 주제를 입력하면 MARL 창발 매트릭스 기반 아이디어를 생성합니다.</div>'
    +'<div style="margin-bottom:6px;font-size:10px;color:#8e8e93;font-weight:600;">전문 분야 선택</div>'
    +radioHtml
    +'<label style="font-size:10px;color:#8e8e93;font-weight:600;display:block;margin-bottom:4px;">아이디어 주제</label>'
    +'<textarea id="__sa_idea_q" class="img-gen-input" style="min-height:60px;" placeholder="아이디어가 필요한 주제를 입력하세요..."></textarea>'
    +'<div style="margin:8px 0 6px;font-size:9px;color:#8e8e93;font-weight:600;">💡 예제 (클릭하면 입력됩니다)</div>'
    +'<div id="__sa_idea_ex" style="display:flex;flex-wrap:wrap;gap:4px;margin-bottom:10px;"></div>'
    +'<button id="__sa_idea_go" class="img-gen-btn" style="background:linear-gradient(135deg,#0d9488,#059669);">💡 아이디어 생성 (10~20초)</button>'
    +'<div id="__sa_idea_result" style="margin-top:10px;"></div>';

  P.appendChild(wrap);

  /* 예제 */
  var examples=[
    '1인 가구를 위한 AI 기반 신규 서비스 아이디어',
    '김치 유산균을 활용한 새로운 건강기능식품 레시피',
    '폐배터리 재활용 기술의 혁신적 비즈니스 모델',
    '메타버스 + 실버경제를 결합한 노인 돌봄 서비스',
    'CRISPR 유전자 편집의 농업 분야 새로운 응용',
    'AI 규제 샌드박스의 한국형 설계 방안'
  ];
  var exWrap=document.getElementById('__sa_idea_ex');
  examples.forEach(function(ex){
    var btn=document.createElement('button');
    btn.textContent=ex.length>28?ex.substring(0,26)+'…':ex;
    btn.title=ex;
    btn.style.cssText='padding:3px 8px;border:1px solid rgba(0,0,0,.06);border-radius:6px;font-size:9px;cursor:pointer;background:rgba(13,148,136,.03);color:#555;text-align:left;';
    btn.onclick=function(){document.getElementById('__sa_idea_q').value=ex;};
    exWrap.appendChild(btn);
  });

  /* 실행 */
  document.getElementById('__sa_idea_go').onclick=function(){
    var q=document.getElementById('__sa_idea_q').value.trim();
    if(!q){alert('아이디어 주제를 입력하세요');return;}
    var selEng=document.querySelector('input[name="__sa_idea_eng"]:checked');
    var eng=selEng?selEng.value:'invent';
    var engName=engines.find(function(e){return e.id===eng;});

    /* 메인 뷰로 전환 + 히스토리에 추가 */
    _viewMode='main';renderMain();
    var hist=document.getElementById('__sa_H');if(!hist)return;
    if(hist.querySelector('div[style*="text-align:center"]'))hist.innerHTML='';

    var uC=document.createElement('div');uC.className='su';
    uC.innerHTML='<span style="opacity:.7;margin-right:4px;">'+(engName?engName.icon:'💡')+'</span> '+esc(q);
    hist.appendChild(uC);

    var aC=document.createElement('div');aC.className='sa';
    aC.innerHTML='<div style="display:flex;align-items:center;gap:6px;"><div class="sd"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></div><span style="font-size:11px;color:#0d9488;font-weight:600;">💡 '+(engName?engName.name:eng)+' 아이디어 생성 중... (10~20초)</span></div>';
    hist.appendChild(aC);_scrollH();

    
    var fullPrompt='[아이디어 요청 — '+eng+' 엔진]\n'+q+'\n\n[지시] 이 분야의 전문 시드 매트릭스를 활용하여 혁신적이고 구체적인 아이디어를 제안하라. 실현 가능성과 차별화 포인트를 명시하라.';
    var BASE=window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space';
    var _t0_eme=Date.now();
    fetch(BASE+'/api/marl',{
      method:'POST',headers:{'Content-Type':'application/json'},
      body:JSON.stringify({prompt:fullPrompt, mode:'emergence', engine:eng, sa_email:window.__SA_USER_EMAIL||'', sa_url:location.href||'', system:'반드시 한국어로 답변하라. 표(table/마크다운 표)는 어떤 경우에도 절대 사용 금지. 개조식 서술형으로 작성. 핵심은 **볼드** 강조. 섹션은 ## 헤딩. 구체적이고 실행 가능한 아이디어를 제시하라.'}),
      mode:'cors'
    }).then(function(r){
      if(!r.ok)return r.text().then(function(t){throw new Error('HTTP '+r.status+': '+t.substring(0,100));});
      return r.text().then(function(t){try{return JSON.parse(t);}catch(e){throw new Error('파싱 실패');}});
    }).then(function(d){
      _saAiDone('idea_gen',_t0_eme,!d.error,{mode:'emergence',engine:eng});
      if(d.error){aC.innerHTML='<p style="color:#e11d48;">❌ '+esc(d.error)+'</p>';_scrollH();_chatHTML=hist.innerHTML;return;}
      var text=d.answer||'';
      if(!text||text.length<5){aC.innerHTML='<p style="color:#d97706;">⚠️ 결과가 비어있습니다.</p>';_scrollH();_chatHTML=hist.innerHTML;return;}
      _logTask('아이디어_'+eng,fullPrompt,text);
      var el=d.elapsed||0;
      aC.innerHTML='<div style="margin-bottom:6px;display:flex;align-items:center;gap:6px;flex-wrap:wrap;">'
        +'<span style="font-size:10px;font-weight:700;color:#0d9488;">💡 '+(engName?engName.name:eng)+' 아이디어</span>'
        +'<span style="font-size:9px;color:#8e8e93;">'+el+'초 · MARL 창발</span></div>'
        +toHTML(text);
      var _pt=text.replace(/<[^>]*>/g,'').trim();
      var actDiv=document.createElement('div');actDiv.className='sa-actions';
      var tBtn=document.createElement('button');tBtn.innerHTML='🔊 읽기';var _tp=false;
      tBtn.onclick=function(){if(_tp){speechSynthesis.cancel();_tp=false;tBtn.innerHTML='🔊 읽기';return;}var u=new SpeechSynthesisUtterance(_pt);u.lang='ko-KR';u.rate=1.1;u.onend=function(){_tp=false;tBtn.innerHTML='🔊 읽기';};speechSynthesis.speak(u);_tp=true;tBtn.innerHTML='⏹ 멈춤';};
      actDiv.appendChild(tBtn);
      var cBtn=document.createElement('button');cBtn.innerHTML='📋 복사';
      cBtn.onclick=function(){navigator.clipboard.writeText(_pt).then(function(){cBtn.innerHTML='✅ 복사됨';setTimeout(function(){cBtn.innerHTML='📋 복사';},1500);});};
      actDiv.appendChild(cBtn);
      aC.appendChild(actDiv);
      _scrollH();_chatHTML=hist.innerHTML;
    }).catch(function(e){
      aC.innerHTML='<p style="color:#e11d48;">❌ '+esc(e.message)+'</p>';
      _scrollH();_chatHTML=hist.innerHTML;
    });
  };

  /* 키보드 차단 */
  var ta=document.getElementById('__sa_idea_q');
  if(ta){ta.addEventListener('keydown',function(e){e.stopPropagation();e.stopImmediatePropagation();},{capture:true});
    ta.addEventListener('keypress',function(e){e.stopPropagation();e.stopImmediatePropagation();},{capture:true});}
}

/* ── 🔬 사이트 X-Ray ── */
function runXray(){
  var hist=document.getElementById('__sa_H');if(!hist)return;
  if(hist.querySelector('div[style*="text-align:center"]'))hist.innerHTML='';

  var uC=document.createElement('div');uC.className='su';
  uC.innerHTML='<span style="opacity:.7;margin-right:4px;">🔬</span> 사이트 X-Ray 분석';
  hist.appendChild(uC);

  var aC=document.createElement('div');aC.className='sa';
  try{
    var doc=document;var url=location.href;var title=doc.title||'없음';
    var metas=doc.querySelectorAll('meta');var imgs=doc.querySelectorAll('img');
    var scripts=doc.querySelectorAll('script[src]');var links=doc.querySelectorAll('a[href]');
    var h1s=doc.querySelectorAll('h1');var h2s=doc.querySelectorAll('h2');

    /* SEO */
    var metaDesc=(doc.querySelector('meta[name="description"]')||{}).content||'❌ 없음';
    var ogTitle=(doc.querySelector('meta[property="og:title"]')||{}).content||'❌ 없음';
    var ogImg=(doc.querySelector('meta[property="og:image"]')||{}).content||'';
    var canonical=(doc.querySelector('link[rel="canonical"]')||{}).href||'❌ 없음';
    var lang=doc.documentElement.lang||'❌ 미설정';

    /* 이미지 */
    var imgNoAlt=0;imgs.forEach(function(i){if(!i.alt)imgNoAlt++;});

    /* 링크 */
    var intLinks=0,extLinks=0;
    links.forEach(function(a){try{if(a.hostname===location.hostname)intLinks++;else extLinks++;}catch(e){extLinks++;}});

    /* 기술 스택 */
    var techs=[];
    if(window.React||doc.querySelector('[data-reactroot],[data-reactid]'))techs.push('React');
    if(window.Vue||doc.querySelector('[data-v-]'))techs.push('Vue');
    if(window.angular||doc.querySelector('[ng-app],[ng-controller]'))techs.push('Angular');
    if(window.jQuery||window.$)techs.push('jQuery');
    if(window.next)techs.push('Next.js');
    if(window.nuxt||window.__NUXT__)techs.push('Nuxt');
    if(doc.querySelector('[data-gatsby]'))techs.push('Gatsby');
    if(doc.querySelector('script[src*="gtag"]'))techs.push('GA4');
    if(doc.querySelector('script[src*="gtm"]'))techs.push('GTM');
    if(doc.querySelector('link[href*="tailwind"]')||doc.querySelector('[class*="tw-"]'))techs.push('Tailwind');

    /* 보안 */
    var isHttps=location.protocol==='https:';

    /* 읽기 분석 */
    var bodyText='';try{bodyText=_saExtractPageText(50000);}catch(e){try{var bc=doc.body.cloneNode(true);bc.querySelectorAll('script,style,noscript,[data-page-agent-ignore]').forEach(function(e2){e2.remove();});bodyText=bc.innerText||'';}catch(e3){}}
    var charCount=bodyText.replace(/\s/g,'').length;
    var readMin=Math.ceil(charCount/500);

    /* 렌더 */
    var html='';
    function sec(t){return '<div class="xr-section"><div class="xr-stitle">'+t+'</div>';}
    function row(l,v,cls){return '<div class="xr-item"><span class="xr-label">'+l+'</span><span class="xr-val '+(cls||'')+'">'+v+'</span></div>';}

    html+=sec('📋 SEO');
    html+=row('Title',title.length+' ('+esc(title.substring(0,30))+'…)', title.length>10&&title.length<70?'xr-good':'xr-warn');
    html+=row('Meta Desc',metaDesc.length>5?metaDesc.length+'자':'❌ 없음', metaDesc.length>50?'xr-good':'xr-bad');
    html+=row('H1 태그',h1s.length+'개', h1s.length===1?'xr-good':h1s.length===0?'xr-bad':'xr-warn');
    html+=row('H2 태그',h2s.length+'개');
    html+=row('OG Title',ogTitle.length>5?'✅':'❌', ogTitle.length>5?'xr-good':'xr-warn');
    html+=row('Canonical',canonical.length>5?'✅':'❌');
    html+=row('Lang',lang, lang!=='❌ 미설정'?'xr-good':'xr-warn');
    html+='</div>';

    html+=sec('🖼 리소스');
    html+=row('이미지',imgs.length+'개');
    html+=row('Alt 누락',imgNoAlt+'개', imgNoAlt===0?'xr-good':'xr-bad');
    html+=row('외부 스크립트',scripts.length+'개');
    html+=row('내부 링크',intLinks+'개');
    html+=row('외부 링크',extLinks+'개');
    html+='</div>';

    html+=sec('🔒 보안');
    html+=row('HTTPS',isHttps?'✅ 사용':'❌ 미사용', isHttps?'xr-good':'xr-bad');
    html+='</div>';

    html+=sec('📖 읽기 분석');
    html+=row('글자 수',charCount.toLocaleString()+'자');
    html+=row('예상 읽기',readMin+'분');
    html+='</div>';

    if(techs.length){
      html+=sec('⚙ 기술 스택');
      html+=row('감지됨',techs.join(', '),'xr-good');
      html+='</div>';
    }

    if(ogImg){
      html+='<div class="xr-section"><div class="xr-stitle">🖼 OG 미리보기</div>';
      html+='<img src="'+esc(ogImg)+'" style="width:100%;border-radius:8px;margin-top:4px;" onerror="this.style.display=\'none\'"/>';
      html+='</div>';
    }

    aC.innerHTML=html;
  }catch(e){
    aC.innerHTML='<p style="color:#e11d48;">❌ 분석 실패: '+esc(e.message)+'</p>';
  }
  hist.appendChild(aC);_scrollH();_chatHTML=hist.innerHTML;
}

/* ── 🌤 날씨 ── */
var _weatherCity='Seoul';
function runWeather(city){
  city=city||_weatherCity;
  _weatherCity=city;
  var hist=document.getElementById('__sa_H');if(!hist)return;
  if(hist.querySelector('div[style*="text-align:center"]'))hist.innerHTML='';

  var uC=document.createElement('div');uC.className='su';
  uC.innerHTML='<span style="opacity:.7;margin-right:4px;">🌤</span> '+esc(city)+' 날씨';
  hist.appendChild(uC);

  var aC=document.createElement('div');aC.className='sa';
  aC.innerHTML='<div style="display:flex;align-items:center;gap:6px;"><div class="sd"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></div><span style="font-size:11px;color:#5856D6;">'+esc(city)+' 날씨 로딩중...</span></div>';
  hist.appendChild(aC);_scrollH();

  fetch('https://wttr.in/'+encodeURIComponent(city)+'?format=j1&lang=ko',{mode:'cors'}).then(function(r){return r.json();}).then(function(d){
    var cur=d.current_condition[0];
    var area=(d.nearest_area[0].areaName[0]||{}).value||city;
    var country=(d.nearest_area[0].country[0]||{}).value||'';
    var temp=cur.temp_C;var feels=cur.FeelsLikeC;
    var desc=cur.weatherDesc[0].value;
    var humid=cur.humidity;var wind=cur.windspeedKmph;
    var uv=cur.uvIndex;

    var wIcon='☀️';var descKo=desc;
    if(/rain|drizzle/i.test(desc)){wIcon='🌧';descKo='비';}
    else if(/cloud|overcast/i.test(desc)){wIcon='☁️';descKo='흐림';}
    else if(/snow/i.test(desc)){wIcon='❄️';descKo='눈';}
    else if(/thunder/i.test(desc)){wIcon='⛈';descKo='천둥번개';}
    else if(/fog|mist/i.test(desc)){wIcon='🌫';descKo='안개';}
    else if(/partly/i.test(desc)){wIcon='⛅';descKo='구름조금';}
    else if(/sunny|clear/i.test(desc)){wIcon='☀️';descKo='맑음';}
    /* lang_ko 값이 있으면 사용 */
    var langKo=(cur.lang_ko||[{}])[0].value;if(langKo)descKo=langKo;

    var html='<div class="wth-card">';
    html+='<div style="display:flex;justify-content:space-between;align-items:center;">';
    html+='<div><div class="wth-temp">'+wIcon+' '+temp+'°C</div>';
    html+='<div class="wth-desc">체감 '+feels+'°C · '+descKo+'</div></div>';
    html+='<div style="text-align:right;font-size:11px;color:#666;">'+esc(area)+'<br>'+esc(country)+'</div></div>';
    html+='<div class="wth-detail">';
    html+='<span>💧 습도 '+humid+'%</span>';
    html+='<span>💨 바람 '+wind+'km/h</span>';
    html+='<span>☀️ UV '+uv+'</span></div></div>';

    /* 3일 예보 */
    var forecast=d.weather||[];
    if(forecast.length){
      html+='<div style="font-size:10px;font-weight:600;color:#5856D6;margin:8px 0 4px;">3일 예보</div>';
      html+='<div class="wth-fc">';
      forecast.forEach(function(day){
        var maxT=day.maxtempC;var minT=day.mintempC;
        var dayDesc=(day.hourly[4]||day.hourly[0]).weatherDesc[0].value;
        var dIcon='☀️';
        if(/rain/i.test(dayDesc))dIcon='🌧';else if(/cloud/i.test(dayDesc))dIcon='☁️';else if(/snow/i.test(dayDesc))dIcon='❄️';
        var dt=day.date.substring(5);
        html+='<div class="wth-fday"><div style="font-weight:600;">'+dt+'</div><div style="font-size:16px;">'+dIcon+'</div><div><b>'+maxT+'°</b>/'+minT+'°</div></div>';
      });
      html+='</div>';
    }

    /* 한국 주요 도시 버튼 */
    html+='<div style="margin-top:10px;"><div style="font-size:9px;color:#8e8e93;font-weight:600;margin-bottom:6px;">🇰🇷 한국 주요 도시</div>';
    html+='<div style="display:flex;flex-wrap:wrap;gap:4px;" id="__sa_wth_cities"></div></div>';

    aC.innerHTML=html;

    /* 도시 버튼 동적 생성 (이벤트 위임 대신 직접 바인딩) */
    var cityWrap=document.getElementById('__sa_wth_cities');
    if(cityWrap){
      var cities=[{n:'서울',c:'Seoul'},{n:'부산',c:'Busan'},{n:'인천',c:'Incheon'},{n:'대구',c:'Daegu'},{n:'대전',c:'Daejeon'},{n:'광주',c:'Gwangju'},{n:'울산',c:'Ulsan'},{n:'세종',c:'Sejong'},{n:'제주',c:'Jeju'}];
      cities.forEach(function(ct){
        var btn=document.createElement('button');
        btn.textContent=ct.n;
        btn.style.cssText='padding:3px 8px;border:1px solid '+(ct.c===city?'#5856D6':'rgba(0,0,0,.08)')+';border-radius:6px;font-size:10px;cursor:pointer;background:'+(ct.c===city?'rgba(88,86,214,.08)':'none')+';color:'+(ct.c===city?'#5856D6':'#666')+';font-weight:'+(ct.c===city?'700':'400')+';';
        btn.onclick=function(){runWeather(ct.c);};
        cityWrap.appendChild(btn);
      });
    }

    _scrollH();_chatHTML=hist.innerHTML;
  }).catch(function(e){
    aC.innerHTML='<p style="color:#e11d48;">❌ 날씨 로딩 실패: '+esc(e.message)+'</p><p style="font-size:10px;color:#8e8e93;">wttr.in 접속이 차단된 네트워크일 수 있습니다.</p>';
    _scrollH();
  });
}

/* ── 🤖 AI 도구 ── */
/* ═══ 화면 캡처 ═══ */
function runScreenCapture(){
  _viewMode='capture';P.innerHTML='';
  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','📷 화면 캡처'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','×');
  back.onclick=function(){_viewMode='main';renderMain();};
  hdr.appendChild(back);P.appendChild(hdr);
  var wrap=h('div','padding:12px;overflow-y:auto;flex:1;');
  wrap.innerHTML='<div style="padding:8px 10px;background:rgba(88,86,214,.04);border-radius:8px;margin-bottom:12px;font-size:10px;color:#555;line-height:1.6;border:1px solid rgba(88,86,214,.06);">'
    +'📷 실제 화면을 그대로 캡처합니다 (이미지/동영상 포함).</div>'
    +'<button id="__sa_cap_screen" class="img-gen-btn" style="margin-bottom:8px;">📷 화면 캡처</button>'
    +'<div id="__sa_cap_result" style="margin-top:8px;"></div>';
  P.appendChild(wrap);
  document.getElementById('__sa_cap_screen').onclick=function(){
    _saFeature('capture_screen');
    var result=document.getElementById('__sa_cap_result');
    result.innerHTML='<span style="font-size:11px;color:#5856D6;">공유할 화면을 선택하세요...</span>';
    navigator.mediaDevices.getDisplayMedia({video:true,audio:false}).then(function(stream){
      var track=stream.getVideoTracks()[0];
      var imgCapture=new ImageCapture(track);
      return imgCapture.grabFrame().then(function(bitmap){
        track.stop();
        stream.getTracks().forEach(function(t){t.stop();});
        var cvs=document.createElement('canvas');
        cvs.width=bitmap.width;cvs.height=bitmap.height;
        var ctx=cvs.getContext('2d');
        ctx.drawImage(bitmap,0,0);
        return cvs.toDataURL('image/png');
      });
    }).then(function(dataUrl){
      _showCaptureResult(dataUrl,'screen_capture');
    }).catch(function(e){
      if(e.name==='NotAllowedError') result.innerHTML='<p style="color:#8e8e93;font-size:11px;">캡처가 취소되었습니다.</p>';
      else result.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ '+esc(e.message)+'</p>';
    });
  };
}
function _showCaptureResult(dataUrl,type){
  var result=document.getElementById('__sa_cap_result');if(!result)return;
  var ts=new Date().toISOString().replace(/[:.]/g,'-').substring(0,19);
  result.innerHTML='';
  var img=document.createElement('img');img.src=dataUrl;img.style.cssText='width:100%;border-radius:8px;border:1px solid rgba(0,0,0,.06);margin-bottom:8px;';
  result.appendChild(img);
  var btns=document.createElement('div');btns.style.cssText='display:flex;gap:6px;flex-wrap:wrap;';
  var dl=document.createElement('a');dl.href=dataUrl;dl.download='siteagent-'+type+'-'+ts+'.png';
  dl.className='img-dl-btn';dl.innerHTML='💾 다운로드';btns.appendChild(dl);
  var cp=document.createElement('button');cp.className='img-dl-btn';cp.innerHTML='📋 클립보드 복사';
  cp.onclick=function(){
    fetch(dataUrl).then(function(r){return r.blob();}).then(function(blob){
      navigator.clipboard.write([new ClipboardItem({'image/png':blob})]).then(function(){cp.innerHTML='✅ 복사됨';setTimeout(function(){cp.innerHTML='📋 클립보드 복사';},1500);});
    }).catch(function(){cp.innerHTML='❌ 실패';});
  };
  btns.appendChild(cp);
  result.appendChild(btns);
}
/* ═══ 화면 녹화 ═══ */
var _saRecorder=null,_saRecChunks=[],_saRecStream=null,_saRecStartTime=0;
function runScreenRecord(){
  _viewMode='record';P.innerHTML='';
  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','🎬 화면 녹화'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','×');
  back.onclick=function(){_stopRecording();_viewMode='main';renderMain();};
  hdr.appendChild(back);P.appendChild(hdr);
  var wrap=h('div','padding:12px;overflow-y:auto;flex:1;');
  var isRecording=_saRecorder&&_saRecorder.state==='recording';
  if(!document.getElementById('__sa_rec_style')){
    var st=document.createElement('style');st.id='__sa_rec_style';
    st.textContent='@keyframes __sa_rec_pulse{0%,100%{opacity:1}50%{opacity:.3}}';
    document.head.appendChild(st);
  }
  if(isRecording){
    wrap.innerHTML='<div style="text-align:center;padding:20px;">'
      +'<div style="display:inline-block;width:14px;height:14px;background:#ef4444;border-radius:50%;animation:__sa_rec_pulse 1s infinite;margin-right:8px;vertical-align:middle;"></div>'
      +'<span style="font-size:16px;font-weight:700;color:#ef4444;" id="__sa_rec_timer">녹화 중...</span>'
      +'<br><button id="__sa_rec_stop" class="img-gen-btn" style="background:#ef4444;margin-top:16px;font-size:14px;padding:10px 28px;">⏹ 녹화 중지 & 저장</button></div>'
      +'<div id="__sa_rec_result" style="margin-top:8px;"></div>';
    P.appendChild(wrap);
    document.getElementById('__sa_rec_stop').onclick=function(){_stopRecording();};
    _updateRecTimer();
  }else{
    wrap.innerHTML='<div style="padding:8px 10px;background:rgba(88,86,214,.04);border-radius:8px;margin-bottom:12px;font-size:10px;color:#555;line-height:1.6;border:1px solid rgba(88,86,214,.06);">'
      +'🎬 화면을 녹화하여 WebM 동영상으로 저장합니다.</div>'
      +'<button id="__sa_rec_start" class="img-gen-btn" style="margin-bottom:8px;">🎬 녹화 시작</button>'
      +'<button id="__sa_rec_mic" class="img-gen-btn" style="background:linear-gradient(135deg,#f59e0b,#d97706);margin-bottom:8px;">🎤 화면+마이크 녹화</button>'
      +'<div id="__sa_rec_result" style="margin-top:8px;"></div>';
    P.appendChild(wrap);
    var startRec=function(withAudio){
      _saFeature('record_start');
      var opts={video:true,audio:!!withAudio};
      navigator.mediaDevices.getDisplayMedia(opts).then(function(stream){
        _saRecStream=stream;_saRecChunks=[];_saRecStartTime=Date.now();
        var mimeType='video/webm;codecs=vp9';
        if(!MediaRecorder.isTypeSupported(mimeType))mimeType='video/webm;codecs=vp8';
        if(!MediaRecorder.isTypeSupported(mimeType))mimeType='video/webm';
        _saRecorder=new MediaRecorder(stream,{mimeType:mimeType,videoBitsPerSecond:2500000});
        _saRecorder.ondataavailable=function(e){if(e.data&&e.data.size>0)_saRecChunks.push(e.data);};
        _saRecorder.onstop=function(){
          var blob=new Blob(_saRecChunks,{type:mimeType});
          _saRecChunks=[];
          if(_saRecStream){try{_saRecStream.getTracks().forEach(function(t){t.stop();});}catch(e){}}
          _saRecStream=null;_saRecorder=null;
          _showRecordResult(blob);
        };
        stream.getVideoTracks()[0].onended=function(){
          if(_saRecorder&&_saRecorder.state==='recording'){try{_saRecorder.stop();}catch(e){}}
        };
        _saRecorder.start(1000);
        runScreenRecord();
      }).catch(function(e){
        var result=document.getElementById('__sa_rec_result');
        if(e.name==='NotAllowedError'){if(result)result.innerHTML='<p style="color:#8e8e93;font-size:11px;">녹화가 취소되었습니다.</p>';}
        else{if(result)result.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ '+esc(e.message)+'</p>';}
      });
    };
    document.getElementById('__sa_rec_start').onclick=function(){startRec(false);};
    document.getElementById('__sa_rec_mic').onclick=function(){startRec(true);};
  }
}
function _stopRecording(){
  if(_saRecorder&&_saRecorder.state==='recording'){
    try{_saRecorder.stop();}catch(e){}
  }else{
    if(_saRecStream){try{_saRecStream.getTracks().forEach(function(t){t.stop();});}catch(e){}}
    _saRecStream=null;_saRecorder=null;
  }
}
function _updateRecTimer(){
  var el=document.getElementById('__sa_rec_timer');if(!el)return;
  if(!_saRecorder||_saRecorder.state!=='recording')return;
  var sec=Math.floor((Date.now()-_saRecStartTime)/1000);
  var mm=String(Math.floor(sec/60)).padStart(2,'0');
  var ss=String(sec%60).padStart(2,'0');
  el.textContent='녹화 중 '+mm+':'+ss;
  setTimeout(_updateRecTimer,1000);
}
function _showRecordResult(blob){
  _viewMode='record';
  var result=document.getElementById('__sa_rec_result');
  if(!result){runScreenRecord();result=document.getElementById('__sa_rec_result');}
  if(!result)return;
  var url=URL.createObjectURL(blob);
  var ts=new Date().toISOString().replace(/[:.]/g,'-').substring(0,19);
  var sizeMB=(blob.size/1024/1024).toFixed(1);
  var dur=Math.floor((Date.now()-_saRecStartTime)/1000);
  var mm=String(Math.floor(dur/60)).padStart(2,'0');
  var ss=String(dur%60).padStart(2,'0');
  result.innerHTML='';
  var vid=document.createElement('video');vid.src=url;vid.controls=true;vid.style.cssText='width:100%;border-radius:8px;border:1px solid rgba(0,0,0,.06);margin-bottom:8px;max-height:250px;background:#000;';
  result.appendChild(vid);
  var btns=document.createElement('div');btns.style.cssText='display:flex;gap:6px;flex-wrap:wrap;';
  var dl=document.createElement('a');dl.href=url;dl.download='siteagent-record-'+ts+'.webm';
  dl.className='img-dl-btn';dl.innerHTML='💾 다운로드 ('+sizeMB+'MB)';btns.appendChild(dl);
  result.appendChild(btns);
  result.appendChild(h('div','font-size:9px;color:#8e8e93;margin-top:6px;','⏱ '+mm+':'+ss+' · '+sizeMB+'MB · WebM'));
  _saFeature('record_complete',{duration:dur,size_mb:sizeMB});
}
/* ═══ 뉴스 ═══ */
function renderNews(){
  _viewMode='news';P.innerHTML='';
  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','📰 AI 뉴스'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','×');
  back.onclick=function(){_viewMode='main';renderMain();};
  hdr.appendChild(back);P.appendChild(hdr);
  var wrap=h('div','padding:12px;overflow-y:auto;flex:1;');
  var cats=['종합','IT·테크','경제·금융','정치·사회','연예·스포츠','국제'];
  var catHtml='<div style="display:flex;gap:4px;flex-wrap:wrap;margin-bottom:10px;">';
  cats.forEach(function(c,i){
    catHtml+='<button class="sa-news-cat" data-cat="'+c+'" style="padding:5px 10px;border:1px solid '+(i===0?'#5856D6':'rgba(0,0,0,.08)')+';border-radius:20px;font-size:9px;font-weight:'+(i===0?'700':'500')+';color:'+(i===0?'#fff':C.sub)+';background:'+(i===0?'#5856D6':'#fff')+';cursor:pointer;">'+c+'</button>';
  });
  catHtml+='</div>';
  wrap.innerHTML=catHtml+'<div id="__sa_news_result" style="font-size:11px;"><div style="text-align:center;padding:16px;color:'+C.sub+';font-size:10px;">카테고리를 선택하면 AI가 최신 뉴스를 브리핑합니다</div></div>';
  P.appendChild(wrap);
  var BASE=window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space';
  function loadNews(cat){
    wrap.querySelectorAll('.sa-news-cat').forEach(function(b){
      var active=b.getAttribute('data-cat')===cat;
      b.style.background=active?'#5856D6':'#fff';
      b.style.color=active?'#fff':C.sub;
      b.style.borderColor=active?'#5856D6':'rgba(0,0,0,.08)';
      b.style.fontWeight=active?'700':'500';
    });
    var res=document.getElementById('__sa_news_result');
    res.innerHTML='<div style="text-align:center;padding:20px;"><div class="sd"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></div><div style="font-size:10px;color:#5856D6;margin-top:8px;">📰 '+cat+' 뉴스 로딩 중...</div></div>';
    fetch(BASE+'/api/news',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({category:cat,count:5}),mode:'cors'}).then(function(r){return r.json();}).then(function(d){
      if(!d.ok){res.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ '+(d.error||'실패')+'</p>';return;}
      res.innerHTML='<div style="line-height:1.7;font-size:11px;">'+toHTML(d.content)+'</div>';
    }).catch(function(e){res.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ '+e.message+'</p>';});
  }
  wrap.querySelectorAll('.sa-news-cat').forEach(function(b){
    b.onclick=function(){loadNews(this.getAttribute('data-cat'));};
  });
  loadNews('종합');
}
/* ═══ 글쓰기 ═══ */
function renderWriter(){
  _viewMode='writer';P.innerHTML='';
  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','✍️ AI 글쓰기'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','×');
  back.onclick=function(){_viewMode='main';renderMain();};
  hdr.appendChild(back);P.appendChild(hdr);
  var wrap=h('div','padding:14px 12px 12px;overflow-y:auto;flex:1;');
  wrap.innerHTML='<div style="display:flex;gap:4px;margin-bottom:8px;position:relative;z-index:10;">'
    +'<select id="__sa_wr_style" style="flex:1;padding:6px;border:1px solid rgba(0,0,0,.08);border-radius:6px;font-size:10px;background:#fff;"><option value="블로그">📝 블로그</option><option value="SNS">📱 SNS</option><option value="이메일">📧 이메일</option><option value="보도자료">📰 보도자료</option><option value="광고카피">📢 광고카피</option><option value="유튜브대본">🎬 유튜브대본</option></select>'
    +'<select id="__sa_wr_tone" style="flex:1;padding:6px;border:1px solid rgba(0,0,0,.08);border-radius:6px;font-size:10px;background:#fff;"><option value="전문적">🎩 전문적</option><option value="친근한">😊 친근한</option><option value="유머러스">😄 유머러스</option><option value="격식체">📋 격식체</option></select>'
    +'</div>'
    +'<input id="__sa_wr_topic" type="text" placeholder="✏️ 주제 또는 제목 (예: AI가 바꿀 미래 교육)" style="width:100%;box-sizing:border-box;padding:8px;border:1px solid rgba(0,0,0,.08);border-radius:6px;font-size:11px;background:#fff;margin-bottom:6px;">'
    +'<div style="display:flex;gap:4px;margin-bottom:8px;">'
    +'<button id="__sa_wr_page" style="flex:1;padding:6px;border:1px solid rgba(88,86,214,.2);border-radius:6px;font-size:9px;color:#5856D6;background:rgba(88,86,214,.04);cursor:pointer;">📄 현재 페이지 참고</button>'
    +'<button id="__sa_wr_sel" style="flex:1;padding:6px;border:1px solid rgba(13,148,136,.2);border-radius:6px;font-size:9px;color:#0d9488;background:rgba(13,148,136,.04);cursor:pointer;">✂️ 선택 텍스트 참고</button>'
    +'</div>'
    +'<div id="__sa_wr_ctx" style="display:none;margin-bottom:6px;padding:6px 8px;background:rgba(0,0,0,.02);border-radius:6px;font-size:9px;color:#555;max-height:60px;overflow:hidden;"></div>'
    +'<button id="__sa_wr_go" class="img-gen-btn" style="width:100%;background:linear-gradient(135deg,#5856D6,#0d9488);">✍️ 글 생성하기</button>'
    +'<div id="__sa_wr_result" style="margin-top:10px;"></div>';
  P.appendChild(wrap);
  var _wrCtx='';
  var BASE=window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space';
  document.getElementById('__sa_wr_page').onclick=function(){
    var txt=document.body.innerText.substring(0,3000);
    _wrCtx=txt;
    var ctxEl=document.getElementById('__sa_wr_ctx');
    ctxEl.style.display='block';ctxEl.textContent='📄 페이지 참고: '+txt.substring(0,100)+'...';
    this.style.background='#5856D6';this.style.color='#fff';
  };
  document.getElementById('__sa_wr_sel').onclick=function(){
    var sel=window.getSelection().toString().trim();
    if(!sel){document.getElementById('__sa_wr_result').innerHTML='<p style="color:#e11d48;font-size:10px;">⚠️ 먼저 텍스트를 드래그 선택하세요</p>';return;}
    _wrCtx=sel;
    var ctxEl=document.getElementById('__sa_wr_ctx');
    ctxEl.style.display='block';ctxEl.textContent='✂️ 선택: '+sel.substring(0,100)+'...';
    this.style.background='#0d9488';this.style.color='#fff';
  };
  document.getElementById('__sa_wr_go').onclick=function(){
    var style=document.getElementById('__sa_wr_style').value;
    var tone=document.getElementById('__sa_wr_tone').value;
    var topic=document.getElementById('__sa_wr_topic').value.trim();
    if(!topic&&!_wrCtx){document.getElementById('__sa_wr_result').innerHTML='<p style="color:#e11d48;font-size:10px;">⚠️ 주제를 입력하거나 페이지/텍스트를 참고하세요</p>';return;}
    _saFeature('writer_generate');
    var res=document.getElementById('__sa_wr_result');
    var btn=this;btn.disabled=true;btn.innerHTML='✍️ 생성 중...';
    res.innerHTML='<div style="text-align:center;padding:16px;"><div class="sd"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></div><div style="font-size:10px;color:#5856D6;margin-top:6px;">AI가 글을 작성하고 있습니다...</div></div>';
    fetch(BASE+'/api/writer',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({style:style,tone:tone,topic:topic,context:_wrCtx}),mode:'cors'}).then(function(r){return r.json();}).then(function(d){
      btn.disabled=false;btn.innerHTML='✍️ 글 생성하기';
      if(!d.ok){res.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ '+(d.error||'실패')+'</p>';return;}
      res.innerHTML='<div style="border:1px solid rgba(0,0,0,.06);border-radius:8px;padding:10px;background:#fff;margin-bottom:6px;"><div style="line-height:1.7;font-size:11px;white-space:pre-wrap;">'+toHTML(d.content)+'</div></div>'
        +'<div style="display:flex;gap:4px;"><button id="__sa_wr_cp" class="img-dl-btn" style="font-size:9px;padding:5px 10px;">📋 복사</button></div>';
      document.getElementById('__sa_wr_cp').onclick=function(){
        var txt=d.content||'';
        navigator.clipboard.writeText(txt).then(function(){document.getElementById('__sa_wr_cp').innerHTML='✅ 복사됨';setTimeout(function(){document.getElementById('__sa_wr_cp').innerHTML='📋 복사';},1500);});
      };
    }).catch(function(e){btn.disabled=false;btn.innerHTML='✍️ 글 생성하기';res.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ '+e.message+'</p>';});
  };
}
/* ═══ 음악/라디오/TV ═══ */
function renderMusic(){
  _viewMode='music';P.innerHTML='';
  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','🎵 라디오 & TV'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','×');
  back.onclick=function(){_viewMode='main';renderMain();};
  hdr.appendChild(back);P.appendChild(hdr);
  var wrap=h('div','padding:0;overflow-y:auto;flex:1;');
  if(!window.__sa_audio)window.__sa_audio=null;
  if(!window.__sa_mu_ch)window.__sa_mu_ch='';
  var _muTab=window.__sa_mu_tab||0;
  var BASE=window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space';
  function render(){
    window.__sa_mu_tab=_muTab;
    var tabs='<div style="display:flex;border-bottom:1px solid rgba(0,0,0,.06);">';
    ['📻 라디오','📺 TV'].forEach(function(t,i){
      tabs+='<div class="sa-mu-tab" data-ti="'+i+'" style="flex:1;text-align:center;padding:8px 0;font-size:11px;font-weight:'+(i===_muTab?'700':'500')+';color:'+(i===_muTab?'#8b5cf6':C.sub)+';border-bottom:'+(i===_muTab?'2px solid #8b5cf6':'none')+';cursor:pointer;">'+t+'</div>';
    });
    tabs+='</div>';
    var playerHtml='';
    if(window.__sa_audio&&!window.__sa_audio.paused){
      playerHtml='<div style="padding:8px 12px;background:linear-gradient(135deg,rgba(139,92,246,.06),rgba(236,72,153,.06));border-bottom:1px solid rgba(139,92,246,.1);">'
        +'<style>@keyframes sa-eq{0%,100%{height:4px}50%{height:14px}}</style>'
        +'<div style="display:flex;align-items:center;gap:8px;">'
        +'<div style="display:flex;gap:2px;align-items:flex-end;height:16px;"><span style="width:3px;background:#8b5cf6;border-radius:1px;animation:sa-eq .4s ease infinite;"></span><span style="width:3px;background:#8b5cf6;border-radius:1px;animation:sa-eq .4s ease infinite .15s;"></span><span style="width:3px;background:#8b5cf6;border-radius:1px;animation:sa-eq .4s ease infinite .3s;"></span></div>'
        +'<div style="flex:1;font-size:10px;font-weight:600;color:#333;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">♫ '+window.__sa_mu_ch+'</div>'
        +'<input id="__sa_mu_vol" type="range" min="0" max="100" value="'+Math.round((window.__sa_audio?window.__sa_audio.volume:0.7)*100)+'" style="width:60px;height:3px;accent-color:#8b5cf6;">'
        +'<button id="__sa_mu_stop" style="border:none;background:#ef4444;color:#fff;font-size:9px;padding:3px 8px;border-radius:4px;cursor:pointer;font-weight:600;">⏹</button>'
        +'</div></div>';
    }
    var tvPlayerHtml='<div id="__sa_tv_player" style="display:none;"></div>';
    var body='<div style="padding:10px 12px;">';
    if(_muTab===0){
      body+='<div style="display:flex;gap:4px;margin-bottom:8px;">'
        +'<input id="__sa_rd_q" type="text" placeholder="🔍 방송국 검색..." style="flex:1;padding:7px 8px;border:1px solid rgba(0,0,0,.08);border-radius:6px;font-size:10px;background:#fff;">'
        +'<button id="__sa_rd_go" style="padding:7px 10px;border:none;border-radius:6px;background:#8b5cf6;color:#fff;font-size:10px;font-weight:700;cursor:pointer;">검색</button>'
        +'</div>';
      var presets=[
        {label:'🇰🇷 한국',country:'KR'},{label:'🇺🇸 미국',country:'US'},{label:'🇯🇵 일본',country:'JP'},
        {label:'🇬🇧 영국',country:'GB'},{label:'🇫🇷 프랑스',country:'FR'},{label:'🇧🇷 브라질',country:'BR'}
      ];
      body+='<div style="display:flex;gap:3px;flex-wrap:wrap;margin-bottom:6px;">';
      presets.forEach(function(p){
        body+='<button class="sa-rd-country" data-cc="'+p.country+'" style="padding:4px 8px;border:1px solid rgba(0,0,0,.06);border-radius:10px;font-size:8px;color:#555;background:#fff;cursor:pointer;">'+p.label+'</button>';
      });
      body+='</div>';
      var genres=['jazz','rock','pop','classical','lounge','electronic','news','talk'];
      body+='<div style="display:flex;gap:3px;flex-wrap:wrap;margin-bottom:10px;">';
      genres.forEach(function(g){
        body+='<button class="sa-rd-tag" data-tag="'+g+'" style="padding:3px 7px;border:1px solid rgba(139,92,246,.12);border-radius:10px;font-size:8px;color:#8b5cf6;background:rgba(139,92,246,.04);cursor:pointer;">#'+g+'</button>';
      });
      body+='</div>';
      body+='<div id="__sa_rd_list"><div style="text-align:center;color:#aaa;font-size:10px;padding:12px;">국가 또는 장르를 선택하세요</div></div>';
    }else{
      body+='<div style="display:flex;gap:3px;flex-wrap:wrap;margin-bottom:8px;">';
      [{label:'🇰🇷 한국',cc:'kr'},{label:'🇺🇸 미국',cc:'us'},{label:'🇯🇵 일본',cc:'jp'},{label:'🇬🇧 영국',cc:'gb'},{label:'🇫🇷 프랑스',cc:'fr'},{label:'🇩🇪 독일',cc:'de'}].forEach(function(p){
        body+='<button class="sa-tv-country" data-cc="'+p.cc+'" style="padding:4px 8px;border:1px solid rgba(0,0,0,.06);border-radius:10px;font-size:8px;color:#555;background:#fff;cursor:pointer;">'+p.label+'</button>';
      });
      body+='</div>';
      body+='<div id="__sa_tv_list"><div style="text-align:center;color:#aaa;font-size:10px;padding:12px;">국가를 선택하세요</div></div>';
    }
    body+='</div>';
    wrap.innerHTML=tabs+playerHtml+tvPlayerHtml+body;
    wrap.querySelectorAll('.sa-mu-tab').forEach(function(t){
      t.onclick=function(){_muTab=parseInt(this.getAttribute('data-ti'));render();};
    });
    if(document.getElementById('__sa_mu_stop')){
      document.getElementById('__sa_mu_stop').onclick=function(){
        if(window.__sa_audio){window.__sa_audio.pause();window.__sa_audio=null;}
        window.__sa_mu_ch='';render();
      };
    }
    if(document.getElementById('__sa_mu_vol')){
      document.getElementById('__sa_mu_vol').oninput=function(){
        if(window.__sa_audio)window.__sa_audio.volume=this.value/100;
      };
    }
    if(_muTab===0){
      function loadRadio(params){
        var list=document.getElementById('__sa_rd_list');
        list.innerHTML='<div style="text-align:center;padding:12px;"><div class="sd"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></div></div>';
        var qs=Object.keys(params).map(function(k){return k+'='+encodeURIComponent(params[k]);}).join('&');
        fetch(BASE+'/api/radio/search?'+qs,{mode:'cors'}).then(function(r){return r.json();}).then(function(d){
          if(!d.ok||!d.stations||!d.stations.length){list.innerHTML='<div style="text-align:center;color:#aaa;font-size:10px;padding:12px;">결과 없음</div>';return;}
          var html='';
          d.stations.forEach(function(s){
            html+='<div class="sa-rd-item" data-url="'+s.url+'" data-name="'+(s.name||'').replace(/"/g,'&quot;')+'" style="display:flex;align-items:center;gap:8px;padding:7px 4px;border-bottom:1px solid rgba(0,0,0,.03);cursor:pointer;">';
            if(s.favicon){
              html+='<img src="'+s.favicon+'" style="width:28px;height:28px;border-radius:6px;object-fit:cover;flex-shrink:0;border:1px solid rgba(0,0,0,.04);" onerror="this.style.display=\'none\'">';
            }else{
              html+='<div style="width:28px;height:28px;border-radius:6px;background:rgba(139,92,246,.08);display:flex;align-items:center;justify-content:center;font-size:12px;flex-shrink:0;">📻</div>';
            }
            html+='<div style="flex:1;min-width:0;"><div style="font-size:10px;font-weight:600;color:#333;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">'+s.name+'</div>'
              +'<div style="font-size:8px;color:#aaa;">'+s.country+(s.tags?' · '+s.tags.split(',').slice(0,2).join(', '):'')+(s.bitrate?' · '+s.bitrate+'kbps':'')+'</div></div>'
              +'<div style="font-size:14px;flex-shrink:0;">▶️</div></div>';
          });
          list.innerHTML=html;
          list.querySelectorAll('.sa-rd-item').forEach(function(el){
            el.onclick=function(){
              var url=this.getAttribute('data-url');
              var name=this.getAttribute('data-name');
              if(window.__sa_audio){window.__sa_audio.pause();window.__sa_audio=null;}
              var a=new Audio(url);a.volume=0.7;a.crossOrigin='anonymous';
              window.__sa_audio=a;window.__sa_mu_ch=name;
              a.play().then(function(){_saFeature('radio_play');render();}).catch(function(e){
                window.__sa_audio=null;window.__sa_mu_ch='';
                list.insertAdjacentHTML('afterbegin','<div style="color:#ef4444;font-size:9px;padding:6px;">❌ 재생 실패: '+e.message+'</div>');
              });
            };
          });
        }).catch(function(e){list.innerHTML='<div style="color:#ef4444;font-size:10px;padding:8px;">❌ '+e.message+'</div>';});
      }
      document.getElementById('__sa_rd_go').onclick=function(){
        var q=document.getElementById('__sa_rd_q').value.trim();
        if(q)loadRadio({q:q});
      };
      document.getElementById('__sa_rd_q').addEventListener('keydown',function(e){if(e.key==='Enter')document.getElementById('__sa_rd_go').click();});
      wrap.querySelectorAll('.sa-rd-country').forEach(function(b){
        b.onclick=function(){loadRadio({country:this.getAttribute('data-cc')});};
      });
      wrap.querySelectorAll('.sa-rd-tag').forEach(function(b){
        b.onclick=function(){loadRadio({tag:this.getAttribute('data-tag')});};
      });
    }else{
      function loadTV(cc){
        var list=document.getElementById('__sa_tv_list');
        var tvp=document.getElementById('__sa_tv_player');
        list.innerHTML='<div style="text-align:center;padding:12px;"><div class="sd"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></div></div>';
        fetch(BASE+'/api/tv/channels?country='+cc,{mode:'cors'}).then(function(r){return r.json();}).then(function(d){
          if(!d.ok||!d.channels||!d.channels.length){list.innerHTML='<div style="text-align:center;color:#aaa;font-size:10px;padding:12px;">채널 없음</div>';return;}
          var html='';
          d.channels.forEach(function(ch){
            html+='<div class="sa-tv-item" data-url="'+ch.url+'" data-name="'+(ch.name||'').replace(/"/g,'&quot;')+'" style="display:flex;align-items:center;gap:8px;padding:7px 4px;border-bottom:1px solid rgba(0,0,0,.03);cursor:pointer;">';
            if(ch.logo){
              html+='<img src="'+ch.logo+'" style="width:32px;height:24px;border-radius:4px;object-fit:contain;flex-shrink:0;border:1px solid rgba(0,0,0,.04);background:#f8f8f8;" onerror="this.style.display=\'none\'">';
            }else{
              html+='<div style="width:32px;height:24px;border-radius:4px;background:rgba(59,130,246,.08);display:flex;align-items:center;justify-content:center;font-size:10px;flex-shrink:0;">📺</div>';
            }
            html+='<div style="flex:1;min-width:0;"><div style="font-size:10px;font-weight:600;color:#333;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">'+ch.name+'</div>'
              +'<div style="font-size:8px;color:#aaa;">'+(ch.categories||[]).join(', ')+'</div></div>'
              +'<div style="font-size:12px;flex-shrink:0;">📺</div></div>';
          });
          list.innerHTML=html;
          list.querySelectorAll('.sa-tv-item').forEach(function(el){
            el.onclick=function(){
              var url=this.getAttribute('data-url');
              var name=this.getAttribute('data-name');
              if(window.__sa_audio){window.__sa_audio.pause();window.__sa_audio=null;window.__sa_mu_ch='';}
              tvp.style.display='block';
              tvp.innerHTML='<div style="padding:0 12px 8px;"><div style="background:#000;border-radius:8px;overflow:hidden;position:relative;">'
                +'<video id="__sa_tv_vid" style="width:100%;height:180px;border-radius:8px;" controls autoplay></video></div>'
                +'<div style="display:flex;align-items:center;justify-content:space-between;padding:4px 0;"><span style="font-size:10px;font-weight:600;color:#333;">📺 '+name+'</span>'
                +'<button id="__sa_tv_close" style="border:none;background:rgba(239,68,68,.08);color:#ef4444;font-size:9px;padding:3px 8px;border-radius:4px;cursor:pointer;">✕ 닫기</button></div></div>';
              var vid=document.getElementById('__sa_tv_vid');
              if(url.includes('.m3u8')||url.includes('.m3u')){
                var sc=document.createElement('script');
                sc.src='https://cdn.jsdelivr.net/npm/hls.js@latest';
                sc.onload=function(){
                  if(Hls.isSupported()){var hls=new Hls();hls.loadSource(url);hls.attachMedia(vid);hls.on(Hls.Events.MANIFEST_PARSED,function(){vid.play();});}
                  else if(vid.canPlayType('application/vnd.apple.mpegurl')){vid.src=url;vid.play();}
                  else{tvp.innerHTML='<div style="color:#ef4444;font-size:10px;padding:12px;">❌ HLS 미지원 브라우저</div>';}
                };
                document.head.appendChild(sc);
              }else{
                vid.src=url;vid.play().catch(function(e){tvp.innerHTML='<div style="color:#ef4444;font-size:10px;padding:12px;">❌ 재생 실패: '+e.message+'</div>';});
              }
              _saFeature('tv_play');
              document.getElementById('__sa_tv_close').onclick=function(){
                vid.pause();vid.src='';tvp.style.display='none';tvp.innerHTML='';
              };
            };
          });
        }).catch(function(e){list.innerHTML='<div style="color:#ef4444;font-size:10px;padding:8px;">❌ '+e.message+'</div>';});
      }
      wrap.querySelectorAll('.sa-tv-country').forEach(function(b){
        b.onclick=function(){loadTV(this.getAttribute('data-cc'));};
      });
    }
  }
  P.appendChild(wrap);
  render();
}
/* ═══ 페이스 (성형/관상/궁합) ═══ */
function renderFace(){
  _viewMode='face';P.innerHTML='';
  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','👤 페이스 AI'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','×');
  back.onclick=function(){_viewMode='main';renderMain();};
  hdr.appendChild(back);P.appendChild(hdr);
  var wrap=h('div','padding:0;overflow-y:auto;flex:1;');
  var BASE=window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space';
  var _fTab=0;
  function render(){
    var tabs='<div style="display:flex;border-bottom:1px solid rgba(0,0,0,.06);">';
    ['🏥 성형','🔮 관상','💑 궁합'].forEach(function(t,i){
      tabs+='<div class="sa-fc-tab" data-ti="'+i+'" style="flex:1;text-align:center;padding:8px 0;font-size:11px;font-weight:'+(i===_fTab?'700':'500')+';color:'+(i===_fTab?'#8b5cf6':C.sub)+';border-bottom:'+(i===_fTab?'2px solid #8b5cf6':'none')+';cursor:pointer;">'+t+'</div>';
    });
    tabs+='</div>';
    var body='<div style="padding:12px;">';
    if(_fTab===0){
      body+=_renderSurgeryTab();
    }else if(_fTab===1){
      body+=_renderPhysiognomyTab();
    }else{
      body+=_renderCompatTab();
    }
    body+='</div>';
    wrap.innerHTML=tabs+body;
    wrap.querySelectorAll('.sa-fc-tab').forEach(function(t){
      t.onclick=function(){_fTab=parseInt(this.getAttribute('data-ti'));render();};
    });
    _bindTabEvents();
  }
  function _renderSurgeryTab(){
    var presets=[
      {l:'👁️ 자연유착 쌍꺼풀',p:'Edit this photo of the person to add natural subtle double eyelid creases, keeping the same face'},
      {l:'👁️ 절개 쌍꺼풀',p:'Edit this photo of the person to add clear defined double eyelid creases, keeping the same face'},
      {l:'👃 코끝 성형',p:'Edit this photo of the person to refine and slightly raise the nasal tip, keeping the same face'},
      {l:'👃 콧대 성형',p:'Edit this photo of the person to make the nose bridge higher and more defined, keeping the same face'},
      {l:'🦷 사각턱 축소',p:'Edit this photo of the person to slim the jawline to a softer V-shape, keeping the same face'},
      {l:'💉 팔자주름 필러',p:'Edit this photo of the person to smooth the nasolabial fold lines for a fresher look, keeping the same face'},
      {l:'💉 이마 보톡스',p:'Edit this photo of the person to smooth forehead wrinkles for a cleaner forehead, keeping the same face'},
      {l:'💋 입술 필러',p:'Edit this photo of the person to make the lips fuller and more voluminous, keeping the same face'},
      {l:'🏥 눈+코 동시',p:'Edit this photo of the person to add natural double eyelid creases and raise the nose bridge, keeping the same face'},
      {l:'🏥 풀페이스 리프팅',p:'Edit this photo of the person to lift and tighten the face for a more youthful look, keeping the same face'},
      {l:'✨ 동안 스타일',p:'Edit this photo of the person to look younger with softer features and brighter skin, keeping the same face'}
    ];
    var html='<div style="font-size:10px;color:#555;background:linear-gradient(135deg,rgba(139,92,246,.04),rgba(236,72,153,.04));border-radius:8px;padding:8px;margin-bottom:8px;border:1px solid rgba(139,92,246,.08);">🏥 사진을 업로드하고 시술을 선택하면 AI가 시뮬레이션합니다.</div>';
    html+='<div style="margin-bottom:8px;"><label style="display:block;padding:20px;border:2px dashed rgba(0,0,0,.1);border-radius:8px;text-align:center;cursor:pointer;font-size:10px;color:#888;background:#fafafa;" id="__sa_fc_drop">📷 얼굴 사진 업로드 (클릭 또는 드래그)<input type="file" id="__sa_fc_file" accept="image/*" style="display:none;"></label></div>';
    html+='<div id="__sa_fc_preview" style="display:none;margin-bottom:8px;text-align:center;"><img id="__sa_fc_img" style="max-width:100%;max-height:150px;border-radius:8px;border:1px solid rgba(0,0,0,.06);"></div>';
    html+='<select id="__sa_fc_preset" style="width:100%;padding:7px 8px;border:1px solid rgba(0,0,0,.08);border-radius:6px;font-size:10px;background:#fff;margin-bottom:6px;">';
    presets.forEach(function(p,i){html+='<option value="'+i+'">'+p.l+'</option>';});
    html+='</select>';
    html+='<button id="__sa_fc_go" class="img-gen-btn" style="width:100%;background:linear-gradient(135deg,#8b5cf6,#ec4899);font-size:12px;padding:10px;" disabled>🏥 시뮬레이션 시작</button>';
    html+='<div id="__sa_fc_result"></div>';
    return html;
  }
  function _renderPhysiognomyTab(){
    var html='<div style="font-size:10px;color:#555;background:linear-gradient(135deg,rgba(168,85,247,.04),rgba(251,146,60,.04));border-radius:8px;padding:8px;margin-bottom:8px;border:1px solid rgba(168,85,247,.08);">🔮 얼굴 사진을 업로드하면 동양 관상학으로 분석합니다.</div>';
    html+='<div style="margin-bottom:8px;"><label style="display:block;padding:20px;border:2px dashed rgba(0,0,0,.1);border-radius:8px;text-align:center;cursor:pointer;font-size:10px;color:#888;background:#fafafa;" id="__sa_ph_drop">📷 얼굴 사진 업로드<input type="file" id="__sa_ph_file" accept="image/*" style="display:none;"></label></div>';
    html+='<div id="__sa_ph_preview" style="display:none;margin-bottom:8px;text-align:center;"><img id="__sa_ph_img" style="max-width:100%;max-height:120px;border-radius:8px;"></div>';
    html+='<button id="__sa_ph_go" class="img-gen-btn" style="width:100%;background:linear-gradient(135deg,#a855f7,#fb923c);font-size:12px;padding:10px;" disabled>🔮 관상 분석하기</button>';
    html+='<div id="__sa_ph_result"></div>';
    return html;
  }
  function _renderCompatTab(){
    var html='<div style="font-size:10px;color:#555;background:linear-gradient(135deg,rgba(236,72,153,.04),rgba(239,68,68,.04));border-radius:8px;padding:8px;margin-bottom:8px;border:1px solid rgba(236,72,153,.08);">💑 두 사람의 사진을 업로드하면 관상 궁합을 분석합니다.</div>';
    html+='<div style="display:flex;gap:6px;margin-bottom:8px;">';
    html+='<div style="flex:1;"><label style="display:block;padding:14px 4px;border:2px dashed rgba(0,0,0,.1);border-radius:8px;text-align:center;cursor:pointer;font-size:9px;color:#888;background:#fafafa;">👤 나<input type="file" id="__sa_cp_file1" accept="image/*" style="display:none;"></label><div id="__sa_cp_p1" style="display:none;text-align:center;margin-top:4px;"><img id="__sa_cp_img1" style="max-width:100%;max-height:80px;border-radius:6px;"></div></div>';
    html+='<div style="flex:1;"><label style="display:block;padding:14px 4px;border:2px dashed rgba(0,0,0,.1);border-radius:8px;text-align:center;cursor:pointer;font-size:9px;color:#888;background:#fafafa;">👤 상대<input type="file" id="__sa_cp_file2" accept="image/*" style="display:none;"></label><div id="__sa_cp_p2" style="display:none;text-align:center;margin-top:4px;"><img id="__sa_cp_img2" style="max-width:100%;max-height:80px;border-radius:6px;"></div></div>';
    html+='</div>';
    html+='<select id="__sa_cp_rel" style="width:100%;padding:6px;border:1px solid rgba(0,0,0,.08);border-radius:6px;font-size:10px;background:#fff;margin-bottom:6px;"><option>💑 연인/부부</option><option>🤝 친구/동료</option><option>💼 비즈니스</option><option>👨‍👩‍👧 가족</option></select>';
    html+='<button id="__sa_cp_go" class="img-gen-btn" style="width:100%;background:linear-gradient(135deg,#ec4899,#ef4444);font-size:12px;padding:10px;" disabled>💑 궁합 분석하기</button>';
    html+='<div id="__sa_cp_result"></div>';
    return html;
  }
  function _readFile(file,cb){
    var r=new FileReader();r.onload=function(){
      var img=new Image();img.onload=function(){
        var max=1024,w=img.width,hh=img.height;
        if(Math.max(w,hh)>max){var ratio=max/Math.max(w,hh);w=Math.round(w*ratio);hh=Math.round(hh*ratio);}
        var cv=document.createElement('canvas');cv.width=w;cv.height=hh;
        cv.getContext('2d').drawImage(img,0,0,w,hh);
        cb(cv.toDataURL('image/jpeg',0.85));
      };img.src=r.result;
    };r.readAsDataURL(file);
  }
  var _fcData={img:null,ph_img:null,cp_img1:null,cp_img2:null};
  function _bindTabEvents(){
    if(_fTab===0){
      var fi=document.getElementById('__sa_fc_file');
      if(fi)fi.onchange=function(){
        if(this.files[0])_readFile(this.files[0],function(d){
          _fcData.img=d;
          document.getElementById('__sa_fc_img').src=d;
          document.getElementById('__sa_fc_preview').style.display='block';
          document.getElementById('__sa_fc_go').disabled=false;
          document.getElementById('__sa_fc_drop').style.display='none';
        });
      };
      var go=document.getElementById('__sa_fc_go');
      if(go)go.onclick=function(){
        if(!_fcData.img)return;
        var presets=[
          'Edit this photo of the person to add natural subtle double eyelid creases, keeping the same face',
          'Edit this photo of the person to add clear defined double eyelid creases, keeping the same face',
          'Edit this photo of the person to refine and slightly raise the nasal tip, keeping the same face',
          'Edit this photo of the person to make the nose bridge higher and more defined, keeping the same face',
          'Edit this photo of the person to slim the jawline to a softer V-shape, keeping the same face',
          'Edit this photo of the person to smooth the nasolabial fold lines for a fresher look, keeping the same face',
          'Edit this photo of the person to smooth forehead wrinkles for a cleaner forehead, keeping the same face',
          'Edit this photo of the person to make the lips fuller and more voluminous, keeping the same face',
          'Edit this photo of the person to add natural double eyelid creases and raise the nose bridge, keeping the same face',
          'Edit this photo of the person to lift and tighten the face for a more youthful look, keeping the same face',
          'Edit this photo of the person to look younger with softer features and brighter skin, keeping the same face'
        ];
        var idx=parseInt(document.getElementById('__sa_fc_preset').value);
        var prompt=presets[idx]||presets[0];
        var res=document.getElementById('__sa_fc_result');
        var btn=this;btn.disabled=true;btn.innerHTML='🏥 시뮬레이션 중...';
        _saFeature('face_surgery');
        res.innerHTML='<div style="text-align:center;padding:20px;"><div class="sd"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></div><div style="font-size:10px;color:#8b5cf6;margin-top:8px;">AI가 시뮬레이션 중입니다...</div></div>';
        fetch(BASE+'/api/imagine-edit',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({prompt:prompt,image_url:_fcData.img}),mode:'cors'}).then(function(r){return r.json();}).then(function(d){
          btn.disabled=false;btn.innerHTML='🏥 시뮬레이션 시작';
          if(d.error){res.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ '+d.error+'</p>';return;}
          var afterSrc='';
          if(d.images&&d.images[0]){afterSrc=d.images[0].data_uri||d.images[0].url||'';}
          if(!afterSrc){afterSrc=d.data_uri||d.url||'';}
          if(!afterSrc){res.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ 결과 이미지 없음</p>';return;}
          res.innerHTML='<div style="margin-top:10px;">'
            +'<div style="font-size:11px;font-weight:700;color:#333;margin-bottom:6px;">📸 Before / After 비교</div>'
            +'<div id="__sa_fc_ba" style="position:relative;width:100%;border-radius:10px;overflow:hidden;border:1px solid rgba(0,0,0,.06);touch-action:none;user-select:none;">'
            +'<img id="__sa_fc_after" src="'+afterSrc+'" style="width:100%;display:block;">'
            +'<div id="__sa_fc_before_wrap" style="position:absolute;top:0;left:0;width:50%;height:100%;overflow:hidden;">'
            +'<img id="__sa_fc_before" src="'+_fcData.img+'" style="width:0;height:100%;display:block;object-fit:cover;">'
            +'</div>'
            +'<div id="__sa_fc_slider" style="position:absolute;top:0;left:50%;width:3px;height:100%;background:#fff;cursor:ew-resize;box-shadow:0 0 6px rgba(0,0,0,.3);z-index:10;">'
            +'<div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:28px;height:28px;background:#fff;border-radius:50%;box-shadow:0 0 8px rgba(0,0,0,.3);display:flex;align-items:center;justify-content:center;font-size:12px;">⟷</div>'
            +'</div>'
            +'</div>'
            +'<div style="display:flex;justify-content:space-between;padding:4px 2px;font-size:9px;color:#888;"><span>◀ Before</span><span>After ▶</span></div>'
            +'</div>';
          var ba=document.getElementById('__sa_fc_ba');
          var bw=document.getElementById('__sa_fc_before_wrap');
          var bi=document.getElementById('__sa_fc_before');
          var sl=document.getElementById('__sa_fc_slider');
          bi.style.width=ba.offsetWidth+'px';
          function moveTo(x){
            var rect=ba.getBoundingClientRect();
            var pct=Math.max(0,Math.min(1,(x-rect.left)/rect.width));
            bw.style.width=(pct*100)+'%';
            sl.style.left=(pct*100)+'%';
          }
          var dragging=false;
          sl.onmousedown=function(){dragging=true;};
          ba.onmousemove=function(e){if(dragging)moveTo(e.clientX);};
          document.addEventListener('mouseup',function(){dragging=false;});
          ba.ontouchstart=function(e){dragging=true;moveTo(e.touches[0].clientX);};
          ba.ontouchmove=function(e){if(dragging){e.preventDefault();moveTo(e.touches[0].clientX);}};
          ba.ontouchend=function(){dragging=false;};
          ba.onclick=function(e){moveTo(e.clientX);};
        }).catch(function(e){btn.disabled=false;btn.innerHTML='🏥 시뮬레이션 시작';res.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ '+e.message+'</p>';});
      };
    }else if(_fTab===1){
      var fi=document.getElementById('__sa_ph_file');
      if(fi)fi.onchange=function(){
        if(this.files[0])_readFile(this.files[0],function(d){
          _fcData.ph_img=d;
          document.getElementById('__sa_ph_img').src=d;
          document.getElementById('__sa_ph_preview').style.display='block';
          document.getElementById('__sa_ph_go').disabled=false;
          document.getElementById('__sa_ph_drop').style.display='none';
        });
      };
      var go=document.getElementById('__sa_ph_go');
      if(go)go.onclick=function(){
        if(!_fcData.ph_img)return;
        var res=document.getElementById('__sa_ph_result');
        var btn=this;btn.disabled=true;btn.innerHTML='🔮 분석 중...';
        _saFeature('face_read');
        res.innerHTML='<div style="text-align:center;padding:20px;"><div class="sd"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></div><div style="font-size:10px;color:#a855f7;margin-top:8px;">관상 분석 중... (30초~1분)</div></div>';
        fetch(BASE+'/api/face/read',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({image:_fcData.ph_img}),mode:'cors'}).then(function(r){return r.json();}).then(function(d){
          btn.disabled=false;btn.innerHTML='🔮 관상 분석하기';
          if(d.error){res.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ '+d.error+'</p>';return;}
          var html='';
          if(d.data&&d.data.scores){
            var sc=d.data.scores;var oh=d.data.oheng||'';var et=d.data.eye_type||'';
            html+='<div style="background:linear-gradient(135deg,rgba(168,85,247,.06),rgba(251,146,60,.06));border:1px solid rgba(168,85,247,.12);border-radius:10px;padding:10px;margin:10px 0;">';
            html+='<div style="text-align:center;margin-bottom:6px;"><span style="font-size:16px;font-weight:800;color:#7c3aed;">'+oh+'</span><br><span style="font-size:9px;color:#888;">'+et+'</span></div>';
            Object.keys(sc).forEach(function(k){
              var v=sc[k];var color=v>=75?'#22c55e':v>=55?'#f59e0b':'#ef4444';
              html+='<div style="display:flex;align-items:center;gap:4px;margin-bottom:3px;"><span style="font-size:9px;width:60px;color:#555;">'+k+'</span><div style="flex:1;height:6px;background:rgba(0,0,0,.04);border-radius:3px;"><div style="height:100%;width:'+v+'%;background:'+color+';border-radius:3px;"></div></div><span style="font-size:9px;font-weight:700;color:'+color+';">'+v+'</span></div>';
            });
            html+='</div>';
          }
          html+='<div style="font-size:10px;line-height:1.7;color:#333;margin-top:8px;">'+toHTML(d.analysis)+'</div>';
          res.innerHTML=html;
        }).catch(function(e){btn.disabled=false;btn.innerHTML='🔮 관상 분석하기';res.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ '+e.message+'</p>';});
      };
    }else{
      ['__sa_cp_file1','__sa_cp_file2'].forEach(function(fid,idx){
        var fi=document.getElementById(fid);
        if(fi)fi.onchange=function(){
          if(this.files[0])_readFile(this.files[0],function(d){
            if(idx===0){_fcData.cp_img1=d;document.getElementById('__sa_cp_img1').src=d;document.getElementById('__sa_cp_p1').style.display='block';}
            else{_fcData.cp_img2=d;document.getElementById('__sa_cp_img2').src=d;document.getElementById('__sa_cp_p2').style.display='block';}
            if(_fcData.cp_img1&&_fcData.cp_img2)document.getElementById('__sa_cp_go').disabled=false;
          });
        };
      });
      var go=document.getElementById('__sa_cp_go');
      if(go)go.onclick=function(){
        if(!_fcData.cp_img1||!_fcData.cp_img2)return;
        var rel=document.getElementById('__sa_cp_rel').value;
        var res=document.getElementById('__sa_cp_result');
        var btn=this;btn.disabled=true;btn.innerHTML='💑 분석 중...';
        _saFeature('face_compat');
        res.innerHTML='<div style="text-align:center;padding:20px;"><div class="sd"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></div><div style="font-size:10px;color:#ec4899;margin-top:8px;">궁합 분석 중... (30초~1분)</div></div>';
        fetch(BASE+'/api/face/compat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({image1:_fcData.cp_img1,image2:_fcData.cp_img2,relationship:rel}),mode:'cors'}).then(function(r){return r.json();}).then(function(d){
          btn.disabled=false;btn.innerHTML='💑 궁합 분석하기';
          if(d.error){res.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ '+d.error+'</p>';return;}
          var html='';
          if(d.data&&d.data.scores){
            var sc=d.data.scores;var tot=d.data.total||0;var gr=d.data.grade||'';
            html+='<div style="background:linear-gradient(135deg,rgba(236,72,153,.06),rgba(239,68,68,.06));border:1px solid rgba(236,72,153,.12);border-radius:10px;padding:10px;margin:10px 0;">';
            html+='<div style="text-align:center;margin-bottom:6px;"><span style="font-size:24px;font-weight:800;color:#ec4899;">'+tot+'점</span><span style="font-size:14px;color:#888;margin-left:4px;">'+gr+'</span><br>';
            if(d.data.oheng1&&d.data.oheng2)html+='<span style="font-size:10px;color:#666;">'+d.data.oheng1+' × '+d.data.oheng2+'</span>';
            html+='</div>';
            Object.keys(sc).forEach(function(k){
              var v=sc[k];var color=v>=75?'#ec4899':v>=55?'#f59e0b':'#9ca3af';
              html+='<div style="display:flex;align-items:center;gap:4px;margin-bottom:3px;"><span style="font-size:9px;width:55px;color:#555;">'+k+'</span><div style="flex:1;height:6px;background:rgba(0,0,0,.04);border-radius:3px;"><div style="height:100%;width:'+v+'%;background:'+color+';border-radius:3px;"></div></div><span style="font-size:9px;font-weight:700;color:'+color+';">'+v+'</span></div>';
            });
            html+='</div>';
          }
          html+='<div style="font-size:10px;line-height:1.7;color:#333;margin-top:8px;">'+toHTML(d.analysis)+'</div>';
          res.innerHTML=html;
        }).catch(function(e){btn.disabled=false;btn.innerHTML='💑 궁합 분석하기';res.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ '+e.message+'</p>';});
      };
    }
  }
  P.appendChild(wrap);
  render();
}
/* ═══ 채팅 (장기기억 자동) ═══ */
function renderChat(){
  _viewMode='chat';P.innerHTML='';
  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','💬 AI 채팅'));
  var right=h('div','display:flex;gap:6px;align-items:center;');
  var memBadge=h('span','font-size:8px;color:#6366f1;background:rgba(99,102,241,.08);padding:2px 6px;border-radius:8px;','🧠 기억 ON');
  right.appendChild(memBadge);
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','×');
  back.onclick=function(){_viewMode='main';renderMain();};
  right.appendChild(back);
  hdr.appendChild(right);P.appendChild(hdr);
  var msgArea=h('div','flex:1;overflow-y:auto;padding:10px 12px;display:flex;flex-direction:column;gap:6px;');
  msgArea.id='__sa_chat_msgs';
  if(!window.__sa_chat_history)window.__sa_chat_history=[];
  var BASE=window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space';
  var email=(window.__SA_USER_EMAIL||'').trim().toLowerCase();
  if(window.__sa_chat_history.length===0){
    msgArea.innerHTML='<div style="text-align:center;padding:30px 10px;color:#aaa;font-size:11px;line-height:1.8;">'
      +'<div style="font-size:28px;margin-bottom:8px;">💬</div>'
      +'안녕하세요! 무엇이든 물어보세요.<br>'
      +'<span style="font-size:9px;color:#bbb;">대화 내용을 기억하고 다음 대화에 활용합니다.</span></div>';
  }else{
    _renderChatHistory(msgArea);
  }
  P.appendChild(msgArea);
  var inputBar=h('div','display:flex;gap:4px;padding:8px 12px;border-top:1px solid rgba(0,0,0,.04);flex-shrink:0;background:#fff;');
  inputBar.innerHTML='<input id="__sa_chat_in" type="text" placeholder="메시지를 입력하세요..." style="flex:1;padding:8px 10px;border:1px solid rgba(0,0,0,.08);border-radius:8px;font-size:11px;background:#f8f8fa;outline:none;">'
    +'<button id="__sa_chat_mic" style="padding:8px;border:none;border-radius:8px;background:rgba(99,102,241,.06);color:#6366f1;font-size:14px;cursor:pointer;" title="음성 입력">🎤</button>'
    +'<button id="__sa_chat_send" style="padding:8px 14px;border:none;border-radius:8px;background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;font-size:12px;font-weight:700;cursor:pointer;">전송</button>';
  P.appendChild(inputBar);
  function _renderChatHistory(el){
    el.innerHTML='';
    window.__sa_chat_history.forEach(function(m){
      var isUser=m.role==='user';
      var bubble=document.createElement('div');
      bubble.style.cssText='max-width:85%;padding:8px 10px;border-radius:'+(isUser?'12px 12px 2px 12px':'12px 12px 12px 2px')+';font-size:10px;line-height:1.6;word-break:break-word;'
        +(isUser?'background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;align-self:flex-end;':'background:#f0f0f5;color:#333;align-self:flex-start;');
      bubble.innerHTML=isUser?m.content:toHTML(m.content);
      el.appendChild(bubble);
    });
    el.scrollTop=el.scrollHeight;
  }
  function _qid(id){return document.getElementById(id)||(P?P.querySelector('#'+id):null);}
  function sendMsg(){
    var inp=_qid('__sa_chat_in');
    if(!inp)return;
    var msg=inp.value.trim();
    if(!msg)return;
    inp.value='';
    window.__sa_chat_history.push({role:'user',content:msg});
    _renderChatHistory(msgArea);
    var typing=document.createElement('div');
    typing.style.cssText='max-width:85%;padding:8px 10px;border-radius:12px 12px 12px 2px;background:#f0f0f5;align-self:flex-start;font-size:10px;color:#888;';
    typing.innerHTML='<div class="sd" style="display:inline-flex;"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></div> 생각 중...';
    typing.id='__sa_chat_typing';
    msgArea.appendChild(typing);
    msgArea.scrollTop=msgArea.scrollHeight;
    _saFeature('chat_memory');
    var pageCtx='';
    try{pageCtx=document.title+' | '+location.href;}catch(e){}
    fetch(BASE+'/api/chat/completions',{
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body:JSON.stringify({
        messages:[
          {role:'system',content:'당신은 SiteAgent AI 어시스턴트입니다. 사용자와의 대화를 기억하고 개인화된 도움을 제공합니다. 반드시 한국어로 자연스럽게 답변하세요. 현재 페이지: '+pageCtx},
          {role:'user',content:msg}
        ],
        sa_email:email,
        sa_url:location.href||''
      }),
      mode:'cors'
    }).then(function(r){return r.json();}).then(function(d){
      var t=_qid('__sa_chat_typing');
      if(t)t.remove();
      var reply='';
      try{reply=d.choices[0].message.content||'';}catch(e){reply=d.error?.message||'응답을 받지 못했습니다.';}
      window.__sa_chat_history.push({role:'assistant',content:reply});
      _renderChatHistory(msgArea);
    }).catch(function(e){
      var t=_qid('__sa_chat_typing');
      if(t)t.remove();
      window.__sa_chat_history.push({role:'assistant',content:'❌ 오류: '+e.message});
      _renderChatHistory(msgArea);
    });
  }
  var _chatSend=_qid('__sa_chat_send');
  if(_chatSend)_chatSend.onclick=sendMsg;
  var _chatIn=_qid('__sa_chat_in');
  if(_chatIn){
    _chatIn.addEventListener('keydown',function(e){
      if(e.isComposing)return;
      if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();sendMsg();}
    });
    _chatIn.addEventListener('keypress',function(e){e.stopPropagation();e.stopImmediatePropagation();},{capture:true});
  }
  var micBtn=_qid('__sa_chat_mic');
  var _recognition=null;var _micOn=false;
  if(window.SpeechRecognition||window.webkitSpeechRecognition){
    var SR=window.SpeechRecognition||window.webkitSpeechRecognition;
    micBtn.onclick=function(){
      if(_micOn){_recognition.stop();return;}
      _recognition=new SR();
      _recognition.lang='ko-KR';
      _recognition.interimResults=true;
      _recognition.continuous=false;
      _micOn=true;
      micBtn.style.background='#ef4444';micBtn.style.color='#fff';micBtn.innerHTML='⏹';
      var inp=_qid('__sa_chat_in');
      var _prev=inp.value;
      _recognition.onresult=function(ev){
        var t='';
        for(var i=ev.resultIndex;i<ev.results.length;i++){t+=ev.results[i][0].transcript;}
        inp.value=_prev?_prev+' '+t:t;
      };
      _recognition.onend=function(){
        _micOn=false;
        micBtn.style.background='rgba(99,102,241,.06)';micBtn.style.color='#6366f1';micBtn.innerHTML='🎤';
        if(inp.value.trim())inp.focus();
      };
      _recognition.onerror=function(){
        _micOn=false;
        micBtn.style.background='rgba(99,102,241,.06)';micBtn.style.color='#6366f1';micBtn.innerHTML='🎤';
      };
      _recognition.start();
    };
  }else{
    micBtn.style.display='none';
  }
  setTimeout(function(){var ci=_qid('__sa_chat_in');if(ci)ci.focus();},100);
}
/* ═══ 쇼핑 가격비교 ═══ */
function renderShopping(){
  _viewMode='shopping';P.innerHTML='';
  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','🛒 쇼핑 최저가'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','×');
  back.onclick=function(){_viewMode='main';renderMain();};
  hdr.appendChild(back);P.appendChild(hdr);
  var wrap=h('div','padding:12px;overflow-y:auto;flex:1;');
  var BASE=window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space';
  wrap.innerHTML='<div style="display:flex;gap:4px;margin-bottom:8px;">'
    +'<input id="__sa_sh_q" type="text" placeholder="🔍 상품명 검색 (예: 에어팟 프로 2)" style="flex:1;padding:8px;border:1px solid rgba(0,0,0,.08);border-radius:6px;font-size:11px;background:#fff;">'
    +'<button id="__sa_sh_go" style="padding:8px 12px;border:none;border-radius:6px;background:linear-gradient(135deg,#ef4444,#f97316);color:#fff;font-size:11px;font-weight:700;cursor:pointer;">검색</button>'
    +'</div>'
    +'<div style="display:flex;gap:4px;flex-wrap:wrap;margin-bottom:8px;">';
  ['에어팟 프로 2','갤럭시 S25','맥북 에어 M4','다이슨 에어랩','닌텐도 스위치2'].forEach(function(q){
    wrap.innerHTML+='<button class="sa-sh-quick" data-q="'+q+'" style="padding:4px 8px;border:1px solid rgba(0,0,0,.06);border-radius:12px;font-size:8px;color:#666;background:#fff;cursor:pointer;">'+q+'</button>';
  });
  wrap.innerHTML+='</div>'
    +'<div style="display:flex;gap:4px;margin-bottom:10px;">'
    +'<button class="sa-sh-sort" data-s="sim" style="padding:3px 8px;border:1px solid #ef4444;border-radius:10px;font-size:8px;color:#fff;background:#ef4444;cursor:pointer;">정확도</button>'
    +'<button class="sa-sh-sort" data-s="asc" style="padding:3px 8px;border:1px solid rgba(0,0,0,.08);border-radius:10px;font-size:8px;color:#666;background:#fff;cursor:pointer;">낮은가격</button>'
    +'<button class="sa-sh-sort" data-s="dsc" style="padding:3px 8px;border:1px solid rgba(0,0,0,.08);border-radius:10px;font-size:8px;color:#666;background:#fff;cursor:pointer;">높은가격</button>'
    +'<button class="sa-sh-sort" data-s="date" style="padding:3px 8px;border:1px solid rgba(0,0,0,.08);border-radius:10px;font-size:8px;color:#666;background:#fff;cursor:pointer;">최신순</button>'
    +'</div>'
    +'<div id="__sa_sh_result"></div>';
  P.appendChild(wrap);
  var _shSort='sim';
  function _setSort(s){
    _shSort=s;
    wrap.querySelectorAll('.sa-sh-sort').forEach(function(b){
      var active=b.getAttribute('data-s')===s;
      b.style.background=active?'#ef4444':'#fff';
      b.style.color=active?'#fff':'#666';
      b.style.borderColor=active?'#ef4444':'rgba(0,0,0,.08)';
    });
  }
  wrap.querySelectorAll('.sa-sh-sort').forEach(function(b){
    b.onclick=function(){
      _setSort(this.getAttribute('data-s'));
      var q=document.getElementById('__sa_sh_q').value.trim();
      if(q)doSearch(q);
    };
  });
  function _fmtPrice(n){return n?n.toString().replace(/\B(?=(\d{3})+(?!\d))/g,',')+'원':'—';}
  function doSearch(query){
    _saFeature('shopping_search');
    var res=document.getElementById('__sa_sh_result');
    res.innerHTML='<div style="text-align:center;padding:20px;"><div class="sd"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></div><div style="font-size:10px;color:#ef4444;margin-top:8px;">🛒 '+query+' 검색 중...</div></div>';
    fetch(BASE+'/api/shopping',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({query:query,sort:_shSort}),mode:'cors'}).then(function(r){
      if(!r.ok)return r.text().then(function(t){throw new Error('HTTP '+r.status+': '+t.substring(0,100));});
      return r.json();
    }).then(function(d){
      if(!d.ok){res.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ '+(d.error||'알 수 없는 오류')+'</p>';return;}
      var items=d.items||[];
      if(!items.length){res.innerHTML='<p style="color:#888;font-size:11px;">검색 결과가 없습니다.</p>';return;}
      var html='';
      if(d.lowest){
        html+='<div style="background:linear-gradient(135deg,#fef2f2,#fff7ed);border:1px solid rgba(239,68,68,.15);border-radius:10px;padding:10px;margin-bottom:10px;text-align:center;">'
          +'<div style="font-size:9px;color:#888;">🏆 최저가</div>'
          +'<div style="font-size:18px;font-weight:800;color:#ef4444;">'+_fmtPrice(d.lowest)+'</div>'
          +'<div style="font-size:9px;color:#aaa;">총 '+d.total+'개 상품 중</div></div>';
      }
      items.forEach(function(item,i){
        var isLowest=item.price===d.lowest;
        html+='<div style="display:flex;gap:8px;padding:8px;border:1px solid '+(isLowest?'rgba(239,68,68,.2)':'rgba(0,0,0,.04)')+';border-radius:8px;margin-bottom:6px;background:'+(isLowest?'rgba(239,68,68,.02)':'#fff')+';'+(isLowest?'box-shadow:0 0 8px rgba(239,68,68,.08);':'')+'position:relative;">';
        if(item.image){
          html+='<img src="'+item.image+'" style="width:56px;height:56px;border-radius:6px;object-fit:cover;flex-shrink:0;border:1px solid rgba(0,0,0,.04);" onerror="this.style.display=\'none\'">';
        }
        html+='<div style="flex:1;min-width:0;">'
          +'<div onclick="window.open(\''+item.link.replace(/'/g,"\\'")+'\',\'_blank\')" style="font-size:10px;font-weight:600;color:#333;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;cursor:pointer;">'+(isLowest?'🏆 ':'')+item.title+'</div>'
          +'<div style="display:flex;align-items:baseline;gap:4px;margin-top:3px;">'
          +'<span style="font-size:13px;font-weight:800;color:'+(isLowest?'#ef4444':'#333')+';">'+_fmtPrice(item.price)+'</span>';
        if(item.hprice&&item.hprice>item.price){
          html+='<span style="font-size:9px;color:#aaa;text-decoration:line-through;">'+_fmtPrice(item.hprice)+'</span>';
        }
        html+='</div>'
          +'<div style="display:flex;align-items:center;gap:4px;margin-top:2px;">'
          +'<span style="font-size:8px;color:#888;background:rgba(0,0,0,.03);padding:1px 4px;border-radius:3px;">🏪 '+item.mall+'</span>';
        if(item.category){
          html+='<span style="font-size:7px;color:#aaa;">'+item.category+'</span>';
        }
        html+='</div></div>'
          +'<div onclick="window.open(\''+item.link.replace(/'/g,"\\'")+'\',\'_blank\')" style="position:absolute;top:8px;right:8px;font-size:9px;color:#fff;background:#5856D6;padding:3px 8px;border-radius:4px;cursor:pointer;font-weight:600;">🔗 바로가기</div>'
          +'</div>';
      });
      res.innerHTML=html;
    }).catch(function(e){res.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ '+e.message+'</p>';});
  }
  document.getElementById('__sa_sh_go').onclick=function(){
    var q=document.getElementById('__sa_sh_q').value.trim();
    if(!q)return;
    doSearch(q);
  };
  document.getElementById('__sa_sh_q').addEventListener('keydown',function(e){
    if(e.key==='Enter'){document.getElementById('__sa_sh_go').click();}
  });
  wrap.querySelectorAll('.sa-sh-quick').forEach(function(b){
    b.onclick=function(){
      var q=this.getAttribute('data-q');
      document.getElementById('__sa_sh_q').value=q;
      doSearch(q);
    };
  });
}
/* ═══ 사주/운세 ═══ */
function renderSaju(){
  _viewMode='saju';P.innerHTML='';
  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','🔮 사주/운세'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','×');
  back.onclick=function(){_viewMode='main';renderMain();};
  hdr.appendChild(back);P.appendChild(hdr);
  var wrap=h('div','padding:12px;overflow-y:auto;flex:1;');
  wrap.innerHTML='<div style="font-size:10px;color:#555;background:linear-gradient(135deg,rgba(147,51,234,.05),rgba(236,72,153,.05));border-radius:10px;padding:10px;margin-bottom:10px;border:1px solid rgba(147,51,234,.1);">'
    +'🔮 생년월일시를 입력하면 <b>전통 명리학 + AI</b>로 사주팔자를 분석합니다.</div>'
    +'<div style="display:flex;gap:4px;margin-bottom:8px;">'
    +'<select id="__sa_sj_cal" style="flex:1;padding:6px;border:1px solid rgba(0,0,0,.08);border-radius:6px;font-size:10px;background:#fff;"><option value="양력">☀️ 양력</option><option value="음력">🌙 음력</option></select>'
    +'<select id="__sa_sj_gen" style="flex:1;padding:6px;border:1px solid rgba(0,0,0,.08);border-radius:6px;font-size:10px;background:#fff;"><option value="남">👨 남</option><option value="여">👩 여</option></select>'
    +'<select id="__sa_sj_mode" style="flex:1;padding:6px;border:1px solid rgba(0,0,0,.08);border-radius:6px;font-size:10px;background:#fff;"><option value="물닭">🐣 물닭</option><option value="불닭">🔥 불닭</option></select>'
    +'</div>'
    +'<div style="display:flex;gap:4px;margin-bottom:8px;">'
    +'<input id="__sa_sj_date" type="text" placeholder="생년월일 8자리 (19900515)" maxlength="8" style="flex:2;padding:7px 8px;border:1px solid rgba(0,0,0,.08);border-radius:6px;font-size:11px;background:#fff;">'
    +'<input id="__sa_sj_time" type="text" placeholder="생시 4자리 (1430)" maxlength="4" style="flex:1;padding:7px 8px;border:1px solid rgba(0,0,0,.08);border-radius:6px;font-size:11px;background:#fff;">'
    +'</div>'
    +'<input id="__sa_sj_concern" type="text" placeholder="💬 고민 (선택사항: 직장운, 연애운 등)" style="width:100%;box-sizing:border-box;padding:7px 8px;border:1px solid rgba(0,0,0,.08);border-radius:6px;font-size:10px;background:#fff;margin-bottom:8px;">'
    +'<button id="__sa_sj_go" class="img-gen-btn" style="width:100%;background:linear-gradient(135deg,#7c3aed,#ec4899);font-size:12px;padding:10px;">🔮 사주 분석하기</button>'
    +'<div id="__sa_sj_result" style="margin-top:10px;"></div>';
  P.appendChild(wrap);
  document.getElementById('__sa_sj_go').onclick=function(){
    var bd=document.getElementById('__sa_sj_date').value.trim();
    var bt=document.getElementById('__sa_sj_time').value.trim()||'1200';
    var cal=document.getElementById('__sa_sj_cal').value;
    var gen=document.getElementById('__sa_sj_gen').value;
    var mode=document.getElementById('__sa_sj_mode').value;
    var concern=document.getElementById('__sa_sj_concern').value.trim();
    if(bd.length!==8){document.getElementById('__sa_sj_result').innerHTML='<p style="color:#e11d48;font-size:11px;">❌ 생년월일 8자리를 정확히 입력하세요</p>';return;}
    _saFeature('saju_analyze');
    var res=document.getElementById('__sa_sj_result');
    var btn=document.getElementById('__sa_sj_go');
    btn.disabled=true;btn.innerHTML='🔮 분석 중...';
    res.innerHTML='<div style="text-align:center;padding:20px;"><div class="sd"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></div><div style="font-size:11px;color:#7c3aed;margin-top:8px;">사주팔자 계산 + AI 분석 중...</div></div>';
    var BASE=window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space';
    fetch(BASE+'/api/saju',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({birth_date:bd,birth_time:bt,calendar_type:cal,gender:gen,mode:mode,concern:concern}),mode:'cors'}).then(function(r){return r.json();}).then(function(d){
      btn.disabled=false;btn.innerHTML='🔮 사주 분석하기';
      if(!d.ok){res.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ '+(d.error||'분석 실패')+'</p>';return;}
      _renderSajuResult(d,res);
    }).catch(function(e){btn.disabled=false;btn.innerHTML='🔮 사주 분석하기';res.innerHTML='<p style="color:#e11d48;font-size:11px;">❌ '+e.message+'</p>';});
  };
}
function _renderSajuResult(d,el){
  var sj=d.saju;var ss=d.sipseong;var us=d.unseong;var em=d.emojis||{};
  var hj=d.hanja||{};
  var oh=d.ohaeng||sj['오행']||{};
  var oe=em.ohaeng||{};var se=em.sipseong||{};var ue=em.unseong||{};var sn=em.sipseong_short||{};
  var HGAN={'갑':'甲','을':'乙','병':'丙','정':'丁','무':'戊','기':'己','경':'庚','신':'辛','임':'壬','계':'癸'};
  var HJI={'자':'子','축':'丑','인':'寅','묘':'卯','진':'辰','사':'巳','오':'午','미':'未','신':'申','유':'酉','술':'戌','해':'亥'};
  var HOH={'목':'木','화':'火','토':'土','금':'金','수':'水'};
  function hg(c){return HGAN[c]||c;}
  function hji(c){return HJI[c]||c;}
  var _tab=0;
  function render(){
    var tabs='<div style="display:flex;border-bottom:1px solid rgba(0,0,0,.06);margin-bottom:8px;">';
    ['🎴 사주표','⭐ 십성·운성','🤖 AI분석'].forEach(function(t,i){
      tabs+='<div class="sj-tab" data-ti="'+i+'" style="flex:1;text-align:center;padding:6px 0;font-size:10px;font-weight:'+(i===_tab?'700':'500')+';color:'+(i===_tab?'#7c3aed':C.sub)+';border-bottom:'+(i===_tab?'2px solid #7c3aed':'none')+';cursor:pointer;">'+t+'</div>';
    });
    tabs+='</div>';
    var body='';
    if(_tab===0){
      body+='<div style="background:linear-gradient(135deg,rgba(147,51,234,.04),rgba(236,72,153,.04));border-radius:10px;padding:10px;border:1px solid rgba(147,51,234,.08);">';
      body+='<div style="text-align:center;font-size:9px;color:#888;margin-bottom:6px;">'+d.birth.year+'년 '+d.birth.month+'월 '+d.birth.day+'일 '+d.birth.hour+'시'+d.birth.minute+'분 ('+d.birth.gender+') · '+d.mode+'</div>';
      body+='<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:4px;text-align:center;">';
      ['시주','일주','월주','년주'].forEach(function(p){
        var v=sj[p]||'??';var g=v[0]||'?';var j=v[1]||'?';
        var gh=hg(g);var jh=hji(j);
        body+='<div style="background:#fff;border-radius:8px;padding:6px 2px;border:1px solid rgba(0,0,0,.04);'+(p==='일주'?'border-color:#7c3aed;box-shadow:0 0 6px rgba(124,58,237,.15);':'')+'">'
          +'<div style="font-size:8px;color:#888;">'+p+(p==='일주'?' ⭐':'')+'</div>'
          +'<div style="font-size:22px;font-weight:800;margin:3px 0;font-family:serif;">'+gh+'</div>'
          +'<div style="font-size:7px;color:#bbb;">'+g+'</div>'
          +'<div style="font-size:7px;color:#aaa;">─────</div>'
          +'<div style="font-size:22px;font-weight:800;margin:3px 0;font-family:serif;">'+jh+'</div>'
          +'<div style="font-size:7px;color:#bbb;">'+j+'</div>'
          +'<div style="font-size:8px;color:#7c3aed;font-weight:600;">'+gh+jh+'</div>'
          +'</div>';
      });
      body+='</div>';
      body+='<div style="margin-top:8px;background:#fff;border-radius:8px;padding:8px;border:1px solid rgba(0,0,0,.04);">';
      body+='<div style="font-size:9px;font-weight:700;color:#333;margin-bottom:4px;">⚖️ 오행(五行) 분포</div>';
      var ohMax=Math.max.apply(null,Object.values(oh))||1;
      ['목','화','토','금','수'].forEach(function(k){
        var v=oh[k]||0;var pct=Math.round(v/8*100);
        var colors={'목':'#22c55e','화':'#ef4444','토':'#a3844e','금':'#9ca3af','수':'#3b82f6'};
        body+='<div style="display:flex;align-items:center;gap:4px;margin-bottom:2px;"><span style="font-size:9px;width:36px;">'+(oe[k]||'')+HOH[k]+'('+k+')</span><div style="flex:1;height:6px;background:rgba(0,0,0,.04);border-radius:3px;"><div style="height:100%;width:'+pct+'%;background:'+colors[k]+';border-radius:3px;"></div></div><span style="font-size:8px;color:#666;width:14px;text-align:right;">'+v+'</span></div>';
      });
      body+='</div></div>';
    }else if(_tab===1){
      body+='<div style="background:#fff;border-radius:8px;padding:8px;border:1px solid rgba(0,0,0,.04);margin-bottom:6px;">';
      body+='<div style="font-size:9px;font-weight:700;color:#7c3aed;margin-bottom:4px;">🌟 천간 십성</div>';
      ['년간','월간','시간'].forEach(function(k){
        var v=ss[k]||'';body+='<div style="display:flex;align-items:center;gap:4px;margin-bottom:2px;font-size:9px;"><span style="width:30px;color:#888;">'+k+'</span><span>'+(se[v]||'')+' <b>'+v+'</b></span><span style="color:#666;font-size:8px;">('+(sn[v]||'')+')</span></div>';
      });
      body+='</div>';
      body+='<div style="background:#fff;border-radius:8px;padding:8px;border:1px solid rgba(0,0,0,.04);margin-bottom:6px;">';
      body+='<div style="font-size:9px;font-weight:700;color:#7c3aed;margin-bottom:4px;">🌟 지지 십성 (장간 기준)</div>';
      ['년지','월지','일지','시지'].forEach(function(k){
        var v=ss[k]||'';body+='<div style="display:flex;align-items:center;gap:4px;margin-bottom:2px;font-size:9px;"><span style="width:30px;color:#888;">'+k+'</span><span>'+(se[v]||'')+' <b>'+v+'</b></span><span style="color:#666;font-size:8px;">('+(sn[v]||'')+')</span></div>';
      });
      body+='</div>';
      body+='<div style="background:#fff;border-radius:8px;padding:8px;border:1px solid rgba(0,0,0,.04);">';
      body+='<div style="font-size:9px;font-weight:700;color:#7c3aed;margin-bottom:4px;">🌀 12운성</div>';
      ['년주','월주','일주','시주'].forEach(function(k){
        var v=us[k]||'';body+='<div style="display:flex;align-items:center;gap:4px;margin-bottom:2px;font-size:9px;"><span style="width:30px;color:#888;">'+k+'</span><span>'+(ue[v]||'')+' <b>'+v+'</b></span></div>';
      });
      body+='</div>';
    }else{
      var ai=d.ai_analysis||'분석 결과 없음';
      body+='<div style="font-size:10px;line-height:1.7;color:#333;white-space:pre-wrap;">'+toHTML(ai)+'</div>';
    }
    el.innerHTML=tabs+body;
    el.querySelectorAll('.sj-tab').forEach(function(t){
      t.onclick=function(){_tab=parseInt(this.getAttribute('data-ti'));render();};
    });
  }
  render();
}
/* ═══ 클립 (HF Bucket 저장) ═══ */
function renderClips(){
  _viewMode='clips';P.innerHTML='';
  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','📌 클립'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','×');
  back.onclick=function(){_viewMode='main';renderMain();};
  hdr.appendChild(back);P.appendChild(hdr);
  var wrap=h('div','padding:12px;overflow-y:auto;flex:1;');
  var BASE=window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space';
  var email=window.__SA_USER_EMAIL||'';
  wrap.innerHTML='<div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:10px;">'
    +'<button id="__sa_clip_url" class="img-gen-btn" style="flex:1;min-width:100px;font-size:11px;padding:8px;">📌 현재 페이지 저장</button>'
    +'<button id="__sa_clip_text" class="img-gen-btn" style="flex:1;min-width:100px;font-size:11px;padding:8px;background:linear-gradient(135deg,#0d9488,#059669);">📝 선택 텍스트 저장</button>'
    +'<button id="__sa_clip_img" class="img-gen-btn" style="flex:1;min-width:100px;font-size:11px;padding:8px;background:linear-gradient(135deg,#f59e0b,#d97706);">🖼️ 캡처 저장</button></div>'
    +'<div id="__sa_clip_memo_wrap" style="display:none;margin-bottom:10px;"><textarea id="__sa_clip_memo" class="img-gen-input" style="min-height:40px;" placeholder="메모 (선택사항)"></textarea>'
    +'<button id="__sa_clip_confirm" class="img-gen-btn" style="margin-top:4px;font-size:11px;">💾 저장 확인</button></div>'
    +'<div id="__sa_clip_status" style="margin-bottom:8px;"></div>'
    +'<div style="border-top:1px solid rgba(0,0,0,.04);padding-top:8px;"><div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">'
    +'<span style="font-size:11px;font-weight:700;color:'+C.text+';">📂 내 클립</span>'
    +'<button id="__sa_clip_refresh" style="border:none;background:none;font-size:11px;color:'+C.accent+';cursor:pointer;font-weight:600;">🔄 새로고침</button></div>'
    +'<div id="__sa_clip_list"><div style="text-align:center;padding:16px;color:'+C.sub+';font-size:11px;">불러오는 중...</div></div></div>';
  P.appendChild(wrap);
  var _pendingClip=null;
  function showStatus(msg,color){var el=document.getElementById('__sa_clip_status');if(el)el.innerHTML='<div style="padding:6px 10px;border-radius:6px;font-size:10px;font-weight:600;background:rgba('+(color==='green'?'34,197,94':'239,68,68')+',.08);color:'+(color==='green'?'#16a34a':'#e11d48')+';">'+msg+'</div>';}
  function saveClip(data){
    if(!email){showStatus('❌ 이메일 연동이 필요합니다 (팝업에서 설정)','red');return;}
    var st=document.getElementById('__sa_clip_status');
    if(st)st.innerHTML='<div style="padding:6px;font-size:10px;color:'+C.accent+';">💾 저장 중...</div>';
    fetch(BASE+'/api/clips/save',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(Object.assign({email:email},data)),mode:'cors'}).then(function(r){return r.json();}).then(function(d){
      if(d.ok){var uMB=d.used_bytes?Math.round(d.used_bytes/1024/1024*10)/10:0;var lMB=d.limit_bytes?d.limit_bytes/1024/1024:1024;showStatus('✅ 저장 완료! ('+uMB+'MB / '+lMB+'MB)','green');loadClipList();document.getElementById('__sa_clip_memo_wrap').style.display='none';}
      else showStatus('❌ '+(d.error||'저장 실패'),'red');
    }).catch(function(e){showStatus('❌ '+e.message,'red');});
  }
  document.getElementById('__sa_clip_url').onclick=function(){
    _saFeature('clip_url');
    _pendingClip={type:'url',url:location.href,title:document.title};
    document.getElementById('__sa_clip_memo_wrap').style.display='block';
    document.getElementById('__sa_clip_memo').focus();
  };
  document.getElementById('__sa_clip_text').onclick=function(){
    _saFeature('clip_text');
    var sel=window.getSelection().toString().trim();
    if(!sel){showStatus('⚠️ 먼저 페이지에서 텍스트를 드래그 선택하세요','red');return;}
    _pendingClip={type:'text',url:location.href,title:document.title,text:sel};
    document.getElementById('__sa_clip_memo_wrap').style.display='block';
    document.getElementById('__sa_clip_memo').value='';
    showStatus('📝 선택된 텍스트: "'+sel.substring(0,50)+(sel.length>50?'...':'')+'"','green');
  };
  document.getElementById('__sa_clip_img').onclick=function(){
    _saFeature('clip_image');
    navigator.mediaDevices.getDisplayMedia({video:true}).then(function(stream){
      var track=stream.getVideoTracks()[0];
      var imgCap=new ImageCapture(track);
      return imgCap.grabFrame().then(function(bitmap){
        track.stop();stream.getTracks().forEach(function(t){t.stop();});
        var cvs=document.createElement('canvas');cvs.width=bitmap.width;cvs.height=bitmap.height;
        cvs.getContext('2d').drawImage(bitmap,0,0);
        return cvs.toDataURL('image/png');
      });
    }).then(function(dataUrl){
      _pendingClip={type:'image',url:location.href,title:document.title,image:dataUrl};
      document.getElementById('__sa_clip_memo_wrap').style.display='block';
      showStatus('🖼️ 캡처 완료 — 메모 입력 후 저장','green');
    }).catch(function(e){
      if(e.name!=='NotAllowedError') showStatus('❌ '+e.message,'red');
    });
  };
  document.getElementById('__sa_clip_confirm').onclick=function(){
    if(!_pendingClip){showStatus('⚠️ 먼저 저장할 항목을 선택하세요','red');return;}
    _pendingClip.memo=(document.getElementById('__sa_clip_memo').value||'').trim();
    saveClip(_pendingClip);
    _pendingClip=null;
  };
  document.getElementById('__sa_clip_refresh').onclick=function(){loadClipList();};
  function _clipDetail(c){
    var wrap=document.getElementById('__sa_clip_list');if(!wrap)return;
    var icon=c.type==='url'?'🔗':c.type==='text'?'📝':'🖼️';
    var time=c.ts?new Date(c.ts*1000).toLocaleString('ko-KR'):'';
    var html='<div style="margin-bottom:8px;"><button id="__sa_clip_back" style="border:none;background:none;font-size:11px;color:'+C.accent+';cursor:pointer;font-weight:600;">← 목록으로</button></div>';
    html+='<div style="padding:10px;border:1px solid rgba(88,86,214,.1);border-radius:10px;background:rgba(88,86,214,.02);">';
    html+='<div style="font-size:13px;font-weight:700;margin-bottom:6px;">'+icon+' '+(c.title||'제목 없음')+'</div>';
    if(c.url)html+='<div style="margin-bottom:6px;"><a href="'+c.url+'" target="_blank" style="font-size:10px;color:'+C.accent+';word-break:break-all;">'+c.url+'</a></div>';
    if(c.text)html+='<div style="background:#fff;border:1px solid rgba(0,0,0,.06);border-radius:6px;padding:8px;margin-bottom:6px;font-size:11px;line-height:1.6;white-space:pre-wrap;max-height:200px;overflow-y:auto;">'+c.text.replace(/</g,'&lt;')+'</div>';
    if(c.memo)html+='<div style="font-size:10px;color:#666;margin-bottom:6px;">💬 '+c.memo.replace(/</g,'&lt;')+'</div>';
    if(c.image_url)html+='<img src="'+BASE+c.image_url+'" style="max-width:100%;border-radius:6px;margin-bottom:6px;cursor:pointer;" onclick="window.open(this.src)">';
    html+='<div style="font-size:8px;color:#aaa;margin-bottom:8px;">🕐 '+time+'</div>';
    html+='<div style="display:flex;gap:4px;flex-wrap:wrap;">';
    if(c.url)html+='<button class="img-dl-btn" style="font-size:9px;padding:4px 8px;" onclick="window.open(\''+c.url+'\')">🔗 열기</button>';
    if(c.text)html+='<button class="img-dl-btn" style="font-size:9px;padding:4px 8px;background:#0d9488;" id="__sa_clip_cptxt">📋 텍스트 복사</button>';
    if(c.image_url)html+='<a class="img-dl-btn" style="font-size:9px;padding:4px 8px;background:#f59e0b;text-decoration:none;" href="'+BASE+c.image_url+'" download="clip_image.png">💾 이미지 저장</a>';
    html+='</div></div>';
    wrap.innerHTML=html;
    document.getElementById('__sa_clip_back').onclick=function(){loadClipList();};
    var cpBtn=document.getElementById('__sa_clip_cptxt');
    if(cpBtn) cpBtn.onclick=function(){navigator.clipboard.writeText(c.text||'').then(function(){cpBtn.innerHTML='✅ 복사됨';setTimeout(function(){cpBtn.innerHTML='📋 텍스트 복사';},1500);});};
  }
  function loadClipList(){
    var list=document.getElementById('__sa_clip_list');
    if(!email){list.innerHTML='<div style="text-align:center;padding:12px;color:'+C.sub+';font-size:10px;">이메일 연동 후 이용 가능</div>';return;}
    list.innerHTML='<div style="text-align:center;padding:12px;color:'+C.sub+';font-size:10px;">불러오는 중...</div>';
    fetch(BASE+'/api/clips/list?email='+encodeURIComponent(email),{mode:'cors'}).then(function(r){return r.json();}).then(function(d){
      if(!d.ok){list.innerHTML='<div style="text-align:center;padding:12px;color:#e11d48;font-size:10px;">❌ '+(d.error||'오류')+'</div>';return;}
      var usedMB=d.used_mb||0;var limitMB=d.limit_mb||1024;var pct=limitMB?Math.min(100,Math.round(usedMB/limitMB*100)):0;
      var barColor=pct>80?'#ef4444':pct>50?'#f59e0b':'#5856D6';
      var storageHtml='<div style="margin-bottom:8px;padding:6px 8px;background:rgba(0,0,0,.02);border-radius:6px;font-size:9px;">'
        +'<div style="display:flex;justify-content:space-between;margin-bottom:3px;"><span>💾 사용량</span><b style="color:'+barColor+';">'+usedMB+'MB</b> / '+limitMB+'MB ('+pct+'%)</div>'
        +'<div style="height:4px;background:rgba(0,0,0,.06);border-radius:2px;"><div style="height:100%;width:'+pct+'%;background:'+barColor+';border-radius:2px;transition:width .3s;"></div></div></div>';
      if(!d.clips||d.clips.length===0){list.innerHTML=storageHtml+'<div style="text-align:center;padding:12px;color:'+C.sub+';font-size:10px;">저장된 클립이 없습니다</div>';return;}
      var exportHtml='<div style="text-align:right;margin-bottom:6px;"><a href="'+BASE+'/api/clips/export?email='+encodeURIComponent(email)+'&fmt=csv" target="_blank" style="font-size:9px;color:'+C.accent+';text-decoration:none;font-weight:600;">📤 CSV 내보내기</a></div>';
      var html='';
      var _clips=d.clips;
      _clips.forEach(function(c,ci){
        var icon=c.type==='url'?'🔗':c.type==='text'?'📝':'🖼️';
        var time=c.ts?new Date(c.ts*1000).toLocaleString('ko-KR',{month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit'}):'';
        html+='<div class="sa-clip-item" data-ci="'+ci+'" style="padding:8px;border:1px solid rgba(0,0,0,.04);border-radius:8px;margin-bottom:6px;font-size:10px;background:rgba(0,0,0,.01);cursor:pointer;transition:background .15s;">'
          +'<div style="display:flex;justify-content:space-between;align-items:flex-start;">'
          +'<div style="flex:1;min-width:0;">'
          +'<div style="font-weight:700;margin-bottom:2px;">'+icon+' '+(c.title||c.url||'(제목 없음)').substring(0,40)+'</div>';
        if(c.text)html+='<div style="color:#555;font-size:9px;margin-bottom:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:200px;">"'+c.text.substring(0,50)+(c.text.length>50?'...':'')+'"</div>';
        if(c.url&&c.type==='url')html+='<div style="color:'+C.accent+';font-size:8px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">'+c.url.substring(0,45)+'</div>';
        if(c.memo)html+='<div style="color:#888;font-size:8px;margin-top:1px;">💬 '+c.memo.substring(0,30)+'</div>';
        if(c.image_url)html+='<div style="font-size:8px;color:#0d9488;margin-top:1px;">🖼️ 이미지 포함</div>';
        html+='</div><div style="flex-shrink:0;display:flex;flex-direction:column;align-items:flex-end;gap:2px;">'
          +'<span style="font-size:8px;color:#aaa;">'+time+'</span>'
          +'<button class="sa-clip-del" data-cid="'+c.id+'" style="border:none;background:rgba(239,68,68,.08);color:#e11d48;font-size:8px;padding:2px 6px;border-radius:4px;cursor:pointer;">🗑</button>'
          +'</div></div></div>';
      });
      list.innerHTML=storageHtml+exportHtml+html;
      list.querySelectorAll('.sa-clip-item').forEach(function(el){
        el.onmouseenter=function(){this.style.background='rgba(88,86,214,.04)';};
        el.onmouseleave=function(){this.style.background='rgba(0,0,0,.01)';};
        el.onclick=function(e){
          if(e.target.classList.contains('sa-clip-del'))return;
          var ci=parseInt(this.getAttribute('data-ci'));
          if(_clips[ci]) _clipDetail(_clips[ci]);
        };
      });
      list.querySelectorAll('.sa-clip-del').forEach(function(btn){
        btn.onclick=function(e){
          e.stopPropagation();
          var cid=this.getAttribute('data-cid');
          this.textContent='...';
          fetch(BASE+'/api/clips/delete',{method:'DELETE',headers:{'Content-Type':'application/json'},body:JSON.stringify({email:email,clip_id:cid}),mode:'cors'}).then(function(){loadClipList();});
        };
      });
    }).catch(function(e){list.innerHTML='<div style="text-align:center;padding:12px;color:#e11d48;font-size:10px;">❌ '+e.message+'</div>';});
  }
  loadClipList();
}
function renderAITools(){
  _viewMode='aitools';P.innerHTML='';

  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','🤖 AI 도구'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','×');
  back.onclick=function(){_viewMode='main';renderMain();};
  hdr.appendChild(back);P.appendChild(hdr);

  var wrap=h('div','padding:12px;overflow-y:auto;flex:1;');

  /* 설명글 */
  var desc=document.createElement('div');
  desc.style.cssText='padding:10px 12px;background:linear-gradient(135deg,rgba(88,86,214,.06),rgba(13,148,136,.04));border-radius:10px;margin-bottom:12px;font-size:11px;color:#444;line-height:1.6;border:1px solid rgba(88,86,214,.08);';
  desc.innerHTML='✨ <b>나노바나나, 클링, 그록</b> 등 최고의 생성 AI 도구를 <b style="color:#5856D6;">무료로 체험</b>해 볼 수 있습니다. 생성된 모든 이미지에는 <b>Ginigen.AI</b> 워터마크가 자동 삽입됩니다.';
  wrap.appendChild(desc);

  /* 이미지 생성 카드 */
  var card1=document.createElement('div');card1.className='ait-card';
  card1.innerHTML='<div class="ait-icon">🎨</div><div class="ait-name">이미지 생성 (Text → Image)</div><div class="ait-desc">Grok Imagine · 텍스트로 고품질 이미지 생성</div>';
  card1.onclick=function(){renderImageGen();};
  wrap.appendChild(card1);

  /* 이미지 편집 카드 */
  var card2=document.createElement('div');card2.className='ait-card';
  card2.innerHTML='<div class="ait-icon">🖌️</div><div class="ait-name">이미지 편집 (Image → Image)</div><div class="ait-desc">Grok Imagine Edit · 이미지 업로드 + 텍스트로 편집</div>';
  card2.onclick=function(){renderImageEdit();};
  wrap.appendChild(card2);

  /* Coming Soon */
  var csItems=[
    {icon:'📝',name:'텍스트 → 비디오 (Text → Video)',desc:'Coming Soon · 텍스트로 영상 생성'},
    {icon:'🎬',name:'이미지 → 비디오 (Image → Video)',desc:'Coming Soon · 이미지를 영상으로 변환'}
  ];
  csItems.forEach(function(item){
    var cs=document.createElement('div');cs.className='ait-card';cs.style.opacity='0.4';cs.style.cursor='default';
    cs.innerHTML='<div class="ait-icon">'+item.icon+'</div><div class="ait-name">'+item.name+'</div><div class="ait-desc">'+item.desc+'</div>';
    wrap.appendChild(cs);
  });

  P.appendChild(wrap);
}

/* ── 🎨 이미지 생성 뷰 ── */
function renderImageGen(){
  _viewMode='imagegen';P.innerHTML='';

  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','🎨 이미지 생성'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','←');
  back.onclick=function(){renderAITools();};
  hdr.appendChild(back);P.appendChild(hdr);

  var wrap=h('div','padding:12px;overflow-y:auto;flex:1;');

  var defaultPrompt="아름다운 20대 한국 여성이 비키니 수영복을 입고 환하게 웃으면서 표지판을 들고 있다. 표지판에는 '여기 완전 핫해'라고 적혀 있다, 그녀는 커다란 워터슬라이드를 타면서 내려오며 앉아 있다.";

  wrap.innerHTML='<div style="margin-bottom:10px;">'
    +'<label style="font-size:10px;color:#8e8e93;font-weight:600;display:block;margin-bottom:4px;">프롬프트 (이미지 설명)</label>'
    +'<textarea id="__sa_img_prompt" class="img-gen-input" placeholder="생성할 이미지를 설명하세요...">'+defaultPrompt+'</textarea></div>'
    +'<button id="__sa_img_gen" class="img-gen-btn" style="margin-top:8px;">🎨 이미지 생성 (1:1)</button>'
    +'<div id="__sa_img_result" style="margin-top:10px;"></div>'
    +'<div style="margin-top:10px;padding:8px;background:rgba(0,0,0,.02);border-radius:8px;font-size:9px;color:#8e8e93;line-height:1.5;">'
    +'Powered by Grok Imagine (xai) · Ginigen.AI 워터마크 자동 삽입 · 생성 시간 10~30초</div>';

  P.appendChild(wrap);

  /* 이벤트 */
  document.getElementById('__sa_img_gen').onclick=function(){
    var prompt=document.getElementById('__sa_img_prompt').value.trim();
    if(!prompt){alert('프롬프트를 입력하세요');return;}
    var ratio='1:1';
    var num=1;
    var btn=this;var result=document.getElementById('__sa_img_result');

    btn.disabled=true;btn.innerHTML='<span class="sd" style="display:inline-flex;margin-right:6px;"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></span> 생성 중... (10~30초)';
    result.innerHTML='';

    var BASE=window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space';
    var _ue=window.__SA_USER_EMAIL||'';
    var _t0_img=Date.now();
    fetch(BASE+'/api/imagine',{
      method:'POST',headers:{'Content-Type':'application/json'},
      body:JSON.stringify({prompt:prompt,aspect_ratio:ratio,num_images:num,sa_email:_ue,sa_url:location.href||''}),
      mode:'cors'
    }).then(function(r){
      if(!r.ok)return r.text().then(function(t){throw new Error('HTTP '+r.status+': '+t.substring(0,100));});
      return r.text().then(function(t){try{return JSON.parse(t);}catch(e){throw new Error('파싱 실패');}});
    }).then(function(d){
      _saAiDone('imagine',_t0_img,!d.error,{feature:'image_gen'});
      if(d.error){
        result.innerHTML='<p style="color:#e11d48;font-size:12px;">❌ '+esc(d.error)+'</p>';
        return;
      }
      var imgs=d.images||[];
      result.innerHTML='';
      var hasImg=false;
      imgs.forEach(function(img,i){
        if(img.error){
          var ep=document.createElement('p');ep.style.cssText='color:#e11d48;font-size:11px;';ep.textContent='❌ 이미지 '+(i+1)+': '+img.error;
          result.appendChild(ep);return;
        }
        var src=img.data_uri||img.url||'';
        if(!src)return;
        hasImg=true;
        var card=document.createElement('div');card.style.cssText='margin-bottom:10px;';
        var im=document.createElement('img');im.src=src;im.className='img-result';im.alt='Generated '+(i+1);
        card.appendChild(im);
        var btns=document.createElement('div');btns.style.cssText='display:flex;gap:6px;margin-top:6px;';
        /* 다운로드 버튼 */
        var dlBtn=document.createElement('a');dlBtn.className='img-dl-btn';dlBtn.innerHTML='💾 다운로드';
        dlBtn.download='ginigen_ai_'+(i+1)+'.jpg';dlBtn.href=src;
        btns.appendChild(dlBtn);
        /* 복사 버튼 */
        var cpBtn=document.createElement('button');cpBtn.className='img-dl-btn';cpBtn.style.background='#0d9488';cpBtn.innerHTML='📋 복사';
        cpBtn.onclick=function(){
          if(src.startsWith('data:')){
            /* data URI → blob → clipboard */
            fetch(src).then(function(r){return r.blob();}).then(function(bl){
              try{navigator.clipboard.write([new ClipboardItem({'image/jpeg':bl})]);cpBtn.innerHTML='✅ 복사됨';}catch(e){cpBtn.innerHTML='⚠️ 미지원';}
              setTimeout(function(){cpBtn.innerHTML='📋 복사';},1500);
            });
          }else{
            navigator.clipboard.writeText(src).then(function(){cpBtn.innerHTML='✅ 복사됨';setTimeout(function(){cpBtn.innerHTML='📋 복사';},1500);});
          }
        };
        btns.appendChild(cpBtn);
        card.appendChild(btns);
        result.appendChild(card);
      });
      if(!hasImg){var np=document.createElement('p');np.style.cssText='color:#8e8e93;font-size:11px;';np.textContent='이미지가 생성되지 않았습니다.';result.appendChild(np);}
    }).catch(function(e){
      result.innerHTML='<p style="color:#e11d48;font-size:12px;">❌ '+esc(e.message)+'</p>';
    }).finally(function(){
      btn.disabled=false;btn.innerHTML='🎨 이미지 생성';
    });
  };

  /* textarea 키보드 이벤트 차단 */
  var ta=document.getElementById('__sa_img_prompt');
  if(ta){
    ta.addEventListener('keydown',function(e){e.stopPropagation();e.stopImmediatePropagation();},{capture:true});
    ta.addEventListener('keypress',function(e){e.stopPropagation();e.stopImmediatePropagation();},{capture:true});
  }
}

/* ── 🖌️ 이미지 편집 뷰 ── */
function renderImageEdit(){
  _viewMode='imageedit';P.innerHTML='';

  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','🖌️ 이미지 편집'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','←');
  back.onclick=function(){renderAITools();};
  hdr.appendChild(back);P.appendChild(hdr);

  var wrap=h('div','padding:12px;overflow-y:auto;flex:1;');

  wrap.innerHTML='<div style="margin-bottom:10px;">'
    +'<label style="font-size:10px;color:#8e8e93;font-weight:600;display:block;margin-bottom:4px;">원본 이미지 (1장)</label>'
    +'<div id="__sa_edit_preview" style="width:100%;min-height:100px;border:2px dashed rgba(0,0,0,.1);border-radius:10px;display:flex;align-items:center;justify-content:center;cursor:pointer;overflow:hidden;position:relative;" onclick="document.getElementById(\'__sa_edit_file\').click();">'
    +'<span style="font-size:12px;color:#8e8e93;">📷 클릭하여 이미지 선택</span></div>'
    +'<input type="file" id="__sa_edit_file" accept="image/*" style="display:none;" /></div>'
    +'<div style="margin-bottom:10px;">'
    +'<label style="font-size:10px;color:#8e8e93;font-weight:600;display:block;margin-bottom:4px;">편집 지시 (프롬프트)</label>'
    +'<textarea id="__sa_edit_prompt" class="img-gen-input" placeholder="어떻게 편집할지 설명하세요...\n예: 배경을 우주로 바꿔줘, 더 밝게 만들어줘, 애니메이션 스타일로 바꿔줘">배경을 환상적인 석양이 지는 해변으로 바꾸고, 전체적으로 따뜻한 톤으로 만들어줘.</textarea></div>'
    +'<button id="__sa_edit_gen" class="img-gen-btn" style="margin-top:4px;" disabled>🖌️ 이미지 편집</button>'
    +'<div id="__sa_edit_result" style="margin-top:10px;"></div>'
    +'<div style="margin-top:10px;padding:8px;background:rgba(0,0,0,.02);border-radius:8px;font-size:9px;color:#8e8e93;line-height:1.5;">'
    +'Powered by Grok Imagine Edit (xai) · Ginigen.AI 워터마크 자동 삽입 · 편집 시간 10~30초</div>';

  P.appendChild(wrap);

  var _editDataUri='';

  /* 파일 선택 이벤트 */
  document.getElementById('__sa_edit_file').onchange=function(ev){
    var file=ev.target.files[0];if(!file)return;
    if(!file.type.startsWith('image/')){alert('이미지 파일만 가능합니다');return;}
    if(file.size>10*1024*1024){alert('10MB 이하 이미지만 가능합니다');return;}
    var reader=new FileReader();
    reader.onload=function(e){
      /* Canvas로 압축 (최대 1024px, JPEG 85%) — 대용량 방지 */
      var img=new Image();
      img.onload=function(){
        var maxSz=1024;
        var w=img.width,ht=img.height;
        if(w>maxSz||ht>maxSz){
          if(w>ht){ht=Math.round(ht*(maxSz/w));w=maxSz;}
          else{w=Math.round(w*(maxSz/ht));ht=maxSz;}
        }
        var cv=document.createElement('canvas');cv.width=w;cv.height=ht;
        var ctx=cv.getContext('2d');ctx.drawImage(img,0,0,w,ht);
        _editDataUri=cv.toDataURL('image/jpeg',0.85);
        console.log('[SA-EDIT] compressed:',Math.round(_editDataUri.length/1024)+'KB');
        var preview=document.getElementById('__sa_edit_preview');
        if(preview){
          preview.innerHTML='<img src="'+_editDataUri+'" style="width:100%;border-radius:8px;" />';
          preview.style.border='1px solid rgba(88,86,214,.15)';
        }
        var btn=document.getElementById('__sa_edit_gen');if(btn)btn.disabled=false;
      };
      img.src=e.target.result;
    };
    reader.readAsDataURL(file);
  };

  /* 이미지 미리보기 클릭 → 파일 선택 (이벤트 위임) */
  document.getElementById('__sa_edit_preview').onclick=function(){
    document.getElementById('__sa_edit_file').click();
  };

  /* 편집 실행 */
  document.getElementById('__sa_edit_gen').onclick=function(){
    var prompt=document.getElementById('__sa_edit_prompt').value.trim();
    if(!prompt){alert('편집 지시를 입력하세요');return;}
    if(!_editDataUri){alert('이미지를 먼저 선택하세요');return;}
    var btn=this;var result=document.getElementById('__sa_edit_result');

    btn.disabled=true;btn.innerHTML='<span class="sd" style="display:inline-flex;margin-right:6px;"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></span> 편집 중... (10~30초)';
    result.innerHTML='';

    var BASE=window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space';
    var _t0_edit=Date.now();
    fetch(BASE+'/api/imagine-edit',{
      method:'POST',headers:{'Content-Type':'application/json'},
      body:JSON.stringify({prompt:prompt,image_url:_editDataUri,sa_email:window.__SA_USER_EMAIL||'',sa_url:location.href||''}),
      mode:'cors'
    }).then(function(r){
      if(!r.ok)return r.text().then(function(t){throw new Error('HTTP '+r.status+': '+t.substring(0,100));});
      return r.text().then(function(t){try{return JSON.parse(t);}catch(e){throw new Error('파싱 실패');}});
    }).then(function(d){
      _saAiDone('imagine_edit',_t0_edit,!d.error,{feature:'image_edit'});
      if(d.error){
        result.innerHTML='<p style="color:#e11d48;font-size:12px;">❌ '+esc(d.error)+'</p>';
        return;
      }
      var imgs=d.images||[];
      result.innerHTML='';
      imgs.forEach(function(img,i){
        if(img.error){
          var ep=document.createElement('p');ep.style.cssText='color:#e11d48;font-size:11px;';ep.textContent='❌ '+img.error;
          result.appendChild(ep);return;
        }
        var src=img.data_uri||img.url||'';if(!src)return;
        var card=document.createElement('div');card.style.cssText='margin-bottom:10px;';
        var im=document.createElement('img');im.src=src;im.className='img-result';im.alt='Edited';
        card.appendChild(im);
        var btns=document.createElement('div');btns.style.cssText='display:flex;gap:6px;margin-top:6px;';
        var dlBtn=document.createElement('a');dlBtn.className='img-dl-btn';dlBtn.innerHTML='💾 다운로드';
        dlBtn.download='ginigen_ai_edit.jpg';dlBtn.href=src;btns.appendChild(dlBtn);
        card.appendChild(btns);
        result.appendChild(card);
      });
      if(!imgs.length||(!imgs[0].data_uri&&!imgs[0].url)){
        var np=document.createElement('p');np.style.cssText='color:#8e8e93;font-size:11px;';np.textContent='편집된 이미지가 없습니다.';result.appendChild(np);
      }
    }).catch(function(e){
      result.innerHTML='<p style="color:#e11d48;font-size:12px;">❌ '+esc(e.message)+'</p>';
    }).finally(function(){
      btn.disabled=false;btn.innerHTML='🖌️ 이미지 편집';
    });
  };

  /* textarea 키보드 이벤트 차단 */
  var ta=document.getElementById('__sa_edit_prompt');
  if(ta){
    ta.addEventListener('keydown',function(e){e.stopPropagation();e.stopImmediatePropagation();},{capture:true});
    ta.addEventListener('keypress',function(e){e.stopPropagation();e.stopImmediatePropagation();},{capture:true});
  }
}

/* ── ⏱ 뽀모도로 타이머 ── */
function renderTimer(){
  _viewMode='timer';P.innerHTML='';

  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','⏱ 뽀모도로 타이머'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','×');
  back.onclick=function(){if(window._tmrInterval)clearInterval(window._tmrInterval);_viewMode='main';renderMain();};
  hdr.appendChild(back);P.appendChild(hdr);

  var wrap=h('div','padding:16px;overflow-y:auto;flex:1;text-align:center;');

  var totalSec=25*60;var remaining=totalSec;var running=false;var mode='focus';

  wrap.innerHTML='<div class="tmr-display" id="__sa_tmr_disp">25:00</div>'
    +'<div class="tmr-label" id="__sa_tmr_mode">🎯 집중 모드</div>'
    +'<div class="tmr-btns">'
    +'<button class="tmr-btn" id="__sa_tmr_start" style="background:linear-gradient(135deg,#5856D6,#4f46e5);color:#fff;">▶ 시작</button>'
    +'<button class="tmr-btn" id="__sa_tmr_reset" style="background:rgba(0,0,0,.05);color:#666;">↺ 리셋</button></div>'
    +'<div style="margin:10px 0 6px;font-size:9px;color:#8e8e93;font-weight:600;text-transform:uppercase;">⏱ 시간 직접 설정</div>'
    +'<div style="display:flex;align-items:center;gap:6px;justify-content:center;margin-bottom:10px;">'
    +'<input type="number" id="__sa_tmr_custom" min="1" max="180" value="25" style="width:60px;text-align:center;padding:6px;border:1px solid rgba(0,0,0,.08);border-radius:8px;font-size:14px;font-weight:700;outline:none;" />'
    +'<span style="font-size:12px;color:#666;">분</span>'
    +'<button class="tmr-p" id="__sa_tmr_apply" style="background:linear-gradient(135deg,#5856D6,#4f46e5);color:#fff;border:none;font-weight:700;">적용</button></div>'
    +'<div style="margin-bottom:6px;font-size:9px;color:#8e8e93;font-weight:600;text-transform:uppercase;">빠른 설정</div>'
    +'<div class="tmr-preset">'
    +'<button class="tmr-p" data-min="1" data-mode="focus">1분</button>'
    +'<button class="tmr-p" data-min="3" data-mode="focus">3분</button>'
    +'<button class="tmr-p" data-min="10" data-mode="focus">10분</button>'
    +'<button class="tmr-p" data-min="25" data-mode="focus">🎯 25분</button>'
    +'<button class="tmr-p" data-min="30" data-mode="focus">30분</button>'
    +'<button class="tmr-p" data-min="60" data-mode="focus">1시간</button>'
    +'<button class="tmr-p" data-min="5" data-mode="break">☕ 5분</button>'
    +'<button class="tmr-p" data-min="15" data-mode="break">☕ 15분</button></div>'
    +'<div style="margin-top:12px;padding:10px;background:rgba(88,86,214,.04);border-radius:10px;font-size:10px;color:#666;line-height:1.6;">'
    +'<b>뽀모도로 기법</b><br>• 25분 집중 → 5분 휴식 반복<br>• 4회 후 15분 긴 휴식<br>• 알림으로 시간 종료 알림</div>';
  P.appendChild(wrap);

  function fmt(s){var m=Math.floor(s/60);var ss=s%60;return (m<10?'0':'')+m+':'+(ss<10?'0':'')+ss;}
  function updateDisp(){
    var d=document.getElementById('__sa_tmr_disp');if(d)d.textContent=fmt(remaining);
  }

  document.getElementById('__sa_tmr_start').onclick=function(){
    if(running){
      running=false;clearInterval(window._tmrInterval);this.innerHTML='▶ 시작';this.style.background='linear-gradient(135deg,#5856D6,#4f46e5)';
    }else{
      running=true;this.innerHTML='⏸ 일시정지';this.style.background='linear-gradient(135deg,#d97706,#f59e0b)';
      window._tmrInterval=setInterval(function(){
        remaining--;updateDisp();
        if(remaining<=0){
          clearInterval(window._tmrInterval);running=false;
          var btn=document.getElementById('__sa_tmr_start');if(btn){btn.innerHTML='▶ 시작';btn.style.background='linear-gradient(135deg,#5856D6,#4f46e5)';}
          try{var audio=new Audio('data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQ==');audio.play();}catch(e){}
          try{if(Notification.permission==='granted')new Notification('⏱ 타이머 종료!',{body:mode==='focus'?'휴식 시간입니다 ☕':'다시 집중하세요 🎯'});}catch(e){}
          var ml=document.getElementById('__sa_tmr_mode');
          if(ml)ml.textContent=mode==='focus'?'✅ 집중 완료! 휴식하세요':'✅ 휴식 끝! 다시 집중!';
        }
      },1000);
      try{if(Notification.permission==='default')Notification.requestPermission();}catch(e){}
    }
  };

  document.getElementById('__sa_tmr_reset').onclick=function(){
    running=false;if(window._tmrInterval)clearInterval(window._tmrInterval);
    remaining=totalSec;updateDisp();
    var btn=document.getElementById('__sa_tmr_start');if(btn){btn.innerHTML='▶ 시작';btn.style.background='linear-gradient(135deg,#5856D6,#4f46e5)';}
    var ml=document.getElementById('__sa_tmr_mode');if(ml)ml.textContent=mode==='focus'?'🎯 집중 모드':'☕ 휴식 모드';
  };

  wrap.querySelectorAll('.tmr-p:not(#__sa_tmr_apply)').forEach(function(b){
    if(!b.dataset.min)return;
    b.onclick=function(){
      running=false;if(window._tmrInterval)clearInterval(window._tmrInterval);
      totalSec=parseInt(this.dataset.min)*60;remaining=totalSec;mode=this.dataset.mode||'focus';
      updateDisp();
      var ci=document.getElementById('__sa_tmr_custom');if(ci)ci.value=this.dataset.min;
      var btn=document.getElementById('__sa_tmr_start');if(btn){btn.innerHTML='▶ 시작';btn.style.background='linear-gradient(135deg,#5856D6,#4f46e5)';}
      var ml=document.getElementById('__sa_tmr_mode');if(ml)ml.textContent=mode==='focus'?'🎯 집중 모드':'☕ 휴식 모드';
    };
  });

  /* 커스텀 시간 적용 */
  var applyBtn=document.getElementById('__sa_tmr_apply');
  if(applyBtn) applyBtn.onclick=function(){
    var ci=document.getElementById('__sa_tmr_custom');
    var mins=parseInt((ci||{}).value)||25;
    if(mins<1)mins=1;if(mins>180)mins=180;
    running=false;if(window._tmrInterval)clearInterval(window._tmrInterval);
    totalSec=mins*60;remaining=totalSec;mode='focus';
    updateDisp();
    var btn=document.getElementById('__sa_tmr_start');if(btn){btn.innerHTML='▶ 시작';btn.style.background='linear-gradient(135deg,#5856D6,#4f46e5)';}
    var ml=document.getElementById('__sa_tmr_mode');if(ml)ml.textContent='🎯 '+mins+'분 집중 모드';
  };

  /* Enter키로 적용 */
  var ci=document.getElementById('__sa_tmr_custom');
  if(ci) ci.onkeydown=function(e){if(e.key==='Enter'){e.preventDefault();applyBtn.click();}};
}

/* ── 금융 대시보드 렌더 ── */
function renderFinance(){
  _viewMode='finance';P.innerHTML='';

  /* 헤더 */
  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','📊 실시간 금융'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','×');
  back.onclick=function(){_viewMode='main';renderMain();};
  hdr.appendChild(back);
  P.appendChild(hdr);

  /* 탭 */
  var tabs=h('div','');tabs.className='fin-tabs';
  var TAB_DATA=[
    {id:'overview',l:'종합'},
    {id:'forex',l:'환율'},
    {id:'crypto',l:'암호화폐'},
    {id:'calendar',l:'캘린더'},
    {id:'news',l:'뉴스'}
  ];
  var activeTab='overview';
  function renderTab(tabId){
    activeTab=tabId;
    Array.from(tabs.children).forEach(function(t){t.className='fin-tab'+(t.dataset.tab===tabId?' active':'');});
    renderWidgetArea(tabId);
  }
  TAB_DATA.forEach(function(td){
    var tb=h('button','','');tb.className='fin-tab'+(td.id==='overview'?' active':'');
    tb.textContent=td.l;tb.dataset.tab=td.id;
    tb.onclick=function(){renderTab(td.id);};
    tabs.appendChild(tb);
  });
  P.appendChild(tabs);

  /* 위젯 영역 */
  var wArea=h('div','padding:10px 12px;overflow-y:auto;flex:1;');
  wArea.id='__sa_fin_area';
  P.appendChild(wArea);

  function renderWidgetArea(tabId){
    var area=document.getElementById('__sa_fin_area');
    if(!area)return;
    area.innerHTML='';

    if(tabId==='overview'){
      /* 종합: 티커 테이프 + 주요 지표 */
      _addWidget(area,'ticker-tape',{
        "symbols":[
          {"proName":"FOREXCOM:SPXUSD","title":"S&P500"},
          {"proName":"FOREXCOM:NSXUSD","title":"나스닥"},
          {"proName":"FOREXCOM:DJI","title":"US30"},
          {"proName":"OANDA:XAUUSD","title":"금"},
          {"proName":"BINANCE:BTCUSDT","title":"BTC"},
          {"proName":"FX:EURUSD","title":"EUR/USD"}
        ],
        "showSymbolLogo":true,"isTransparent":true,"displayMode":"compact","colorTheme":"light","locale":"kr"
      },'60');

      _addLabel(area,'주요 시장');
      _addMiniSymbol(area,'FOREXCOM:SPXUSD','S&P 500');
      _addMiniSymbol(area,'FOREXCOM:NSXUSD','나스닥 100');
      _addMiniSymbol(area,'FOREXCOM:DJI','US 30 (다우)');
      _addMiniSymbol(area,'OANDA:XAUUSD','금(Gold)');
      _addMiniSymbol(area,'BINANCE:BTCUSDT','비트코인');

    }else if(tabId==='forex'){
      _addLabel(area,'주요 환율');
      _addMiniSymbol(area,'FX:EURUSD','유로/달러');
      _addMiniSymbol(area,'FX:USDJPY','달러/엔');
      _addMiniSymbol(area,'FX:GBPUSD','파운드/달러');
      _addLabel(area,'원자재');
      _addMiniSymbol(area,'OANDA:XAUUSD','금/달러');
      _addMiniSymbol(area,'TVC:USOIL','WTI 원유');

    }else if(tabId==='crypto'){
      _addLabel(area,'암호화폐');
      _addMiniSymbol(area,'BINANCE:BTCUSDT','비트코인');
      _addMiniSymbol(area,'BINANCE:ETHUSDT','이더리움');
      _addMiniSymbol(area,'BINANCE:SOLUSDT','솔라나');
      _addMiniSymbol(area,'BINANCE:XRPUSDT','리플');

    }else if(tabId==='calendar'){
      _addLabel(area,'경제 캘린더');
      _addWidget(area,'events',{
        "colorTheme":"light","isTransparent":true,"locale":"en","importanceFilter":"0,1","countryFilter":"us,eu,gb,jp,cn,kr,de,fr,in,au,ca,br"
      },'400');

    }else if(tabId==='news'){
      _addLabel(area,'실시간 금융 뉴스 (영문)');
      _addWidget(area,'timeline',{
        "feedMode":"all_symbols","isTransparent":true,"displayMode":"compact","colorTheme":"light","locale":"en","height":"500"
      },'500');
    }
  }

  function _addLabel(container,text){
    var lb=h('div','','');lb.className='fin-label';lb.textContent=text;
    container.appendChild(lb);
  }

  function _addMiniSymbol(container,symbol,title){
    var wrap=h('div','');wrap.className='fin-widget';
    var wid=h('div','');
    wid.className='tradingview-widget-container';
    var scr=document.createElement('script');
    scr.src='https://s3.tradingview.com/external-embedding/embed-widget-mini-symbol-overview.js';
    scr.async=true;
    scr.textContent=JSON.stringify({
      "symbol":symbol,"width":"100%","height":"160",
      "locale":"kr","dateRange":"1M","colorTheme":"light",
      "isTransparent":true,"autosize":false,
      "largeChartUrl":"https://www.tradingview.com/chart/?symbol="+encodeURIComponent(symbol)
    });
    wid.appendChild(scr);wrap.appendChild(wid);container.appendChild(wrap);
  }

  function _addWidget(container,widgetType,config,height){
    var wrap=h('div','');wrap.className='fin-widget';
    var wid=h('div','');wid.className='tradingview-widget-container';
    var scr=document.createElement('script');
    scr.src='https://s3.tradingview.com/external-embedding/embed-widget-'+widgetType+'.js';
    scr.async=true;
    scr.textContent=JSON.stringify(Object.assign({"width":"100%","height":height||"200"},config));
    wid.appendChild(scr);wrap.appendChild(wid);container.appendChild(wrap);
  }

  renderWidgetArea('overview');
}

/* ── 설정 렌더 ── */
function renderSettings(){
  _viewMode='settings';P.innerHTML='';
  var hdr=h('div','display:flex;align-items:center;justify-content:space-between;padding:14px 16px 11px;border-bottom:1px solid rgba(0,0,0,.04);flex-shrink:0;background:rgba(255,255,255,.92);border-radius:24px 24px 0 0;');
  hdr.appendChild(h('span','font-size:14px;font-weight:800;color:'+C.text+';','⚙ 설정'));
  var back=h('button','border:none;background:none;font-size:22px;color:'+C.sub+';cursor:pointer;padding:0;line-height:1;','×');
  back.onclick=function(){_viewMode='main';renderMain();};hdr.appendChild(back);
  P.appendChild(hdr);

  var wrap=h('div','padding:16px;overflow-y:auto;flex:1;');
  wrap.innerHTML='<div style="background:rgba(88,86,214,.06);border-radius:10px;padding:10px 12px;margin-bottom:14px;font-size:11px;color:#666;line-height:1.5;">🔒 <b>보안 안내</b><br>• API 키는 이 브라우저의 localStorage에만 저장됩니다.<br>• OpenAI API는 브라우저에서 직접 호출되며, 서버에 키가 전송되지 않습니다.<br>• 브라우저 데이터를 삭제하면 키도 함께 삭제됩니다.<br>• 기본 무료 모드는 별도 설정 없이 사용 가능합니다.</div>';

  var PROVS=[{v:'demo',l:'🆓 무료 데모 (기본)'},{v:'openai',l:'🟢 OpenAI'}];
  var MODELS={openai:['gpt-4o','gpt-5-mini','gpt-5.2']};
  var URLS={openai:'https://api.openai.com/v1'};
  var IS='width:100%;background:rgba(118,118,128,.08);border:1px solid rgba(0,0,0,.04);border-radius:10px;padding:8px 12px;font-size:12px;color:#1a1a1a;outline:none;display:block;margin-top:4px;';
  var LB='font-size:10px;color:#8e8e93;font-weight:600;display:block;margin-top:12px;';

  var s=settings;
  var po=PROVS.map(function(p){return '<option value="'+p.v+'"'+(s.provider===p.v?' selected':'')+'>'+p.l+'</option>';}).join('');
  var isDemo=s.provider==='demo';
  function _buildModelOpts(pv,sel){var ml=MODELS[pv]||[];if(!ml.length)return '<option value="">모델 없음</option>';return ml.map(function(m){return '<option value="'+esc(m)+'"'+(m===sel?' selected':'')+'>'+esc(m)+'</option>';}).join('');}

  wrap.innerHTML+='<label style="'+LB.replace('margin-top:12px','margin-top:0')+'">LLM 프로바이더</label><select id="__sa_prov" style="'+IS+'cursor:pointer;">'+po+'</select>';
  wrap.innerHTML+='<div id="__sa_af" style="display:'+(isDemo?'none':'block')+'">'
    +'<label style="'+LB+'">API KEY</label><input type="password" id="__sa_ak" value="'+esc(s.apiKey)+'" placeholder="API 키..." style="'+IS+'" />'
    +'<label style="'+LB+'">모델 선택</label><select id="__sa_mod" style="'+IS+'cursor:pointer;">'+_buildModelOpts(s.provider,s.model)+'</select>'
    +'<label style="'+LB+'">BASE URL</label><input type="text" id="__sa_url" value="'+esc(s.baseURL||URLS[s.provider]||'')+'" style="'+IS+'" /></div>';
  /* MARL 토글 */
  wrap.innerHTML+='<div style="margin-top:16px;padding:12px;background:rgba(88,86,214,.04);border-radius:12px;border:1px solid rgba(88,86,214,.08);">'
    +'<div style="font-size:11px;font-weight:700;color:#5856D6;margin-bottom:8px;">🧠 AI 강화 모드 (MARL)</div>'
    +'<label style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;cursor:pointer;"><span style="font-size:11px;color:#1c1c1e;"><b>🧠 딥분석</b> — 5단계 심층 분석 + 웹 검색 강화</span><input type="checkbox" id="__sa_marl_ins" '+(s.marl_insight?'checked':'')+' style="width:18px;height:18px;accent-color:#5856D6;" /></label>'
    +'<label style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;cursor:pointer;"><span style="font-size:11px;color:#1c1c1e;"><b>💡 아이디어</b> — 9개 전문 분야 아이디어 엔진</span><input type="checkbox" id="__sa_marl_eme" '+(s.marl_emergence?'checked':'')+' style="width:18px;height:18px;accent-color:#0d9488;" /></label>'
    +'<div id="__sa_engine_wrap" style="display:'+(s.marl_emergence?'block':'none')+';margin-top:6px;"><label style="font-size:10px;color:#8e8e93;font-weight:600;">엔진 선택</label>'
    +'<select id="__sa_marl_eng" style="width:100%;background:rgba(118,118,128,.08);border:1px solid rgba(0,0,0,.04);border-radius:10px;padding:8px 12px;font-size:12px;color:#1a1a1a;outline:none;margin-top:4px;cursor:pointer;">'
    +'<option value="invent" '+(s.marl_engine==='invent'?'selected':'')+'>🔬 발명 (Invent)</option>'
    +'<option value="create" '+(s.marl_engine==='create'?'selected':'')+'>🎨 창작 (Create)</option>'
    +'<option value="document" '+(s.marl_engine==='document'?'selected':'')+'>📄 문서 (Document)</option>'
    +'<option value="recipe" '+(s.marl_engine==='recipe'?'selected':'')+'>🍳 레시피 (Recipe)</option>'
    +'<option value="pharma" '+(s.marl_engine==='pharma'?'selected':'')+'>💊 제약 (Pharma)</option>'
    +'<option value="genomics" '+(s.marl_engine==='genomics'?'selected':'')+'>🧬 유전체 (Genomics)</option>'
    +'<option value="chemistry" '+(s.marl_engine==='chemistry'?'selected':'')+'>⚗️ 화학 (Chemistry)</option>'
    +'<option value="ecology" '+(s.marl_engine==='ecology'?'selected':'')+'>🌿 생태 (Ecology)</option>'
    +'<option value="law" '+(s.marl_engine==='law'?'selected':'')+'>⚖️ 법률 (Law)</option>'
    +'</select></div>'
    +'<div style="margin-top:6px;font-size:9px;color:#8e8e93;line-height:1.5;">⚡ 강화 모드 사용 시 응답에 10~20초 소요. LLM 5회 호출.</div></div>';
  wrap.innerHTML+='<button type="button" id="__sa_save" style="width:100%;padding:12px;background:linear-gradient(135deg,'+C.fab1+','+C.fab2+');border:none;border-radius:12px;color:#fff;font-size:13px;font-weight:700;cursor:pointer;margin-top:16px;">저장하고 적용</button>';
  P.appendChild(wrap);

  /* 이벤트 */
  document.getElementById('__sa_prov').onchange=function(){
    var pv=this.value;document.getElementById('__sa_af').style.display=pv==='demo'?'none':'block';
    var ue=document.getElementById('__sa_url');if(ue&&URLS[pv])ue.value=URLS[pv];
    var me=document.getElementById('__sa_mod');if(me)me.innerHTML=_buildModelOpts(pv,'');
  };
  /* MARL 창발성 토글 → 엔진 선택 표시 */
  var emeCheck=document.getElementById('__sa_marl_eme');
  if(emeCheck) emeCheck.onchange=function(){
    var ew=document.getElementById('__sa_engine_wrap');if(ew)ew.style.display=this.checked?'block':'none';
  };
  document.getElementById('__sa_save').onclick=function(){
    var pv=document.getElementById('__sa_prov').value;
    settings={provider:pv,apiKey:pv==='demo'?'':(document.getElementById('__sa_ak')||{}).value||'',model:pv==='demo'?'':(document.getElementById('__sa_mod')||{}).value||'',baseURL:pv==='demo'?'':(document.getElementById('__sa_url')||{}).value||'',language:'ko-KR',marl_insight:!!(document.getElementById('__sa_marl_ins')||{}).checked,marl_emergence:!!(document.getElementById('__sa_marl_eme')||{}).checked,marl_engine:(document.getElementById('__sa_marl_eng')||{}).value||'invent'};
    try{localStorage.setItem(LS_SET,JSON.stringify(settings));}catch(e){}
    /* 에이전트 재생성 — 모든 프로바이더 서버 프록시 경유 */
    if(pv!=='demo'&&settings.apiKey&&settings.model){
      try{SA.dispose();}catch(e){}
      var cfg={baseURL:settings.baseURL||URLS[pv],apiKey:settings.apiKey,model:settings.model,language:'ko-KR'};
      window.__SA_AGENT=new window.PageAgent(cfg);SA=window.__SA_AGENT;
      try{SA.panel.show=function(){};SA.panel.hide=function(){};SA.panel.expand=function(){};SA.panel.collapse=function(){};if(SA.panel.wrapper)SA.panel.wrapper.remove();}catch(e){}
      if(window.__SA_SPOTLIGHT) window.__SA_SPOTLIGHT.hookAgent(SA);
      _rebindEvents();
    }
    track('settings_save',{provider:pv,marl_insight:settings.marl_insight,marl_emergence:settings.marl_emergence,marl_engine:settings.marl_engine});
    _viewMode='main';renderMain();
  };
}

/* ── md → HTML ── */
function toHTML(t){
  if(!t)return'';

  /* STEP 0: 마크다운 표 → 개조식 리스트 강제 변환 */
  t=(function(src){
    var lines=src.split('\n'),result=[],tbl=[],inTable=false;
    function flushTable(){
      if(tbl.length<2){result.push.apply(result,tbl);tbl=[];inTable=false;return;}
      var headers=tbl[0].replace(/^\|/,'').replace(/\|$/,'').split('|').map(function(c){return c.trim();});
      for(var i=0;i<tbl.length;i++){
        var cells=tbl[i].replace(/^\|/,'').replace(/\|$/,'').split('|').map(function(c){return c.trim();});
        if(i===0){result.push('**'+cells.join(' · ')+'**');continue;}
        if(i===1&&/^[\s:\-]+$/.test(cells.join('')))continue;
        var parts=[];
        for(var j=0;j<cells.length;j++){
          if(cells[j]){
            if(headers[j]&&headers[j]!==cells[j])parts.push('**'+headers[j]+'**: '+cells[j]);
            else parts.push(cells[j]);
          }
        }
        result.push('• '+parts.join(' / '));
      }
      tbl=[];inTable=false;
    }
    for(var i=0;i<lines.length;i++){
      var l=lines[i];
      if(/^\s*\|.+\|\s*$/.test(l)){inTable=true;tbl.push(l);}
      else{if(inTable)flushTable();result.push(l);}
    }
    if(inTable)flushTable();
    return result.join('\n');
  })(t);

  /* STEP 1: 코드 블록 */
  t=t.replace(/```(\w*)\n?([\s\S]*?)```/g,function(_,lang,code){return '<pre><code>'+code.replace(/</g,'&lt;').replace(/>/g,'&gt;').trim()+'</code></pre>';});
  t=t.replace(/`([^`]+)`/g,'<code>$1</code>');

  /* STEP 2: 헤딩 */
  t=t.replace(/^#{3}\s+(.+)$/gm,'<h3 style="margin:12px 0 6px;font-size:12px;">$1</h3>');
  t=t.replace(/^#{2}\s+(.+)$/gm,'<h2 style="margin:14px 0 6px;font-size:13px;">$1</h2>');
  t=t.replace(/^#{1}\s+(.+)$/gm,'<h1 style="margin:16px 0 8px;font-size:14px;">$1</h1>');
  /* STEP 2.5: 번호 제목 (예: 1. / 2.1 / 3.2.1) → 별도 블록 */
  t=t.replace(/^(\d+(?:\.\d+)*)\.\s+\*\*(.+?)\*\*/gm,'<div style="margin:12px 0 4px;font-weight:700;font-size:12px;">$1. $2</div>');
  t=t.replace(/^(\d+(?:\.\d+)*)\s+\*\*(.+?)\*\*/gm,'<div style="margin:12px 0 4px;font-weight:700;font-size:12px;">$1 $2</div>');

  /* STEP 3: 강조 */
  t=t.replace(/\*\*\*(.+?)\*\*\*/g,'<strong><em>$1</em></strong>');
  t=t.replace(/\*\*(.+?)\*\*/g,'<strong>$1</strong>');
  t=t.replace(/\*(.+?)\*/g,'<em>$1</em>');

  /* STEP 4: 구분선 */
  t=t.replace(/^---+$/gm,'<hr>');

  /* STEP 5: 리스트 */
  t=t.replace(/^[\-\*•▸]\s+(.+)$/gm,'<li>$1</li>');
  t=t.replace(/((?:<li>.*<\/li>\n?)+)/g,'<ul>$1</ul>');
  t=t.replace(/^\d+\.\s+(.+)$/gm,'<li>$1</li>');

  /* STEP 6: 인용 */
  t=t.replace(/^>\s+(.+)$/gm,'<blockquote>$1</blockquote>');

  /* STEP 7: 링크 */
  t=t.replace(/(https?:\/\/[^\s<]+)/g,'<a href="$1" target="_blank" rel="noopener" style="color:#5856D6;word-break:break-all;">$1</a>');

  /* STEP 8: 문단 래핑 */
  var lines=t.split('\n'),out=[],buf=[];
  lines.forEach(function(l){
    var trimmed=l.trim();
    if(/^<(h[1-3]|ul|ol|li|pre|hr|blockquote|div)/.test(trimmed)||trimmed===''){
      if(buf.length){out.push('<p>'+buf.join('<br>').trim()+'</p>');buf=[];}
      if(trimmed)out.push(l);
    }else buf.push(l);
  });
  if(buf.length)out.push('<p>'+buf.join('<br>').trim()+'</p>');
  return out.join('');
}

/* ── 이벤트 리스닝 ── */
var _activeCard=null;
var _stepCards=[];

function _rebindEvents(){
  SA.addEventListener('activity',_onActivity);
  SA.addEventListener('historychange',_onHistChange);
}

function _onActivity(ev){
  if(!_activeCard)return;
  var d=ev.detail,st='';
  switch(d.type){
    case 'thinking':st='🧠 분석 중...';break;
    case 'executing':st='🔨 '+_actLabel(d.tool,d.input);break;
    case 'executed':st='👁 '+(d.output||'').substring(0,50);break;
    case 'retrying':st='🔄 재시도 ('+d.attempt+'/'+d.maxAttempts+')';break;
    case 'error':st='❌ '+((d.message||'').substring(0,60));break;
  }
  if(st)_activeCard.innerHTML='<div style="display:flex;align-items:center;gap:8px;"><div class="sd"><i></i><i></i><i></i></div><span style="font-size:12px;color:'+C.sub+';">'+st+'</span></div>';
  _scrollH();
}

function _onHistChange(){
  if(!_activeCard)return;
  var hst=SA.history||[];if(!hst.length)return;
  var last=hst[hst.length-1];
  /* 멀티스텝: 완료 전 액션 카드 누적 */
  if(last.type==='step'&&last.action&&last.action.name!=='done'){
    var label=_actLabel(last.action.name,last.action.input);
    var output=last.action.output||'';
    var stepDiv=document.createElement('div');stepDiv.className='ss';
    stepDiv.innerHTML='<b>Step '+(last.stepIndex+1)+'</b> '+esc(label)+(output?' → <span style="color:'+C.green+';">'+esc(output.substring(0,60))+'</span>':'');
    var hist=document.getElementById('__sa_H');
    if(hist)hist.insertBefore(stepDiv,_activeCard);
    _stepCards.push(stepDiv);
    _scrollH();
  }
}

function _actLabel(name,input){
  input=input||{};
  switch(name){
    case 'click_element_by_index':return '요소 ['+(input.index!==undefined?input.index:'?')+'] 클릭';
    case 'input_text':return '텍스트 입력: "'+(input.text||'').substring(0,20)+'"';
    case 'select_dropdown_option':return '옵션 선택: "'+(input.text||'')+'"';
    case 'scroll':return (input.down!==false?'아래':'위')+'로 스크롤';
    case 'wait':return (input.seconds||1)+'초 대기';
    case 'execute_javascript':return 'JS 실행';
    default:return name;
  }
}

function _scrollH(){var h=document.getElementById('__sa_H');if(h)h.scrollTop=h.scrollHeight;}

_rebindEvents();

/* ── MARL 파이프라인 (메타인지/창발성) ── */
function runMarl(task, mode, engine){
  var hist=document.getElementById('__sa_H');if(!hist)return;
  if(hist.querySelector('div[style*="text-align:center"]'))hist.innerHTML='';

  var modeLabel = mode==='insight' ? '🧠 딥분석' : '💡 아이디어 ['+engine+']';
  var uC=document.createElement('div');uC.className='su';
  uC.innerHTML='<span style="opacity:.7;margin-right:4px;">'+(mode==='insight'?'🧠':'✨')+'</span> '+esc(task);
  hist.appendChild(uC);

  /* 진행 상태 카드 */
  var aC=document.createElement('div');aC.className='sa';
  aC.innerHTML='<div style="padding:8px 0;"><div style="display:flex;align-items:center;gap:6px;margin-bottom:6px;"><div class="sd"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></div><span style="font-size:11px;color:#5856D6;font-weight:600;">'+modeLabel+' 처리 중...</span></div>'
    +'<div style="font-size:10px;color:#8e8e93;line-height:1.5;" id="__sa_marl_status">S1 가설 생성 → S2 해결 → S3 감사 → S4 검증 → S5 정제</div></div>';
  hist.appendChild(aC);_scrollH();
  if(window._setSendMode) window._setSendMode(true);

  /* 페이지 텍스트 추출 (DOM) */
  var pageText = '';
  try {
    var bodyClone = document.body.cloneNode(true);
    bodyClone.querySelectorAll('[data-page-agent-ignore],[id^="__sa_"],[id^="page-agent-runtime"]').forEach(function(el){el.remove();});
    bodyClone.querySelectorAll('script,style,noscript,svg,iframe').forEach(function(el){el.remove();});
    pageText = (bodyClone.innerText||bodyClone.textContent||'').replace(/\s+/g,' ').trim().substring(0, 6000);
  } catch(e) { pageText = document.title || location.href; }
  if(!pageText || pageText.length < 10) pageText = document.title + ' ' + (document.querySelector('meta[name="description"]')||{}).content||'';

  var fullPrompt = task + '\n\n[현재 페이지 제목] ' + (document.title||'없음') + '\n[URL] ' + location.href + '\n\n[페이지 내용 (' + pageText.length + '자)]\n' + pageText;
  console.log('[SA-MARL] prompt length:',fullPrompt.length,'pageText:',pageText.length);

  var BASE=window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space';
  var _t0_chat=Date.now();
  fetch(BASE+'/api/marl',{
    method:'POST',headers:{'Content-Type':'application/json'},
    body:JSON.stringify({prompt:fullPrompt, mode:mode, engine:engine, system:'반드시 한국어로 답변하라. 표(table/마크다운 표)는 어떤 경우에도 절대 사용 금지. 개조식 서술형으로 작성. 핵심은 **볼드** 강조. 섹션은 ## 헤딩으로 구분.'}),
    mode:'cors'
  }).then(function(r){
    console.log('[SA-MARL] response status:',r.status);
    if(!r.ok) return r.text().then(function(t){throw new Error('HTTP '+r.status+': '+t.substring(0,100));});
    return r.text().then(function(t){
      try{return JSON.parse(t);}catch(e){throw new Error('Invalid JSON: '+t.substring(0,100));}
    });
  }).then(function(d){
    _saAiDone('marl_chat',_t0_chat,!d.error,{mode:mode,engine:engine});
    console.log('[SA-MARL] data:',JSON.stringify(d).substring(0,200));
    if(d.error){
      aC.innerHTML='<p style="color:'+C.red+';font-weight:600;">❌ '+esc(d.error)+'</p>';
      _scrollH();return;
    }
    var text=d.answer;
    if(!text||text.trim().length<5){
      aC.innerHTML='<p style="color:'+C.orange+';font-weight:600;">⚠️ MARL 처리 결과가 비어있습니다. 다시 시도해주세요.</p>';
      _scrollH();return;
    }
    _logTask('MARL_'+modeLabel,task,text);
    var elapsed=d.elapsed||0;
    var fixes=d.fixes||[];
    aC.innerHTML='<div style="margin-bottom:6px;display:flex;align-items:center;gap:6px;"><span style="font-size:11px;font-weight:700;color:#5856D6;">'+modeLabel+'</span><span style="font-size:9px;color:#8e8e93;">'+elapsed+'초 · 5단계 처리'+(fixes.length?' · '+fixes.length+'개 수정':'')+'</span></div>'
      +toHTML(text);

    /* 🔊📋 액션 버튼 */
    var _pt=text.replace(/<[^>]*>/g,'').trim();
    var actDiv=document.createElement('div');actDiv.className='sa-actions';
    var tBtn=document.createElement('button');tBtn.innerHTML='🔊 읽기';var _tp=false;
    tBtn.onclick=function(){if(_tp){speechSynthesis.cancel();_tp=false;tBtn.innerHTML='🔊 읽기';tBtn.classList.remove('active');return;}var u=new SpeechSynthesisUtterance(_pt);u.lang='ko-KR';u.rate=1.1;u.onend=function(){_tp=false;tBtn.innerHTML='🔊 읽기';tBtn.classList.remove('active');};speechSynthesis.speak(u);_tp=true;tBtn.innerHTML='⏹ 멈춤';tBtn.classList.add('active');};
    actDiv.appendChild(tBtn);
    var cBtn=document.createElement('button');cBtn.innerHTML='📋 복사';
    cBtn.onclick=function(){navigator.clipboard.writeText(_pt).then(function(){cBtn.innerHTML='✅ 복사됨';setTimeout(function(){cBtn.innerHTML='📋 복사';},1500);}).catch(function(){});};
    actDiv.appendChild(cBtn);
    aC.appendChild(actDiv);
    _scrollH();_chatHTML=hist.innerHTML;
  }).catch(function(e){
    aC.innerHTML='<p style="color:'+C.red+';font-weight:600;">❌ MARL 처리 실패: '+esc(e.message)+'</p>';
    _scrollH();
  }).finally(function(){if(window._setSendMode) window._setSendMode(false);});
}

/* ── 웹 검색 (browser_search) ── */
function runSearch(query){
  var hist=document.getElementById('__sa_H');if(!hist)return;
  if(hist.querySelector('div[style*="text-align:center"]'))hist.innerHTML='';

  var uC=document.createElement('div');uC.className='su';
  uC.innerHTML='<span style="opacity:.7;margin-right:4px;">🔍</span> '+esc(query);
  hist.appendChild(uC);

  var aC=document.createElement('div');aC.className='sa';
  aC.innerHTML='<div class="sd"><i></i><i style="animation-delay:.15s"></i><i style="animation-delay:.3s"></i></div>';
  hist.appendChild(aC);_scrollH();
  if(window._setSendMode) window._setSendMode(true);

  var BASE=window.__SA_BASE||'https://ginigen-ai-siteagent.hf.space';
  var _t0_srch=Date.now();
  fetch(BASE+'/api/search',{
    method:'POST',headers:{'Content-Type':'application/json'},
    body:JSON.stringify({query:query}),mode:'cors'
  }).then(function(r){return r.json();}).then(function(d){
    _saAiDone('search',_t0_srch,!d.error,{feature:'search'});
    var text=d.result||d.error||'검색 결과 없음';
    _logTask('검색',query,text);
    aC.innerHTML=toHTML(text);
    /* 🔊📋 액션 버튼 */
    var actDiv=document.createElement('div');actDiv.className='sa-actions';
    var _pt=text.replace(/<[^>]*>/g,'').trim();
    var tBtn=document.createElement('button');tBtn.innerHTML='🔊 읽기';var _tp=false;
    tBtn.onclick=function(){if(_tp){speechSynthesis.cancel();_tp=false;tBtn.innerHTML='🔊 읽기';tBtn.classList.remove('active');return;}var u=new SpeechSynthesisUtterance(_pt);u.lang='ko-KR';u.rate=1.1;u.onend=function(){_tp=false;tBtn.innerHTML='🔊 읽기';tBtn.classList.remove('active');};speechSynthesis.speak(u);_tp=true;tBtn.innerHTML='⏹ 멈춤';tBtn.classList.add('active');};
    actDiv.appendChild(tBtn);
    var cBtn=document.createElement('button');cBtn.innerHTML='📋 복사';
    cBtn.onclick=function(){navigator.clipboard.writeText(_pt).then(function(){cBtn.innerHTML='✅ 복사됨';setTimeout(function(){cBtn.innerHTML='📋 복사';},1500);}).catch(function(){});};
    actDiv.appendChild(cBtn);
    aC.appendChild(actDiv);
    _scrollH();_chatHTML=hist.innerHTML;
  }).catch(function(e){
    aC.innerHTML='<p style="color:red;">❌ 검색 실패: '+esc(e.message)+'</p>';
    _scrollH();
  }).finally(function(){if(window._setSendMode) window._setSendMode(false);});
}

/* ── 실행 ── */
function runTask(task){
  window.__SA_LAST_CMD = task;
  window.__SA_LAST_USER_TIME = Date.now();
  if(window._setSendMode) window._setSendMode(true);
  var hist=document.getElementById('__sa_H');if(!hist)return;
  if(hist.querySelector('div[style*="text-align:center"]'))hist.innerHTML='';
  /* 제안 배너 제거 */
  var banner=document.getElementById('__sa_suggest');if(banner)banner.remove();

  var uC=document.createElement('div');uC.className='su';
  uC.innerHTML='<span style="opacity:.7;margin-right:4px;">💬</span> '+esc(task);
  hist.appendChild(uC);

  var aC=document.createElement('div');aC.className='sa';
  aC.innerHTML='<div class="sd"><i></i><i></i><i></i></div><span style="font-size:12px;color:'+C.sub+';margin-left:8px;">🧠 분석 시작...</span>';
  hist.appendChild(aC);
  _activeCard=aC;_stepCards=[];
  _scrollH();

  var dot=document.getElementById('__sa_dot');
  if(dot){dot.style.background=C.orange;dot.style.boxShadow='0 0 8px rgba(255,159,10,.6)';}

  track('command',{domain:location.hostname});

  SA.execute(task).then(function(result){
    _activeCard=null;
    if(window._setSendMode) window._setSendMode(false);
    var last=result&&result.data||'';
    if(!last){var hst=SA.history||[];for(var i=hst.length-1;i>=0;i--){var hh=hst[i];if(hh.type==='step'&&hh.action&&hh.action.name==='done'){last=hh.action.input&&hh.action.input.text||hh.action.output||'';break;}}}
    aC.innerHTML=last?toHTML(last):'<p style="color:'+C.green+';font-weight:600;">✅ 완료</p>';
    _logTask(task.substring(0,50),task,last);
    /* 🔊📋 액션 버튼 추가 */
    if(last){
      var actDiv=document.createElement('div');actDiv.className='sa-actions';
      var _plainText=last.replace(/<[^>]*>/g,'').replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&quot;/g,'"').replace(/&#039;/g,"'").trim();
      /* 🔊 읽기 */
      var ttsBtn=document.createElement('button');ttsBtn.innerHTML='🔊 읽기';
      var _ttsPlaying=false;
      ttsBtn.onclick=function(){
        if(_ttsPlaying){speechSynthesis.cancel();_ttsPlaying=false;ttsBtn.innerHTML='🔊 읽기';ttsBtn.classList.remove('active');return;}
        var utter=new SpeechSynthesisUtterance(_plainText);
        utter.lang='ko-KR';utter.rate=1.1;
        utter.onend=function(){_ttsPlaying=false;ttsBtn.innerHTML='🔊 읽기';ttsBtn.classList.remove('active');};
        utter.onerror=function(){_ttsPlaying=false;ttsBtn.innerHTML='🔊 읽기';ttsBtn.classList.remove('active');};
        speechSynthesis.speak(utter);_ttsPlaying=true;ttsBtn.innerHTML='⏹ 멈춤';ttsBtn.classList.add('active');
      };
      actDiv.appendChild(ttsBtn);
      /* 📋 복사 */
      var cpBtn=document.createElement('button');cpBtn.innerHTML='📋 복사';
      cpBtn.onclick=function(){
        navigator.clipboard.writeText(_plainText).then(function(){cpBtn.innerHTML='✅ 복사됨';setTimeout(function(){cpBtn.innerHTML='📋 복사';},1500);}).catch(function(){
          var ta=document.createElement('textarea');ta.value=_plainText;ta.style.cssText='position:fixed;left:-9999px;';document.body.appendChild(ta);ta.select();document.execCommand('copy');ta.remove();cpBtn.innerHTML='✅ 복사됨';setTimeout(function(){cpBtn.innerHTML='📋 복사';},1500);
        });
      };
      actDiv.appendChild(cpBtn);
      aC.appendChild(actDiv);
    }
    _scrollH();
    _chatHTML=hist.innerHTML;
    if(dot){dot.style.background=C.green;dot.style.boxShadow='0 0 6px rgba(48,209,88,.5)';}
  }).catch(function(e){
    _activeCard=null;
    if(window._setSendMode) window._setSendMode(false);
    aC.innerHTML='<p style="color:'+C.red+';font-weight:600;">❌ '+esc(e.message)+'</p>';
    _chatHTML=hist.innerHTML;
    if(dot){dot.style.background=C.red;dot.style.boxShadow='none';}
  });
}

/* 첫 로드 */
/* ── ask_user 연결: LLM이 사용자에게 질문할 때 ── */
SA.onAskUser = function(question){
  return new Promise(function(resolve){
    var hist=document.getElementById('__sa_H');if(!hist){resolve('');return;}
    /* 질문 카드 */
    var qCard=document.createElement('div');qCard.className='sa';
    qCard.innerHTML='<div style="padding:2px 0;"><span style="color:#FF9F0A;font-weight:700;">❓ AI 질문:</span> '+esc(question)+'</div>'
      +'<div style="display:flex;gap:6px;margin-top:8px;">'
      +'<input type="text" id="__sa_askInp" placeholder="답변을 입력하세요..." style="flex:1;border:1px solid rgba(88,86,214,.2);border-radius:10px;padding:8px 12px;font-size:12px;outline:none;background:rgba(255,255,255,.8);color:#1c1c1e;"/>'
      +'<button type="button" id="__sa_askBtn" style="border:none;border-radius:10px;background:linear-gradient(135deg,#5856D6,#007AFF);color:#fff;font-size:12px;font-weight:700;padding:8px 16px;cursor:pointer;">전송</button>'
      +'</div>';
    hist.appendChild(qCard);_scrollH();
    /* 키 이벤트 차단 */
    var askInp=document.getElementById('__sa_askInp');
    ['keydown','keyup','keypress','input','compositionstart','compositionend','compositionupdate'].forEach(function(evt){
      askInp.addEventListener(evt,function(e){e.stopPropagation();e.stopImmediatePropagation();},true);
    });
    askInp.focus();
    function _submit(){
      var ans=askInp.value.trim();if(!ans)return;
      qCard.innerHTML='<div style="padding:2px 0;"><span style="color:#FF9F0A;">❓</span> '+esc(question)+'</div><div style="color:#5856D6;font-weight:600;margin-top:4px;">💬 '+esc(ans)+'</div>';
      _scrollH();_chatHTML=hist.innerHTML;
      resolve(ans);
    }
    document.getElementById('__sa_askBtn').onclick=_submit;
    askInp.addEventListener('keydown',function(e){if(e.key==='Enter'&&!e.isComposing){e.preventDefault();_submit();}});
  });
};

openP();

/* ── 네비게이션 모드 처리 ── */
var _navMode = window.__SA_NAV_MODE || 'first';
var _navCmd = window.__SA_NAV_CMD || '';
console.log('[SA-UI] nav mode:', _navMode, 'cmd:', _navCmd);

if (_navMode === 'auto' && _navCmd) {
  /* 에이전트가 클릭해서 이동 → 자동 후속 실행 */
  setTimeout(function(){
    var followUp = '이전 요청: "' + _navCmd + '". 페이지가 이동되었다. 현재 페이지 내용을 분석하여 답변하라. 주의: 추가 클릭이나 페이지 이동 없이 현재 페이지만 분석하라.';
    runTask(followUp);
  }, 1000);
} else if (_navMode === 'suggest' && _navCmd) {
  /* 사용자가 직접 이동 → 제안 배너 */
  setTimeout(function(){
    var hist = document.getElementById('__sa_H');
    if (!hist) return;
    var banner = document.createElement('div');
    banner.id = '__sa_suggest';
    banner.style.cssText = 'padding:10px 12px;margin-bottom:8px;background:linear-gradient(135deg,rgba(88,86,214,.08),rgba(0,122,255,.05));border:1px solid rgba(88,86,214,.15);border-radius:14px;font-size:12px;color:#1c1c1e;';
    banner.innerHTML = '<div style="margin-bottom:6px;color:#5856D6;font-weight:700;font-size:11px;">📌 이전 명령을 이어서 실행할까요?</div>'
      + '<div style="color:#636366;font-size:11px;margin-bottom:8px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">"' + esc(_navCmd) + '"</div>'
      + '<div style="display:flex;gap:6px;">'
      + '<button type="button" id="__sa_cont" style="flex:1;border:none;border-radius:10px;background:linear-gradient(135deg,#5856D6,#007AFF);color:#fff;font-size:11px;font-weight:700;padding:7px 0;cursor:pointer;">▶ 이어서 분석</button>'
      + '<button type="button" id="__sa_skip" style="flex:1;border:none;border-radius:10px;background:rgba(0,0,0,.05);color:#8e8e93;font-size:11px;font-weight:600;padding:7px 0;cursor:pointer;">✕ 새로 시작</button>'
      + '</div>';
    hist.appendChild(banner);
    _scrollH();
    document.getElementById('__sa_cont').onclick = function(){
      banner.remove();
      var followUp = '이전 요청: "' + _navCmd + '". 페이지가 이동되었다. 현재 페이지에서 이전 요청에 대한 답변을 완성하라.';
      runTask(followUp);
    };
    document.getElementById('__sa_skip').onclick = function(){
      banner.remove();
    };
  }, 500);
}

console.log('✅ [SA-UI] v3 active');
} /* end initUI */
})();