@realtimex/realtimex-alchemy 1.0.50 → 1.0.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/CHANGELOG.md +9 -0
- package/dist/api/services/AlchemistService.js +2 -2
- package/dist/api/services/ChatService.js +1 -1
- package/dist/api/services/DeduplicationService.js +1 -1
- package/dist/api/services/EmbeddingService.js +54 -34
- package/dist/api/services/SDKService.js +0 -1
- package/dist/assets/{index-DH6m-zOy.js → index-Cb2XPDey.js} +3 -3
- package/dist/index.html +1 -1
- package/package.json +3 -3
- package/supabase/migrations/20260127000002_add_vector_storage.sql +67 -0
package/dist/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [1.0.51] - 2026-01-27
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
- **Vector Storage**: Migrated embedding storage from local SDK to Supabase `pgvector`. This enables cloud-native similarity search and persistent memory across devices.
|
|
12
|
+
- **Database**: Added `alchemy_vectors` table and HNSW indexes for high-performance semantic retrieval.
|
|
13
|
+
|
|
14
|
+
### Improved
|
|
15
|
+
- **Performance**: Implemented server-side similarity search via `match_vectors` RPC function, reducing latency for RAG and deduplication.
|
|
16
|
+
|
|
8
17
|
## [1.0.50] - 2026-01-26
|
|
9
18
|
|
|
10
19
|
### Improved
|
|
@@ -410,14 +410,14 @@ export class AlchemistService {
|
|
|
410
410
|
.eq('id', signal.id);
|
|
411
411
|
return;
|
|
412
412
|
}
|
|
413
|
-
// Store embedding in
|
|
413
|
+
// Store embedding in Supabase pgvector storage
|
|
414
414
|
await embeddingService.storeSignalEmbedding(signal.id, embedding, {
|
|
415
415
|
title: signal.title,
|
|
416
416
|
summary: signal.summary,
|
|
417
417
|
url: signal.url,
|
|
418
418
|
category: signal.category,
|
|
419
419
|
userId
|
|
420
|
-
});
|
|
420
|
+
}, supabase);
|
|
421
421
|
// Update signal metadata
|
|
422
422
|
await supabase
|
|
423
423
|
.from('signals')
|
|
@@ -64,7 +64,7 @@ export class ChatService {
|
|
|
64
64
|
let sources = [];
|
|
65
65
|
// 3. Retrieve Context (if embedding checks out)
|
|
66
66
|
if (queryEmbedding) {
|
|
67
|
-
const similar = await embeddingService.findSimilarSignals(queryEmbedding, userId, 0.55, // Lowered threshold for better recall
|
|
67
|
+
const similar = await embeddingService.findSimilarSignals(queryEmbedding, userId, supabase, 0.55, // Lowered threshold for better recall
|
|
68
68
|
10 // Increased Top K
|
|
69
69
|
);
|
|
70
70
|
console.log(`[ChatService] RAG Retrieval: Found ${similar.length} signals for query: "${content}"`);
|
|
@@ -18,7 +18,7 @@ export class DeduplicationService {
|
|
|
18
18
|
try {
|
|
19
19
|
// 1. Semantic Check (if embedding exists)
|
|
20
20
|
if (embedding && embedding.length > 0) {
|
|
21
|
-
const similar = await embeddingService.findSimilarSignals(embedding, userId, this.SIMILARITY_THRESHOLD, 5 // Check top 5 matches
|
|
21
|
+
const similar = await embeddingService.findSimilarSignals(embedding, userId, supabase, this.SIMILARITY_THRESHOLD, 5 // Check top 5 matches
|
|
22
22
|
);
|
|
23
23
|
if (similar.length > 0) {
|
|
24
24
|
const bestMatch = similar[0];
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { SDKService } from './SDKService.js';
|
|
2
2
|
/**
|
|
3
|
-
* Embedding Service
|
|
4
|
-
*
|
|
3
|
+
* Embedding Service
|
|
4
|
+
* Uses RealTimeX SDK for embedding generation
|
|
5
|
+
* Uses Supabase pgvector for vector storage and similarity search
|
|
5
6
|
* Gracefully degrades if SDK is not available
|
|
6
7
|
*/
|
|
7
8
|
export class EmbeddingService {
|
|
8
|
-
WORKSPACE_ID = 'alchemy-signals';
|
|
9
9
|
SIMILARITY_THRESHOLD = 0.85;
|
|
10
10
|
/**
|
|
11
11
|
* Generate embedding for a single text
|
|
@@ -60,22 +60,29 @@ export class EmbeddingService {
|
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
62
|
/**
|
|
63
|
-
* Store signal embedding in
|
|
63
|
+
* Store signal embedding in Supabase pgvector storage
|
|
64
64
|
* @param signalId - Unique signal ID
|
|
65
65
|
* @param embedding - Embedding vector
|
|
66
66
|
* @param metadata - Signal metadata
|
|
67
|
+
* @param supabase - Supabase client
|
|
67
68
|
*/
|
|
68
|
-
async storeSignalEmbedding(signalId, embedding, metadata) {
|
|
69
|
+
async storeSignalEmbedding(signalId, embedding, metadata, supabase) {
|
|
69
70
|
try {
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
71
|
+
// Format embedding as pgvector string
|
|
72
|
+
const embeddingStr = `[${embedding.join(',')}]`;
|
|
73
|
+
const { error } = await supabase
|
|
74
|
+
.from('alchemy_vectors')
|
|
75
|
+
.upsert({
|
|
76
|
+
signal_id: signalId,
|
|
77
|
+
user_id: metadata.userId,
|
|
78
|
+
embedding: embeddingStr,
|
|
79
|
+
model: 'text-embedding-3-small'
|
|
80
|
+
}, {
|
|
81
|
+
onConflict: 'signal_id,model'
|
|
82
|
+
});
|
|
83
|
+
if (error) {
|
|
84
|
+
throw error;
|
|
73
85
|
}
|
|
74
|
-
await sdk.llm.vectors.upsert([{
|
|
75
|
-
id: signalId,
|
|
76
|
-
vector: embedding,
|
|
77
|
-
metadata
|
|
78
|
-
}], { workspaceId: this.WORKSPACE_ID });
|
|
79
86
|
console.log('[EmbeddingService] Stored embedding for signal:', signalId);
|
|
80
87
|
}
|
|
81
88
|
catch (error) {
|
|
@@ -84,32 +91,39 @@ export class EmbeddingService {
|
|
|
84
91
|
}
|
|
85
92
|
}
|
|
86
93
|
/**
|
|
87
|
-
* Find similar signals using semantic search
|
|
94
|
+
* Find similar signals using semantic search via Supabase pgvector
|
|
88
95
|
* @param queryEmbedding - Query embedding vector
|
|
89
96
|
* @param userId - User ID for filtering
|
|
97
|
+
* @param supabase - Supabase client
|
|
90
98
|
* @param threshold - Similarity threshold (0-1)
|
|
91
99
|
* @param limit - Max results
|
|
92
100
|
* @returns Array of similar signals
|
|
93
101
|
*/
|
|
94
|
-
async findSimilarSignals(queryEmbedding, userId, threshold = this.SIMILARITY_THRESHOLD, limit = 10) {
|
|
102
|
+
async findSimilarSignals(queryEmbedding, userId, supabase, threshold = this.SIMILARITY_THRESHOLD, limit = 10) {
|
|
95
103
|
try {
|
|
96
|
-
|
|
97
|
-
|
|
104
|
+
// Format embedding as pgvector string
|
|
105
|
+
const embeddingStr = `[${queryEmbedding.join(',')}]`;
|
|
106
|
+
const { data, error } = await supabase.rpc('match_vectors', {
|
|
107
|
+
query_embedding: embeddingStr,
|
|
108
|
+
match_threshold: threshold,
|
|
109
|
+
match_count: limit,
|
|
110
|
+
target_user_id: userId
|
|
111
|
+
});
|
|
112
|
+
if (error) {
|
|
113
|
+
console.error('[EmbeddingService] Similarity search RPC error:', error.message);
|
|
98
114
|
return [];
|
|
99
115
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
score: r.score,
|
|
112
|
-
metadata: r.metadata || {}
|
|
116
|
+
// Map results to expected format
|
|
117
|
+
return (data || []).map((r) => ({
|
|
118
|
+
id: r.signal_id,
|
|
119
|
+
score: r.similarity,
|
|
120
|
+
metadata: {
|
|
121
|
+
title: r.title,
|
|
122
|
+
summary: r.summary,
|
|
123
|
+
url: r.url,
|
|
124
|
+
category: r.category,
|
|
125
|
+
userId
|
|
126
|
+
}
|
|
113
127
|
}));
|
|
114
128
|
}
|
|
115
129
|
catch (error) {
|
|
@@ -120,12 +134,18 @@ export class EmbeddingService {
|
|
|
120
134
|
/**
|
|
121
135
|
* Delete all embeddings for a user
|
|
122
136
|
* @param userId - User ID
|
|
137
|
+
* @param supabase - Supabase client
|
|
123
138
|
*/
|
|
124
|
-
async deleteUserEmbeddings(userId) {
|
|
139
|
+
async deleteUserEmbeddings(userId, supabase) {
|
|
125
140
|
try {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
141
|
+
const { error } = await supabase
|
|
142
|
+
.from('alchemy_vectors')
|
|
143
|
+
.delete()
|
|
144
|
+
.eq('user_id', userId);
|
|
145
|
+
if (error) {
|
|
146
|
+
throw error;
|
|
147
|
+
}
|
|
148
|
+
console.log('[EmbeddingService] Deleted all embeddings for user:', userId);
|
|
129
149
|
}
|
|
130
150
|
catch (error) {
|
|
131
151
|
console.error('[EmbeddingService] Deletion failed:', error.message);
|
|
@@ -67,7 +67,7 @@ ${S}`}class kt extends Error{constructor({message:t,code:n,cause:r,name:o}){var
|
|
|
67
67
|
${d===w?"border-primary/50 bg-black/40 scale-105":""}
|
|
68
68
|
disabled:opacity-50 disabled:cursor-not-allowed
|
|
69
69
|
`,"aria-label":`Digit ${w+1}`},w))})}function jP({onAuthSuccess:e,isInitialized:t=!0}){const[n,r]=T.useState(""),[o,a]=T.useState(""),[l,d]=T.useState(""),[h,p]=T.useState(""),[m,y]=T.useState(!1),[x,w]=T.useState(!t),[b,_]=T.useState(null),[k,S]=T.useState("password"),[E,N]=T.useState("email"),[R,M]=T.useState(""),O=async V=>{V.preventDefault(),y(!0),_(null);try{if(x){const{error:W}=await ne.auth.signUp({email:n,password:o,options:{data:{first_name:l,last_name:h,full_name:`${l} ${h}`.trim()}}});if(W)throw W;e()}else if(k==="password"){const{error:W}=await ne.auth.signInWithPassword({email:n,password:o});if(W)throw W;e()}else if(k==="otp")if(E==="email"){const{error:W}=await ne.auth.signInWithOtp({email:n,options:{shouldCreateUser:!1}});if(W)throw W;N("verify")}else await q()}catch(W){_(W.message)}finally{y(!1)}},q=async()=>{y(!0),_(null);try{const{data:V,error:W}=await ne.auth.verifyOtp({email:n,token:R,type:"magiclink"});if(W)throw W;if(!V.session)throw new Error("Failed to create session");e()}catch(V){_(V.message||"Invalid code")}finally{y(!1)}};return u.jsx("div",{className:"flex flex-col items-center justify-center p-8 h-full bg-gradient-to-t from-bg to-bg/50",children:u.jsxs(ze.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"w-full max-w-md glass p-8 space-y-8",children:[u.jsxs("div",{className:"text-center space-y-2",children:[u.jsx("h2",{className:"text-3xl font-black italic tracking-tighter",children:!t&&x?"INITIALIZE MASTER":x?"JOIN THE CIRCLE":k==="otp"?"MYSTIC ACCESS":"ALCHEMIST LOGIN"}),u.jsx("p",{className:"text-xs text-fg/40 font-mono tracking-widest uppercase",children:!t&&x?"Forge the prime alchemist account":k==="otp"?E==="email"?"Enter your essence email":"Transmute the sacred code":"Transmute your data into intelligence"})]}),u.jsx("form",{onSubmit:O,className:"space-y-4",children:u.jsxs(Pt,{mode:"wait",children:[x&&u.jsxs(ze.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:"grid grid-cols-2 gap-4 overflow-hidden",children:[u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"First Name"}),u.jsx("input",{type:"text",value:l,onChange:V=>d(V.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 px-4 text-sm focus:border-primary/50 outline-none transition-all",placeholder:"Zosimos",required:!0})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Last Name"}),u.jsx("input",{type:"text",value:h,onChange:V=>p(V.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 px-4 text-sm focus:border-primary/50 outline-none transition-all",placeholder:"Panopolis",required:!0})]})]},"signup-fields"),k==="otp"&&E==="verify"?u.jsxs(ze.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},className:"space-y-6 py-4",children:[u.jsx("div",{className:"flex justify-center",children:u.jsx(_P,{value:R,onChange:M,length:6,onComplete:V=>{M(V)},error:!!b})}),u.jsx("button",{type:"button",onClick:()=>N("email"),className:"w-full text-[10px] font-bold uppercase text-primary/40 hover:text-primary transition-colors tracking-widest",children:"Change email address"}),u.jsxs("button",{type:"button",disabled:m||R.length!==6,onClick:q,className:"w-full py-4 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center justify-center gap-2",children:[m?u.jsx("div",{className:"w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"}):u.jsx(Jg,{size:18}),"VERIFY CODE"]})]},"otp-verify"):u.jsxs(ze.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"space-y-4",children:[u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Email Address"}),u.jsxs("div",{className:"relative",children:[u.jsx(NS,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-fg/20",size:16}),u.jsx("input",{type:"email",value:n,onChange:V=>r(V.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 pl-10 pr-4 text-sm focus:border-primary/50 outline-none transition-all",placeholder:"alchemist@example.com",required:!0})]})]}),(x||k==="password")&&u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Complexity Key"}),u.jsxs("div",{className:"relative",children:[u.jsx(ES,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-fg/20",size:16}),u.jsx("input",{type:"password",value:o,onChange:V=>a(V.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 pl-10 pr-4 text-sm focus:border-primary/50 outline-none transition-all",placeholder:"••••••••",required:!0})]})]}),u.jsxs("button",{type:"submit",disabled:m,className:"w-full py-4 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center justify-center gap-2",children:[m&&u.jsx("div",{className:"w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"}),x?u.jsx(US,{size:18}):u.jsx(Jg,{size:18}),x?"INITIALIZE ACCOUNT":k==="otp"?"SEND CODE":"UNSEAL ENGINE"]})]},"base-login")]})}),b&&k==="password"&&u.jsx(ze.p,{initial:{opacity:0},animate:{opacity:1},className:"text-xs text-error font-medium bg-error/10 p-3 rounded-lg border border-error/10",children:b}),u.jsxs("div",{className:"space-y-4",children:[!x&&u.jsx("div",{className:"flex flex-col gap-2",children:k==="password"?u.jsxs("button",{type:"button",onClick:()=>{S("otp"),N("email"),_(null)},className:"w-full flex items-center justify-center gap-2 py-3 glass hover:bg-surface text-xs font-bold uppercase tracking-widest transition-all text-fg/40 hover:text-primary",children:[u.jsx(kS,{size:16})," Sign in with Code"]}):u.jsxs("button",{type:"button",onClick:()=>{S("password"),_(null)},className:"w-full flex items-center justify-center gap-2 py-3 glass hover:bg-surface text-xs font-bold uppercase tracking-widest transition-all text-fg/40 hover:text-primary",children:[u.jsx(B0,{size:16})," Sign in with Password"]})}),u.jsxs("p",{className:"text-center text-xs text-fg/40",children:[x?"Already an Alchemist?":"New to Alchemy?"," "," ",u.jsx("button",{onClick:()=>{w(!x),S("password"),_(null)},className:"text-primary font-bold hover:underline",children:x?"Login instead":"Create an account"})]})]})]})})}function EP(e){const t=e.trim();return t?t.startsWith("http://")||t.startsWith("https://")?t:`https://${t}.supabase.co`:""}function NP(e){const t=e.match(/https?:\/\/([^.]+)\.supabase\.co/);return t?t[1]:""}function hb({onComplete:e,open:t=!0,canClose:n=!1}){const[r,o]=T.useState("welcome"),[a,l]=T.useState(""),[d,h]=T.useState(""),[p,m]=T.useState(""),[y,x]=T.useState(""),[w,b]=T.useState(null),[_,k]=T.useState(!1),[S,E]=T.useState([]),[N,R]=T.useState("idle"),M=T.useRef(null);if(T.useEffect(()=>{M.current?.scrollIntoView({behavior:"smooth"})},[S]),!t)return null;const O=async()=>{b(null),k(!0),o("validating");const W=EP(a),he=d.trim(),se=await wP(W,he);if(se.valid){xP({url:W,anonKey:he});try{const ee=db(W,he),{data:J,error:H}=await ee.from("init_state").select("is_initialized").single();if(!H&&J&&J.is_initialized>0){o("success"),setTimeout(()=>{window.location.reload()},1500);return}}catch{console.log("[SetupWizard] init_state check failed, showing migration step")}const ie=NP(W);m(ie),o("migration"),k(!1)}else b(se.error||"Connection failed"),o("credentials"),k(!1)},q=async()=>{if(!p){b("Project ID is required");return}if(!y){b("Access token is required");return}b(null),E([]),R("running"),o("migrating");try{const he=(await fetch("/api/migrate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:p,accessToken:y})})).body?.getReader(),se=new TextDecoder;if(!he)throw new Error("Failed to read migration stream");for(;;){const{done:ie,value:ee}=await he.read();if(ie)break;const H=se.decode(ee).split(`
|
|
70
|
-
`).filter(re=>re.startsWith("data: "));for(const re of H)try{const ae=JSON.parse(re.slice(6));ae.type==="done"?ae.data==="success"?(R("success"),o("success"),setTimeout(()=>{window.location.reload()},2e3)):(R("failed"),b("Migration failed. Check logs for details.")):E(K=>[...K,ae.data])}catch{}}}catch(W){R("failed"),b(W.message||"Migration failed"),E(he=>[...he,`Error: ${W.message}`])}},V=()=>{o("success"),setTimeout(()=>{window.location.reload()},1500)};return u.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-6 bg-bg/80 backdrop-blur-sm",children:u.jsxs(ze.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:"w-full max-w-lg glass p-8 space-y-8 relative overflow-hidden",children:[u.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-primary/10 rounded-full blur-3xl -translate-y-1/2 translate-x-1/2"}),u.jsxs(Pt,{mode:"wait",children:[r==="welcome"&&u.jsxs(ze.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},className:"space-y-6",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"p-2 bg-primary/10 rounded-xl",children:u.jsx(zo,{className:"w-6 h-6 text-primary"})}),u.jsx("h2",{className:"text-2xl font-black italic tracking-tighter uppercase",children:"Assemble Your Engine"})]}),u.jsx("p",{className:"text-sm text-fg/50 font-medium",children:"Alchemy requires a Supabase essence to store signal fragments and intelligence patterns."})]}),u.jsxs("div",{className:"glass bg-white/5 border-white/10 p-4 rounded-xl space-y-3",children:[u.jsx("p",{className:"text-xs font-bold uppercase tracking-widest text-primary/70",children:"Requirements:"}),u.jsxs("ul",{className:"space-y-2",children:[u.jsxs("li",{className:"flex items-center gap-2 text-sm text-fg/60",children:[u.jsx(pi,{className:"w-4 h-4 text-emerald-500"})," Supabase Project URL"]}),u.jsxs("li",{className:"flex items-center gap-2 text-sm text-fg/60",children:[u.jsx(pi,{className:"w-4 h-4 text-emerald-500"})," Anon Public API Key"]}),u.jsxs("li",{className:"flex items-center gap-2 text-sm text-fg/60",children:[u.jsx(pi,{className:"w-4 h-4 text-emerald-500"})," Database Password (for migrations)"]})]})]}),u.jsxs("div",{className:"flex flex-col gap-3",children:[u.jsxs("a",{href:"https://supabase.com",target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center gap-2 py-3 border border-border/20 rounded-xl text-xs font-bold uppercase tracking-widest hover:bg-white/5 transition-all text-fg/60",children:["Forge Project at Supabase ",u.jsx(Ei,{size:14})]}),u.jsxs("button",{onClick:()=>o("credentials"),className:"w-full py-4 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.01] active:scale-95 transition-all flex items-center justify-center gap-2",children:["BEGIN INITIALIZATION ",u.jsx(aS,{size:18})]})]})]},"welcome"),r==="credentials"&&u.jsxs(ze.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},className:"space-y-6",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx("h2",{className:"text-2xl font-black italic tracking-tighter uppercase",children:"Essence Coordinates"}),u.jsx("p",{className:"text-sm text-fg/50 font-medium lowercase",children:"Link the alchemist engine to your cloud database"})]}),u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Project URL or ID"}),u.jsx("input",{type:"text",value:a,onChange:W=>l(W.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 px-4 text-sm focus:border-primary/50 outline-none transition-all",placeholder:"https://xxx.supabase.co or project-id"})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Anon Public Key"}),u.jsx("input",{type:"password",value:d,onChange:W=>h(W.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 px-4 text-sm focus:border-primary/50 outline-none transition-all",placeholder:"eyJ..."})]})]}),w&&u.jsxs("div",{className:"bg-error/10 border border-error/20 p-3 rounded-xl flex items-center gap-3",children:[u.jsx(pr,{className:"w-5 h-5 text-error"}),u.jsx("p",{className:"text-xs text-error font-bold tracking-tight",children:w})]}),u.jsxs("div",{className:"flex gap-3",children:[u.jsx("button",{onClick:()=>o("welcome"),className:"flex-1 py-4 border border-border/20 rounded-xl text-xs font-bold uppercase tracking-widest hover:bg-white/5 transition-all text-fg/40",children:"BACK"}),u.jsxs("button",{onClick:O,disabled:!a||!d,className:"flex-[2] py-4 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.01] active:scale-95 transition-all disabled:opacity-50 disabled:grayscale flex items-center justify-center gap-2",children:["CONNECT ESSENCE ",u.jsx(Yt,{size:18})]})]})]},"credentials"),r==="validating"&&u.jsxs(ze.div,{initial:{opacity:0},animate:{opacity:1},className:"flex flex-col items-center justify-center py-12 space-y-6",children:[u.jsxs("div",{className:"relative",children:[u.jsx("div",{className:"absolute inset-0 bg-primary/20 blur-xl rounded-full"}),u.jsx(Et,{className:"w-16 h-16 animate-spin text-primary relative z-10"})]}),u.jsxs("div",{className:"text-center space-y-2",children:[u.jsx("h3",{className:"text-xl font-bold italic uppercase tracking-tighter",children:"Validating Link"}),u.jsx("p",{className:"text-sm text-fg/40 font-mono tracking-widest uppercase animate-pulse",children:"Synchronizing Resonance..."})]})]},"validating"),r==="migration"&&u.jsxs(ze.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},className:"space-y-6",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"p-2 bg-accent/10 rounded-xl",children:u.jsx(zl,{className:"w-6 h-6 text-accent"})}),u.jsx("h2",{className:"text-2xl font-black italic tracking-tighter uppercase",children:"Initialize Schema"})]}),u.jsx("p",{className:"text-sm text-fg/50 font-medium",children:"Run database migrations to set up required tables and functions."})]}),u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Project ID"}),u.jsx("input",{type:"text",value:p,onChange:W=>m(W.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 px-4 text-sm focus:border-primary/50 outline-none transition-all font-mono",placeholder:"abcdefghijklm"}),u.jsx("p",{className:"text-[10px] text-fg/30 ml-1",children:"Found in Supabase Dashboard → Project Settings → General"})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Access Token"}),u.jsx("input",{type:"password",value:y,onChange:W=>x(W.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 px-4 text-sm focus:border-primary/50 outline-none transition-all font-mono",placeholder:"sbp_..."}),u.jsxs("p",{className:"text-[10px] text-fg/30 ml-1",children:["Generate at"," ",u.jsx("a",{href:"https://supabase.com/dashboard/account/tokens",target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:underline",children:"supabase.com/dashboard/account/tokens"})]})]})]}),w&&u.jsxs("div",{className:"bg-error/10 border border-error/20 p-3 rounded-xl flex items-center gap-3",children:[u.jsx(pr,{className:"w-5 h-5 text-error"}),u.jsx("p",{className:"text-xs text-error font-bold tracking-tight",children:w})]}),u.jsxs("div",{className:"flex gap-3",children:[u.jsx("button",{onClick:V,className:"flex-1 py-4 border border-border/20 rounded-xl text-xs font-bold uppercase tracking-widest hover:bg-white/5 transition-all text-fg/40",children:"SKIP"}),u.jsxs("button",{onClick:q,disabled:!p||!y,className:"flex-[2] py-4 bg-gradient-to-r from-accent to-primary text-white font-bold rounded-xl shadow-lg glow-accent hover:scale-[1.01] active:scale-95 transition-all disabled:opacity-50 disabled:grayscale flex items-center justify-center gap-2",children:[u.jsx(RS,{size:18})," RUN MIGRATIONS"]})]})]},"migration"),r==="migrating"&&u.jsxs(ze.div,{initial:{opacity:0},animate:{opacity:1},className:"space-y-6",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx(Et,{className:"w-6 h-6 animate-spin text-accent"}),u.jsx("h2",{className:"text-xl font-black italic tracking-tighter uppercase",children:"Running Migrations"})]}),u.jsx("p",{className:"text-sm text-fg/40",children:"This may take a minute..."})]}),u.jsxs("div",{className:"bg-black/40 border border-border/20 rounded-xl p-4 h-64 overflow-y-auto font-mono text-xs",children:[S.map((W,he)=>u.jsx("div",{className:`py-0.5 ${W.includes("✅")||W.includes("SUCCESS")?"text-emerald-400":W.includes("❌")||W.includes("Error")?"text-red-400":W.includes("⚠️")?"text-amber-400":"text-fg/60"}`,children:W},he)),u.jsx("div",{ref:M})]}),N==="failed"&&u.jsxs("div",{className:"flex gap-3",children:[u.jsxs("button",{onClick:()=>o("migration"),className:"flex-1 py-3 border border-border/20 rounded-xl text-xs font-bold uppercase tracking-widest hover:bg-white/5 transition-all text-fg/40",children:[u.jsx(B0,{size:14,className:"inline mr-2"})," BACK"]}),u.jsx("button",{onClick:q,className:"flex-1 py-3 bg-accent/20 border border-accent/30 rounded-xl text-xs font-bold uppercase tracking-widest hover:bg-accent/30 transition-all text-accent",children:"RETRY"})]})]},"migrating"),r==="success"&&u.jsxs(ze.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},className:"flex flex-col items-center justify-center py-12 space-y-6",children:[u.jsx("div",{className:"p-4 bg-emerald-500/20 rounded-full",children:u.jsx(vs,{className:"w-16 h-16 text-emerald-500"})}),u.jsxs("div",{className:"text-center space-y-2",children:[u.jsx("h3",{className:"text-2xl font-black italic uppercase tracking-tighter",children:"Engine Aligned"}),u.jsx("p",{className:"text-sm text-fg/40 font-mono tracking-widest uppercase",children:"Restarting Alchemist Subsystems..."})]})]},"success")]})]})})}const Ur={chrome:{icon:u.jsx(yS,{size:18}),name:"Google Chrome",color:"text-yellow-500"},firefox:{icon:u.jsx(dd,{size:18}),name:"Mozilla Firefox",color:"text-orange-500"},safari:{icon:u.jsx(dd,{size:18}),name:"Safari",color:"text-blue-500"},edge:{icon:u.jsx(dd,{size:18}),name:"Microsoft Edge",color:"text-cyan-500"},brave:{icon:u.jsx(Yt,{size:18}),name:"Brave",color:"text-orange-400"},arc:{icon:u.jsx(Yt,{size:18}),name:"Arc",color:"text-purple-500"}};function CP({sources:e,onChange:t}){const[n,r]=T.useState(!1),[o,a]=T.useState({}),[l,d]=T.useState(""),[h,p]=T.useState("chrome"),[m,y]=T.useState(!1),x=async()=>{r(!0);try{const{data:S}=await Ke.get("/api/browser-paths/detect");a(S)}catch(S){console.error("Detection failed:",S)}finally{r(!1)}},w=S=>{const E=o[S];if(!E||!E.found||!E.valid||e.find(M=>M.browser===S&&M.path===E.path))return;const R={browser:S,path:E.path,enabled:!0,label:`${Ur[S].name} (Auto-detected)`};t([...e,R])},b=async()=>{if(l.trim()){y(!0);try{const{data:S}=await Ke.post("/api/browser-paths/validate",{path:l});if(!S.valid){alert(`Invalid path: ${S.error||"Not a browser history database"}`),y(!1);return}const E={browser:h,path:l,enabled:!0,label:`${Ur[h].name} (Custom)`};t([...e,E]),d("")}catch(S){console.error("Validation failed:",S),alert("Failed to validate path")}finally{y(!1)}}},_=S=>{const E=[...e];E[S].enabled=!E[S].enabled,t(E)},k=S=>{t(e.filter((E,N)=>N!==S))};return u.jsxs("div",{className:"space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[u.jsx(Ll,{size:14})," Auto-Detect Browsers"]}),u.jsxs("button",{onClick:x,disabled:n,className:"px-3 py-1.5 text-xs font-bold uppercase tracking-widest bg-primary/10 hover:bg-primary/20 text-primary rounded-lg transition-all flex items-center gap-2",children:[n?u.jsx(Et,{size:12,className:"animate-spin"}):u.jsx(Ll,{size:12}),n?"Scanning...":"Scan System"]})]}),Object.keys(o).length>0&&u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:Object.keys(Ur).map(S=>{const E=o[S],N=Ur[S],R=e.some(M=>M.browser===S&&M.path===E?.path);return u.jsxs(ze.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:`glass p-4 rounded-xl border ${E?.found&&E?.valid?"border-success/20 bg-success/5":E?.found?"border-error/20 bg-error/5":"border-border/10"}`,children:[u.jsxs("div",{className:"flex items-start justify-between mb-2",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("div",{className:N.color,children:N.icon}),u.jsx("span",{className:"text-sm font-bold",children:N.name})]}),E?.found&&E?.valid?u.jsx(pi,{size:16,className:"text-success"}):E?.found?u.jsx(pr,{size:16,className:"text-error"}):u.jsx(wn,{size:16,className:"text-fg/20"})]}),E?.found?u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"text-[10px] font-mono text-fg/40 truncate mb-2",children:E.path}),E.valid?u.jsx("button",{onClick:()=>w(S),disabled:R,className:`w-full py-1.5 text-xs font-bold uppercase tracking-widest rounded-lg transition-all ${R?"bg-fg/5 text-fg/30 cursor-not-allowed":"bg-success/10 hover:bg-success/20 text-success"}`,children:R?"Already Added":"Add Source"}):u.jsx("p",{className:"text-[10px] text-error font-medium",children:E.error})]}):u.jsx("p",{className:"text-[10px] text-fg/30 italic",children:"Not found on this system"})]},S)})})]}),u.jsxs("div",{className:"space-y-3",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[u.jsx(wS,{size:14})," Add Custom Path"]}),u.jsxs("div",{className:"glass p-4 rounded-xl space-y-3",children:[u.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[u.jsx("select",{value:h,onChange:S=>p(S.target.value),className:"bg-black/20 border border-border/5 rounded-xl py-2 px-3 text-sm focus:border-primary/30 outline-none transition-all",children:Object.keys(Ur).map(S=>u.jsx("option",{value:S,children:Ur[S].name},S))}),u.jsx("input",{type:"text",value:l,onChange:S=>d(S.target.value),placeholder:"/path/to/browser/History",className:"col-span-2 bg-black/20 border border-border/5 rounded-xl py-2 px-3 text-sm focus:border-primary/30 outline-none transition-all"})]}),u.jsxs("button",{onClick:b,disabled:!l.trim()||m,className:"w-full py-2.5 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg hover:scale-[1.01] active:scale-95 transition-all flex items-center justify-center gap-2 disabled:opacity-50 disabled:grayscale",children:[m?u.jsx(Et,{size:16,className:"animate-spin"}):u.jsx(Hh,{size:16}),m?"Validating...":"Add Custom Source"]})]})]}),e.length>0&&u.jsxs("div",{className:"space-y-3",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40",children:["Configured Sources (",e.length,")"]}),u.jsx("div",{className:"space-y-2",children:u.jsx(Pt,{children:e.map((S,E)=>u.jsxs(ze.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},exit:{opacity:0,x:20},className:`glass p-4 rounded-xl border border-border/10 flex items-center justify-between ${!S.enabled&&"opacity-50"}`,children:[u.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[u.jsx("div",{className:Ur[S.browser].color,children:Ur[S.browser].icon}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("p",{className:"text-sm font-bold",children:S.label}),u.jsx("p",{className:"text-[10px] font-mono text-fg/40 truncate",children:S.path})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:()=>_(E),className:`px-3 py-1.5 text-xs font-bold uppercase tracking-widest rounded-lg transition-all ${S.enabled?"bg-success/10 text-success":"bg-fg/5 text-fg/40"}`,children:S.enabled?"Enabled":"Disabled"}),u.jsx("button",{onClick:()=>k(E),className:"p-2 hover:bg-error/10 text-error rounded-lg transition-all",children:u.jsx(wn,{size:16})})]})]},`${S.browser}-${S.path}`))})})]})]})}const fb=T.createContext(void 0);function TP({children:e}){const[t,n]=T.useState([]),r=T.useCallback((o,a="info")=>{const l=Math.random().toString(36).substr(2,9),d={id:l,type:a,message:o};n(h=>[...h,d]),setTimeout(()=>{n(h=>h.filter(p=>p.id!==l))},3e3)},[]);return u.jsxs(fb.Provider,{value:{showToast:r},children:[e,u.jsx(AP,{toasts:t})]})}function yc(){const e=T.useContext(fb);if(!e)throw new Error("useToast must be used within ToastProvider");return e}function AP({toasts:e}){return u.jsx("div",{className:"fixed bottom-6 right-6 z-[100] flex flex-col gap-2 pointer-events-none",children:u.jsx(Pt,{children:e.map(t=>u.jsx(PP,{toast:t},t.id))})})}function PP({toast:e}){const t={success:u.jsx(pi,{size:18,className:"text-success"}),error:u.jsx(wn,{size:18,className:"text-error"}),warning:u.jsx(pr,{size:18,className:"text-accent"}),info:u.jsx(K0,{size:18,className:"text-primary"})},n={success:"border-success/20 bg-success/10",error:"border-error/20 bg-error/10",warning:"border-accent/20 bg-accent/10",info:"border-primary/20 bg-primary/10"};return u.jsxs(ze.div,{initial:{opacity:0,y:20,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,x:100,scale:.95},className:`glass px-4 py-3 rounded-xl border ${n[e.type]} flex items-center gap-3 min-w-[300px] max-w-md pointer-events-auto shadow-lg`,children:[t[e.type],u.jsx("span",{className:"text-sm font-medium flex-1",children:e.message})]})}const pb=new Set(["login","log in","log-in","signin","sign in","sign-in","signup","sign up","sign-up","authentication","auth","password","register","registration","oauth","sso","navigation","menu","footer","header","sidebar","nav","breadcrumb","cookie","cookies","consent","privacy","terms","sitemap","ui","ux","user interface","interface","button","form","modal","popup","banner","facebook","meta","instagram","twitter","x","linkedin","tiktok","youtube","google","google drive","gmail","apple","icloud","microsoft","office","outlook","teams","pinterest","reddit","whatsapp","messenger","slack","discord","zoom","dropbox","notion","figma","github","gitlab","social media","social network","social","share","like","follow","post","error","not found","404","403","500","access denied","no content","empty","page not found","unavailable","blocked","forbidden","unauthorized","website","web page","webpage","page","site","web","app","application","download","install","home","homepage","main","index","default","about","contact","help","support","faq","blog","news","article"]);function RP(){const{showToast:e}=yc(),[t,n]=T.useState("http://localhost:11434"),[r,o]=T.useState("llama3"),[a,l]=T.useState("realtimexai"),[d,h]=T.useState("gpt-4o"),[p,m]=T.useState(""),[y,x]=T.useState([]),[w,b]=T.useState([]),[_,k]=T.useState([]),[S,E]=T.useState("text-embedding-3-small"),[N,R]=T.useState("realtimexai"),[M,O]=T.useState(""),[q,V]=T.useState(""),[W,he]=T.useState(!1),[se,ie]=T.useState(!1),[ee,J]=T.useState(!1),[H,re]=T.useState(!1),[ae,K]=T.useState(!1),[ue,C]=T.useState(!1),[D,G]=T.useState(null),[A,ce]=T.useState([]),[ye,pe]=T.useState([]);T.useEffect(()=>{me(),Ae(),Ee()},[]);const me=async()=>{const{data:{user:Q}}=await ne.auth.getUser();if(!Q)return;const{data:be}=await ne.from("alchemy_settings").select("*").eq("user_id",Q.id).maybeSingle();if(be){n(be.llm_base_url||be.ollama_host||"http://localhost:11434"),o(be.llm_model_name||"llama3"),l(be.llm_provider||"realtimexai"),h(be.llm_model||"gpt-4o-mini"),m(be.llm_api_key||be.openai_api_key||be.anthropic_api_key||""),x(be.custom_browser_paths||[]),b(be.blacklist_domains||[]);const F=be.blocked_tags||[];F.length>0?k(F):k(Array.from(pb)),E(be.embedding_model||"text-embedding-3-small"),R(be.embedding_provider||"realtimexai"),O(be.embedding_base_url||""),V(be.embedding_api_key||"")}else{l("realtimexai"),h("gpt-4o-mini"),R("realtimexai"),E("text-embedding-3-small");const F=new Date(Date.now()-720*60*60*1e3).toISOString();await ne.from("alchemy_settings").insert({user_id:Q.id,llm_provider:"realtimexai",llm_model:"gpt-4o-mini",embedding_provider:"realtimexai",embedding_model:"text-embedding-3-small",max_urls_per_sync:50,sync_mode:"incremental",sync_start_date:F})}},Ae=async()=>{try{const[Q,be]=await Promise.all([Ke.get("/api/sdk/providers/chat",{timeout:5e3}),Ke.get("/api/sdk/providers/embed",{timeout:5e3})]);Q.data.success&&be.data.success&&(G({chat:Q.data.providers,embed:be.data.providers}),C(!0),Ge("realtimexai",Q.data.providers),$e("realtimexai",be.data.providers),console.log("[AlchemistEngine] SDK providers loaded"),console.log(" Chat providers:",Q.data.providers.map(F=>F.provider)),console.log(" Embed providers:",be.data.providers.map(F=>F.provider)))}catch{console.log("[AlchemistEngine] SDK not available, using hardcoded configuration"),C(!1)}},$e=(Q,be)=>{if(be&&Array.isArray(be)){const Y=be.find(ve=>ve.provider===Q);if(Y&&Y.models){const ve=Y.models.map(Pe=>Pe.id);console.log(`[AlchemistEngine] Using SDK embedding models for ${Q}:`,ve),ce(ve);return}}console.log(`[AlchemistEngine] Using hardcoded embedding models for ${Q}`);const F=[];Q==="realtimexai"||Q==="openai"?F.push("text-embedding-3-small","text-embedding-3-large","text-embedding-ada-002"):Q==="gemini"&&F.push("embedding-001"),ce(F)},Ge=(Q,be)=>{if(be&&Array.isArray(be)){const Y=be.find(ve=>ve.provider===Q);if(Y&&Y.models){const ve=Y.models.map(Pe=>Pe.id);console.log(`[AlchemistEngine] Using SDK chat models for ${Q}:`,ve),pe(ve);return}}console.log(`[AlchemistEngine] Using hardcoded chat models for ${Q}`);const F=[];Q==="realtimexai"||Q==="openai"?F.push("gpt-4o","gpt-4o-mini","gpt-4-turbo","gpt-3.5-turbo"):Q==="anthropic"?F.push("claude-3-5-sonnet-20241022","claude-3-5-haiku-20241022","claude-3-opus-20240229"):Q==="google"?F.push("gemini-2.0-flash-exp","gemini-1.5-pro","gemini-1.5-flash"):Q==="ollama"&&F.push("llama3","mistral","codellama","phi"),pe(F)},Kt=async()=>{he(!0);try{const{data:{user:Q}}=await ne.auth.getUser();if(!Q){e("Please log in to save settings","error"),he(!1);return}const{error:be}=await ne.from("alchemy_settings").upsert({user_id:Q.id,llm_provider:a,llm_model:d,llm_base_url:t,llm_model_name:r,llm_api_key:p,embedding_model:S,embedding_provider:N,embedding_base_url:M,embedding_api_key:q,customized_at:new Date().toISOString()},{onConflict:"user_id"});be?(console.error("[AlchemistEngine] Save error:",be),e(`Failed to save: ${be.message}`,"error")):e("LLM settings saved successfully","success")}catch(Q){console.error("[AlchemistEngine] Unexpected error:",Q),e(`Unexpected error: ${Q.message}`,"error")}finally{he(!1)}},vr=async()=>{ie(!0);try{const{data:{user:Q}}=await ne.auth.getUser();if(!Q){e("Please log in to save settings","error"),ie(!1);return}const{error:be}=await ne.from("alchemy_settings").upsert({user_id:Q.id,custom_browser_paths:y},{onConflict:"user_id"});be?(console.error("[AlchemistEngine] Save browser sources error:",be),e(`Failed to save: ${be.message}`,"error")):e("Browser sources saved successfully","success")}catch(Q){console.error("[AlchemistEngine] Unexpected error:",Q),e(`Unexpected error: ${Q.message}`,"error")}finally{ie(!1)}},Rn=async()=>{J(!0);try{const{data:{user:Q}}=await ne.auth.getUser();if(!Q){e("Please log in to save settings","error"),J(!1);return}const be=w.filter(Y=>Y.trim().length>0),{error:F}=await ne.from("alchemy_settings").upsert({user_id:Q.id,blacklist_domains:be},{onConflict:"user_id"});F?(console.error("[AlchemistEngine] Save blacklist error:",F),e(`Failed to save: ${F.message}`,"error")):(e("Blacklist updated successfully","success"),await me())}catch(Q){console.error("[AlchemistEngine] Unexpected error:",Q),e(`Unexpected error: ${Q.message}`,"error")}finally{J(!1)}},rr=async()=>{re(!0);try{const{data:{user:Q}}=await ne.auth.getUser();if(!Q){e("Please log in to save settings","error"),re(!1);return}const be=_.filter(Y=>Y.trim().length>0),{error:F}=await ne.from("alchemy_settings").upsert({user_id:Q.id,blocked_tags:be},{onConflict:"user_id"});F?(console.error("[AlchemistEngine] Save blocked tags error:",F),e(`Failed to save: ${F.message}`,"error")):(e("Blocked tags updated successfully","success"),await me())}catch(Q){console.error("[AlchemistEngine] Unexpected error:",Q),e(`Unexpected error: ${Q.message}`,"error")}finally{re(!1)}},[Hn,de]=T.useState(""),[_e,Me]=T.useState(""),[Te,Ve]=T.useState(!1),Ee=async()=>{const{data:{user:Q}}=await ne.auth.getUser();if(!Q)return;const{data:be}=await ne.from("user_persona").select("*").eq("user_id",Q.id).maybeSingle();be&&(de(be.interest_summary||""),Me(be.anti_patterns||""))},Qe=async()=>{Ve(!0);try{const{data:{user:Q}}=await ne.auth.getUser();if(!Q){e("Please log in to save persona","error"),Ve(!1);return}const{error:be}=await ne.from("user_persona").upsert({user_id:Q.id,interest_summary:Hn,anti_patterns:_e,last_updated_at:new Date().toISOString()},{onConflict:"user_id"});be?(console.error("[AlchemistEngine] Save persona error:",be),e(`Failed to save: ${be.message}`,"error")):e("Persona updated successfully","success")}catch(Q){console.error("[AlchemistEngine] Unexpected error:",Q),e(`Unexpected error: ${Q.message}`,"error")}finally{Ve(!1)}},ht=async()=>{K(!0);try{const{data:Q}=await Ke.post("/api/llm/test",{baseUrl:t,modelName:r,apiKey:p});Q.success?e(`Connection successful! ${Q.model?`Model: ${Q.model}`:""}`,"success"):e(`Connection failed: ${Q.message}`,"error")}catch(Q){console.error("[AlchemistEngine] Test error:",Q),e(`Test failed: ${Q.message}`,"error")}finally{K(!1)}};return u.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[u.jsxs("header",{className:"px-8 py-6 border-b border-border",children:[u.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Intelligence Engine"}),u.jsx("p",{className:"text-sm text-fg/50 font-medium",children:"Fine-tune the Alchemist's cognitive parameters and provider links."})]}),u.jsx("main",{className:"flex-1 overflow-y-auto custom-scrollbar p-8",children:u.jsxs("div",{className:"max-w-7xl mx-auto animate-in fade-in slide-in-from-bottom-2 duration-500",children:[u.jsxs("section",{className:"space-y-6 mb-8",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[u.jsx(W0,{size:14})," AI Configuration"]}),u.jsxs("div",{className:"flex gap-3",children:[u.jsxs("button",{onClick:ht,disabled:ae||W,className:"px-6 py-3 bg-surface hover:bg-surface/80 border border-border text-fg font-bold rounded-xl shadow-sm hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[ae?u.jsx(Et,{size:18,className:"animate-spin"}):u.jsx(Yt,{size:18,className:"text-accent"}),"Test Connection"]}),u.jsxs("button",{onClick:Kt,disabled:W,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[W?u.jsx(Et,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Save Configuration"]})]})]}),u.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[u.jsxs("div",{className:"glass p-6 space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2",children:[u.jsx("h3",{className:"text-sm font-semibold text-fg/80",children:"LLM Provider"}),ue?u.jsxs("span",{className:"text-xs text-green-500 flex items-center gap-1",children:[u.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full"}),"SDK Connected"]}):u.jsxs("span",{className:"text-xs text-orange-500 flex items-center gap-1",children:[u.jsx("span",{className:"w-2 h-2 bg-orange-500 rounded-full"}),"SDK Not Available"]})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-xs font-medium text-fg/60",children:"Provider"}),u.jsxs("select",{value:a,onChange:Q=>{l(Q.target.value),Ge(Q.target.value,D)},className:"w-full px-4 py-3 bg-surface border border-border rounded-xl text-fg focus:outline-none focus:ring-2 focus:ring-primary/50",children:[u.jsx("option",{value:"realtimexai",children:"RealTimeX.AI"}),u.jsx("option",{value:"openai",children:"OpenAI"}),u.jsx("option",{value:"anthropic",children:"Anthropic"}),u.jsx("option",{value:"google",children:"Google"}),u.jsx("option",{value:"ollama",children:"Ollama"})]})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-xs font-medium text-fg/60",children:"Intelligence Model"}),u.jsx("select",{value:d,onChange:Q=>h(Q.target.value),className:"w-full px-4 py-3 bg-surface border border-border rounded-xl text-fg focus:outline-none focus:ring-2 focus:ring-primary/50",children:ye.length>0?ye.map(Q=>u.jsx("option",{value:Q,children:Q},Q)):u.jsxs(u.Fragment,{children:[u.jsx("option",{value:"gpt-4o",children:"gpt-4o"}),u.jsx("option",{value:"gpt-4o-mini",children:"gpt-4o-mini"}),u.jsx("option",{value:"gpt-4-turbo",children:"gpt-4-turbo"})]})})]}),u.jsx("div",{className:"p-3 bg-primary/5 rounded-xl",children:u.jsx("p",{className:"text-[10px] text-primary/60 font-medium leading-relaxed",children:ue?"✓ Using RealTimeX configured provider":"⚠️ RealTimeX SDK not detected. Configure in RealTimeX Desktop."})})]}),u.jsxs("div",{className:"glass p-6 space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2",children:[u.jsx("h3",{className:"text-sm font-semibold text-fg/80",children:"Embedding Provider"}),ue?u.jsxs("span",{className:"text-xs text-green-500 flex items-center gap-1",children:[u.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full"}),"SDK Connected"]}):u.jsxs("span",{className:"text-xs text-orange-500 flex items-center gap-1",children:[u.jsx("span",{className:"w-2 h-2 bg-orange-500 rounded-full"}),"SDK Not Available"]})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-xs font-medium text-fg/60",children:"Provider"}),u.jsxs("select",{value:N,onChange:Q=>{R(Q.target.value),$e(Q.target.value,D)},className:"w-full px-4 py-3 bg-surface border border-border rounded-xl text-fg focus:outline-none focus:ring-2 focus:ring-primary/50",children:[u.jsx("option",{value:"realtimexai",children:"RealTimeX.AI"}),u.jsx("option",{value:"openai",children:"OpenAI"}),u.jsx("option",{value:"gemini",children:"Gemini"})]})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-xs font-medium text-fg/60",children:"Embedding Model"}),u.jsx("select",{value:S,onChange:Q=>E(Q.target.value),className:"w-full px-4 py-3 bg-surface border border-border rounded-xl text-fg focus:outline-none focus:ring-2 focus:ring-primary/50",children:A.length>0?A.map(Q=>u.jsx("option",{value:Q,children:Q},Q)):u.jsxs(u.Fragment,{children:[u.jsx("option",{value:"text-embedding-3-small",children:"text-embedding-3-small"}),u.jsx("option",{value:"text-embedding-3-large",children:"text-embedding-3-large"}),u.jsx("option",{value:"text-embedding-ada-002",children:"text-embedding-ada-002"})]})})]}),u.jsx("div",{className:"p-3 bg-primary/5 rounded-xl",children:u.jsx("p",{className:"text-[10px] text-primary/60 font-medium leading-relaxed",children:ue?"✓ Embeddings are generated using your RealTimeX configured provider":"⚠️ RealTimeX SDK not detected. Configure providers in RealTimeX Desktop."})})]})]})]}),u.jsxs("section",{className:"space-y-6 mb-8",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[u.jsx("span",{className:"text-xl",children:"🧠"})," Persona Memory"]}),u.jsxs("button",{onClick:Qe,disabled:Te,className:"px-6 py-3 bg-surface hover:bg-surface/80 border border-border text-fg font-bold rounded-xl shadow-sm hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[Te?u.jsx(Et,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Save Memory"]})]}),u.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[u.jsxs("div",{className:"glass p-6 space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2",children:[u.jsx("h3",{className:"text-sm font-semibold text-fg/80",children:"Active Interests"}),u.jsx("span",{className:"text-xs text-green-500 bg-green-500/10 px-2 py-1 rounded-full border border-green-500/20",children:"High Priority"})]}),u.jsx("p",{className:"text-xs text-fg/50 leading-relaxed",children:"The Alchemist prioritizes content matching these topics. Updated automatically based on Favorites & Boosts."}),u.jsx("textarea",{value:Hn,onChange:Q=>de(Q.target.value),placeholder:"e.g. User focuses on React performance, Rust backend systems, and AI Agent architecture...",className:"w-full h-32 px-4 py-3 bg-surface border border-border rounded-xl text-sm text-fg placeholder:text-fg/40 focus:outline-none focus:ring-2 focus:ring-green-500/30 resize-none"})]}),u.jsxs("div",{className:"glass p-6 space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2",children:[u.jsx("h3",{className:"text-sm font-semibold text-fg/80",children:"Anti-Patterns"}),u.jsx("span",{className:"text-xs text-red-400 bg-red-500/10 px-2 py-1 rounded-full border border-red-500/20",children:"Avoid"})]}),u.jsx("p",{className:"text-xs text-fg/50 leading-relaxed",children:"The Alchemist filters out or scores down content matching these patterns. Updated via Dismissals."}),u.jsx("textarea",{value:_e,onChange:Q=>Me(Q.target.value),placeholder:"e.g. Dislikes marketing fluff, generic listicles, and crypto hype...",className:"w-full h-32 px-4 py-3 bg-surface border border-border rounded-xl text-sm text-fg placeholder:text-fg/40 focus:outline-none focus:ring-2 focus:ring-red-500/30 resize-none"})]})]})]}),u.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[u.jsx("section",{className:"space-y-6",children:u.jsxs("div",{className:"space-y-4",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[u.jsx(zo,{size:14})," Browser History Sources"]}),u.jsxs("div",{className:"glass p-8 space-y-6",children:[u.jsx(CP,{sources:y,onChange:x}),u.jsx("div",{className:"flex justify-end pt-2",children:u.jsxs("button",{onClick:vr,disabled:se,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[se?u.jsx(Et,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Save Browser Sources"]})})]})]})}),u.jsx("section",{className:"space-y-6",children:u.jsxs("div",{className:"space-y-4",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[u.jsx(Yt,{size:14})," Blacklist Domains"]}),u.jsxs("div",{className:"glass p-8 space-y-6",children:[u.jsx("div",{className:"space-y-2",children:u.jsx("p",{className:"text-sm text-fg/60",children:"URLs containing these patterns will be skipped during mining. Enter one pattern per line."})}),u.jsxs("div",{className:"space-y-2",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Domain Patterns (one per line)"}),u.jsx("textarea",{value:w.join(`
|
|
70
|
+
`).filter(re=>re.startsWith("data: "));for(const re of H)try{const ae=JSON.parse(re.slice(6));ae.type==="done"?ae.data==="success"?(R("success"),o("success"),setTimeout(()=>{window.location.reload()},2e3)):(R("failed"),b("Migration failed. Check logs for details.")):E(K=>[...K,ae.data])}catch{}}}catch(W){R("failed"),b(W.message||"Migration failed"),E(he=>[...he,`Error: ${W.message}`])}},V=()=>{o("success"),setTimeout(()=>{window.location.reload()},1500)};return u.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-6 bg-bg/80 backdrop-blur-sm",children:u.jsxs(ze.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:"w-full max-w-lg glass p-8 space-y-8 relative overflow-hidden",children:[u.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-primary/10 rounded-full blur-3xl -translate-y-1/2 translate-x-1/2"}),u.jsxs(Pt,{mode:"wait",children:[r==="welcome"&&u.jsxs(ze.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},className:"space-y-6",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"p-2 bg-primary/10 rounded-xl",children:u.jsx(zo,{className:"w-6 h-6 text-primary"})}),u.jsx("h2",{className:"text-2xl font-black italic tracking-tighter uppercase",children:"Assemble Your Engine"})]}),u.jsx("p",{className:"text-sm text-fg/50 font-medium",children:"Alchemy requires a Supabase essence to store signal fragments and intelligence patterns."})]}),u.jsxs("div",{className:"glass bg-white/5 border-white/10 p-4 rounded-xl space-y-3",children:[u.jsx("p",{className:"text-xs font-bold uppercase tracking-widest text-primary/70",children:"Requirements:"}),u.jsxs("ul",{className:"space-y-2",children:[u.jsxs("li",{className:"flex items-center gap-2 text-sm text-fg/60",children:[u.jsx(pi,{className:"w-4 h-4 text-emerald-500"})," Supabase Project URL"]}),u.jsxs("li",{className:"flex items-center gap-2 text-sm text-fg/60",children:[u.jsx(pi,{className:"w-4 h-4 text-emerald-500"})," Anon Public API Key"]}),u.jsxs("li",{className:"flex items-center gap-2 text-sm text-fg/60",children:[u.jsx(pi,{className:"w-4 h-4 text-emerald-500"})," Access Token (for migrations)"]})]})]}),u.jsxs("div",{className:"flex flex-col gap-3",children:[u.jsxs("a",{href:"https://supabase.com",target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center gap-2 py-3 border border-border/20 rounded-xl text-xs font-bold uppercase tracking-widest hover:bg-white/5 transition-all text-fg/60",children:["Forge Project at Supabase ",u.jsx(Ei,{size:14})]}),u.jsxs("button",{onClick:()=>o("credentials"),className:"w-full py-4 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.01] active:scale-95 transition-all flex items-center justify-center gap-2",children:["BEGIN INITIALIZATION ",u.jsx(aS,{size:18})]})]})]},"welcome"),r==="credentials"&&u.jsxs(ze.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},className:"space-y-6",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx("h2",{className:"text-2xl font-black italic tracking-tighter uppercase",children:"Essence Coordinates"}),u.jsx("p",{className:"text-sm text-fg/50 font-medium lowercase",children:"Link the alchemist engine to your cloud database"})]}),u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Project URL or ID"}),u.jsx("input",{type:"text",value:a,onChange:W=>l(W.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 px-4 text-sm focus:border-primary/50 outline-none transition-all",placeholder:"https://xxx.supabase.co or project-id"})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Anon Public Key"}),u.jsx("input",{type:"password",value:d,onChange:W=>h(W.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 px-4 text-sm focus:border-primary/50 outline-none transition-all",placeholder:"eyJ..."})]})]}),w&&u.jsxs("div",{className:"bg-error/10 border border-error/20 p-3 rounded-xl flex items-center gap-3",children:[u.jsx(pr,{className:"w-5 h-5 text-error"}),u.jsx("p",{className:"text-xs text-error font-bold tracking-tight",children:w})]}),u.jsxs("div",{className:"flex gap-3",children:[u.jsx("button",{onClick:()=>o("welcome"),className:"flex-1 py-4 border border-border/20 rounded-xl text-xs font-bold uppercase tracking-widest hover:bg-white/5 transition-all text-fg/40",children:"BACK"}),u.jsxs("button",{onClick:O,disabled:!a||!d,className:"flex-[2] py-4 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.01] active:scale-95 transition-all disabled:opacity-50 disabled:grayscale flex items-center justify-center gap-2",children:["CONNECT ESSENCE ",u.jsx(Yt,{size:18})]})]})]},"credentials"),r==="validating"&&u.jsxs(ze.div,{initial:{opacity:0},animate:{opacity:1},className:"flex flex-col items-center justify-center py-12 space-y-6",children:[u.jsxs("div",{className:"relative",children:[u.jsx("div",{className:"absolute inset-0 bg-primary/20 blur-xl rounded-full"}),u.jsx(Et,{className:"w-16 h-16 animate-spin text-primary relative z-10"})]}),u.jsxs("div",{className:"text-center space-y-2",children:[u.jsx("h3",{className:"text-xl font-bold italic uppercase tracking-tighter",children:"Validating Link"}),u.jsx("p",{className:"text-sm text-fg/40 font-mono tracking-widest uppercase animate-pulse",children:"Synchronizing Resonance..."})]})]},"validating"),r==="migration"&&u.jsxs(ze.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},className:"space-y-6",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"p-2 bg-accent/10 rounded-xl",children:u.jsx(zl,{className:"w-6 h-6 text-accent"})}),u.jsx("h2",{className:"text-2xl font-black italic tracking-tighter uppercase",children:"Initialize Schema"})]}),u.jsx("p",{className:"text-sm text-fg/50 font-medium",children:"Run database migrations to set up required tables and functions."})]}),u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Project ID"}),u.jsx("input",{type:"text",value:p,onChange:W=>m(W.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 px-4 text-sm focus:border-primary/50 outline-none transition-all font-mono",placeholder:"abcdefghijklm"}),u.jsx("p",{className:"text-[10px] text-fg/30 ml-1",children:"Found in Supabase Dashboard → Project Settings → General"})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Access Token"}),u.jsx("input",{type:"password",value:y,onChange:W=>x(W.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 px-4 text-sm focus:border-primary/50 outline-none transition-all font-mono",placeholder:"sbp_..."}),u.jsxs("p",{className:"text-[10px] text-fg/30 ml-1",children:["Generate at"," ",u.jsx("a",{href:"https://supabase.com/dashboard/account/tokens",target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:underline",children:"supabase.com/dashboard/account/tokens"})]})]})]}),w&&u.jsxs("div",{className:"bg-error/10 border border-error/20 p-3 rounded-xl flex items-center gap-3",children:[u.jsx(pr,{className:"w-5 h-5 text-error"}),u.jsx("p",{className:"text-xs text-error font-bold tracking-tight",children:w})]}),u.jsxs("div",{className:"flex gap-3",children:[u.jsx("button",{onClick:V,className:"flex-1 py-4 border border-border/20 rounded-xl text-xs font-bold uppercase tracking-widest hover:bg-white/5 transition-all text-fg/40",children:"SKIP"}),u.jsxs("button",{onClick:q,disabled:!p||!y,className:"flex-[2] py-4 bg-gradient-to-r from-accent to-primary text-white font-bold rounded-xl shadow-lg glow-accent hover:scale-[1.01] active:scale-95 transition-all disabled:opacity-50 disabled:grayscale flex items-center justify-center gap-2",children:[u.jsx(RS,{size:18})," RUN MIGRATIONS"]})]})]},"migration"),r==="migrating"&&u.jsxs(ze.div,{initial:{opacity:0},animate:{opacity:1},className:"space-y-6",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx(Et,{className:"w-6 h-6 animate-spin text-accent"}),u.jsx("h2",{className:"text-xl font-black italic tracking-tighter uppercase",children:"Running Migrations"})]}),u.jsx("p",{className:"text-sm text-fg/40",children:"This may take a minute..."})]}),u.jsxs("div",{className:"bg-black/40 border border-border/20 rounded-xl p-4 h-64 overflow-y-auto font-mono text-xs",children:[S.map((W,he)=>u.jsx("div",{className:`py-0.5 ${W.includes("✅")||W.includes("SUCCESS")?"text-emerald-400":W.includes("❌")||W.includes("Error")?"text-red-400":W.includes("⚠️")?"text-amber-400":"text-fg/60"}`,children:W},he)),u.jsx("div",{ref:M})]}),N==="failed"&&u.jsxs("div",{className:"flex gap-3",children:[u.jsxs("button",{onClick:()=>o("migration"),className:"flex-1 py-3 border border-border/20 rounded-xl text-xs font-bold uppercase tracking-widest hover:bg-white/5 transition-all text-fg/40",children:[u.jsx(B0,{size:14,className:"inline mr-2"})," BACK"]}),u.jsx("button",{onClick:q,className:"flex-1 py-3 bg-accent/20 border border-accent/30 rounded-xl text-xs font-bold uppercase tracking-widest hover:bg-accent/30 transition-all text-accent",children:"RETRY"})]})]},"migrating"),r==="success"&&u.jsxs(ze.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},className:"flex flex-col items-center justify-center py-12 space-y-6",children:[u.jsx("div",{className:"p-4 bg-emerald-500/20 rounded-full",children:u.jsx(vs,{className:"w-16 h-16 text-emerald-500"})}),u.jsxs("div",{className:"text-center space-y-2",children:[u.jsx("h3",{className:"text-2xl font-black italic uppercase tracking-tighter",children:"Engine Aligned"}),u.jsx("p",{className:"text-sm text-fg/40 font-mono tracking-widest uppercase",children:"Restarting Alchemist Subsystems..."})]})]},"success")]})]})})}const Ur={chrome:{icon:u.jsx(yS,{size:18}),name:"Google Chrome",color:"text-yellow-500"},firefox:{icon:u.jsx(dd,{size:18}),name:"Mozilla Firefox",color:"text-orange-500"},safari:{icon:u.jsx(dd,{size:18}),name:"Safari",color:"text-blue-500"},edge:{icon:u.jsx(dd,{size:18}),name:"Microsoft Edge",color:"text-cyan-500"},brave:{icon:u.jsx(Yt,{size:18}),name:"Brave",color:"text-orange-400"},arc:{icon:u.jsx(Yt,{size:18}),name:"Arc",color:"text-purple-500"}};function CP({sources:e,onChange:t}){const[n,r]=T.useState(!1),[o,a]=T.useState({}),[l,d]=T.useState(""),[h,p]=T.useState("chrome"),[m,y]=T.useState(!1),x=async()=>{r(!0);try{const{data:S}=await Ke.get("/api/browser-paths/detect");a(S)}catch(S){console.error("Detection failed:",S)}finally{r(!1)}},w=S=>{const E=o[S];if(!E||!E.found||!E.valid||e.find(M=>M.browser===S&&M.path===E.path))return;const R={browser:S,path:E.path,enabled:!0,label:`${Ur[S].name} (Auto-detected)`};t([...e,R])},b=async()=>{if(l.trim()){y(!0);try{const{data:S}=await Ke.post("/api/browser-paths/validate",{path:l});if(!S.valid){alert(`Invalid path: ${S.error||"Not a browser history database"}`),y(!1);return}const E={browser:h,path:l,enabled:!0,label:`${Ur[h].name} (Custom)`};t([...e,E]),d("")}catch(S){console.error("Validation failed:",S),alert("Failed to validate path")}finally{y(!1)}}},_=S=>{const E=[...e];E[S].enabled=!E[S].enabled,t(E)},k=S=>{t(e.filter((E,N)=>N!==S))};return u.jsxs("div",{className:"space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[u.jsx(Ll,{size:14})," Auto-Detect Browsers"]}),u.jsxs("button",{onClick:x,disabled:n,className:"px-3 py-1.5 text-xs font-bold uppercase tracking-widest bg-primary/10 hover:bg-primary/20 text-primary rounded-lg transition-all flex items-center gap-2",children:[n?u.jsx(Et,{size:12,className:"animate-spin"}):u.jsx(Ll,{size:12}),n?"Scanning...":"Scan System"]})]}),Object.keys(o).length>0&&u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:Object.keys(Ur).map(S=>{const E=o[S],N=Ur[S],R=e.some(M=>M.browser===S&&M.path===E?.path);return u.jsxs(ze.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:`glass p-4 rounded-xl border ${E?.found&&E?.valid?"border-success/20 bg-success/5":E?.found?"border-error/20 bg-error/5":"border-border/10"}`,children:[u.jsxs("div",{className:"flex items-start justify-between mb-2",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("div",{className:N.color,children:N.icon}),u.jsx("span",{className:"text-sm font-bold",children:N.name})]}),E?.found&&E?.valid?u.jsx(pi,{size:16,className:"text-success"}):E?.found?u.jsx(pr,{size:16,className:"text-error"}):u.jsx(wn,{size:16,className:"text-fg/20"})]}),E?.found?u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"text-[10px] font-mono text-fg/40 truncate mb-2",children:E.path}),E.valid?u.jsx("button",{onClick:()=>w(S),disabled:R,className:`w-full py-1.5 text-xs font-bold uppercase tracking-widest rounded-lg transition-all ${R?"bg-fg/5 text-fg/30 cursor-not-allowed":"bg-success/10 hover:bg-success/20 text-success"}`,children:R?"Already Added":"Add Source"}):u.jsx("p",{className:"text-[10px] text-error font-medium",children:E.error})]}):u.jsx("p",{className:"text-[10px] text-fg/30 italic",children:"Not found on this system"})]},S)})})]}),u.jsxs("div",{className:"space-y-3",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[u.jsx(wS,{size:14})," Add Custom Path"]}),u.jsxs("div",{className:"glass p-4 rounded-xl space-y-3",children:[u.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[u.jsx("select",{value:h,onChange:S=>p(S.target.value),className:"bg-black/20 border border-border/5 rounded-xl py-2 px-3 text-sm focus:border-primary/30 outline-none transition-all",children:Object.keys(Ur).map(S=>u.jsx("option",{value:S,children:Ur[S].name},S))}),u.jsx("input",{type:"text",value:l,onChange:S=>d(S.target.value),placeholder:"/path/to/browser/History",className:"col-span-2 bg-black/20 border border-border/5 rounded-xl py-2 px-3 text-sm focus:border-primary/30 outline-none transition-all"})]}),u.jsxs("button",{onClick:b,disabled:!l.trim()||m,className:"w-full py-2.5 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg hover:scale-[1.01] active:scale-95 transition-all flex items-center justify-center gap-2 disabled:opacity-50 disabled:grayscale",children:[m?u.jsx(Et,{size:16,className:"animate-spin"}):u.jsx(Hh,{size:16}),m?"Validating...":"Add Custom Source"]})]})]}),e.length>0&&u.jsxs("div",{className:"space-y-3",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40",children:["Configured Sources (",e.length,")"]}),u.jsx("div",{className:"space-y-2",children:u.jsx(Pt,{children:e.map((S,E)=>u.jsxs(ze.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},exit:{opacity:0,x:20},className:`glass p-4 rounded-xl border border-border/10 flex items-center justify-between ${!S.enabled&&"opacity-50"}`,children:[u.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[u.jsx("div",{className:Ur[S.browser].color,children:Ur[S.browser].icon}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("p",{className:"text-sm font-bold",children:S.label}),u.jsx("p",{className:"text-[10px] font-mono text-fg/40 truncate",children:S.path})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:()=>_(E),className:`px-3 py-1.5 text-xs font-bold uppercase tracking-widest rounded-lg transition-all ${S.enabled?"bg-success/10 text-success":"bg-fg/5 text-fg/40"}`,children:S.enabled?"Enabled":"Disabled"}),u.jsx("button",{onClick:()=>k(E),className:"p-2 hover:bg-error/10 text-error rounded-lg transition-all",children:u.jsx(wn,{size:16})})]})]},`${S.browser}-${S.path}`))})})]})]})}const fb=T.createContext(void 0);function TP({children:e}){const[t,n]=T.useState([]),r=T.useCallback((o,a="info")=>{const l=Math.random().toString(36).substr(2,9),d={id:l,type:a,message:o};n(h=>[...h,d]),setTimeout(()=>{n(h=>h.filter(p=>p.id!==l))},3e3)},[]);return u.jsxs(fb.Provider,{value:{showToast:r},children:[e,u.jsx(AP,{toasts:t})]})}function yc(){const e=T.useContext(fb);if(!e)throw new Error("useToast must be used within ToastProvider");return e}function AP({toasts:e}){return u.jsx("div",{className:"fixed bottom-6 right-6 z-[100] flex flex-col gap-2 pointer-events-none",children:u.jsx(Pt,{children:e.map(t=>u.jsx(PP,{toast:t},t.id))})})}function PP({toast:e}){const t={success:u.jsx(pi,{size:18,className:"text-success"}),error:u.jsx(wn,{size:18,className:"text-error"}),warning:u.jsx(pr,{size:18,className:"text-accent"}),info:u.jsx(K0,{size:18,className:"text-primary"})},n={success:"border-success/20 bg-success/10",error:"border-error/20 bg-error/10",warning:"border-accent/20 bg-accent/10",info:"border-primary/20 bg-primary/10"};return u.jsxs(ze.div,{initial:{opacity:0,y:20,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,x:100,scale:.95},className:`glass px-4 py-3 rounded-xl border ${n[e.type]} flex items-center gap-3 min-w-[300px] max-w-md pointer-events-auto shadow-lg`,children:[t[e.type],u.jsx("span",{className:"text-sm font-medium flex-1",children:e.message})]})}const pb=new Set(["login","log in","log-in","signin","sign in","sign-in","signup","sign up","sign-up","authentication","auth","password","register","registration","oauth","sso","navigation","menu","footer","header","sidebar","nav","breadcrumb","cookie","cookies","consent","privacy","terms","sitemap","ui","ux","user interface","interface","button","form","modal","popup","banner","facebook","meta","instagram","twitter","x","linkedin","tiktok","youtube","google","google drive","gmail","apple","icloud","microsoft","office","outlook","teams","pinterest","reddit","whatsapp","messenger","slack","discord","zoom","dropbox","notion","figma","github","gitlab","social media","social network","social","share","like","follow","post","error","not found","404","403","500","access denied","no content","empty","page not found","unavailable","blocked","forbidden","unauthorized","website","web page","webpage","page","site","web","app","application","download","install","home","homepage","main","index","default","about","contact","help","support","faq","blog","news","article"]);function RP(){const{showToast:e}=yc(),[t,n]=T.useState("http://localhost:11434"),[r,o]=T.useState("llama3"),[a,l]=T.useState("realtimexai"),[d,h]=T.useState("gpt-4o"),[p,m]=T.useState(""),[y,x]=T.useState([]),[w,b]=T.useState([]),[_,k]=T.useState([]),[S,E]=T.useState("text-embedding-3-small"),[N,R]=T.useState("realtimexai"),[M,O]=T.useState(""),[q,V]=T.useState(""),[W,he]=T.useState(!1),[se,ie]=T.useState(!1),[ee,J]=T.useState(!1),[H,re]=T.useState(!1),[ae,K]=T.useState(!1),[ue,C]=T.useState(!1),[D,G]=T.useState(null),[A,ce]=T.useState([]),[ye,pe]=T.useState([]);T.useEffect(()=>{me(),Ae(),Ee()},[]);const me=async()=>{const{data:{user:Q}}=await ne.auth.getUser();if(!Q)return;const{data:be}=await ne.from("alchemy_settings").select("*").eq("user_id",Q.id).maybeSingle();if(be){n(be.llm_base_url||be.ollama_host||"http://localhost:11434"),o(be.llm_model_name||"llama3"),l(be.llm_provider||"realtimexai"),h(be.llm_model||"gpt-4o-mini"),m(be.llm_api_key||be.openai_api_key||be.anthropic_api_key||""),x(be.custom_browser_paths||[]),b(be.blacklist_domains||[]);const F=be.blocked_tags||[];F.length>0?k(F):k(Array.from(pb)),E(be.embedding_model||"text-embedding-3-small"),R(be.embedding_provider||"realtimexai"),O(be.embedding_base_url||""),V(be.embedding_api_key||"")}else{l("realtimexai"),h("gpt-4o-mini"),R("realtimexai"),E("text-embedding-3-small");const F=new Date(Date.now()-720*60*60*1e3).toISOString();await ne.from("alchemy_settings").insert({user_id:Q.id,llm_provider:"realtimexai",llm_model:"gpt-4o-mini",embedding_provider:"realtimexai",embedding_model:"text-embedding-3-small",max_urls_per_sync:50,sync_mode:"incremental",sync_start_date:F})}},Ae=async()=>{try{const[Q,be]=await Promise.all([Ke.get("/api/sdk/providers/chat",{timeout:5e3}),Ke.get("/api/sdk/providers/embed",{timeout:5e3})]);Q.data.success&&be.data.success&&(G({chat:Q.data.providers,embed:be.data.providers}),C(!0),Ge("realtimexai",Q.data.providers),$e("realtimexai",be.data.providers),console.log("[AlchemistEngine] SDK providers loaded"),console.log(" Chat providers:",Q.data.providers.map(F=>F.provider)),console.log(" Embed providers:",be.data.providers.map(F=>F.provider)))}catch{console.log("[AlchemistEngine] SDK not available, using hardcoded configuration"),C(!1)}},$e=(Q,be)=>{if(be&&Array.isArray(be)){const Y=be.find(ve=>ve.provider===Q);if(Y&&Y.models){const ve=Y.models.map(Pe=>Pe.id);console.log(`[AlchemistEngine] Using SDK embedding models for ${Q}:`,ve),ce(ve);return}}console.log(`[AlchemistEngine] Using hardcoded embedding models for ${Q}`);const F=[];Q==="realtimexai"||Q==="openai"?F.push("text-embedding-3-small","text-embedding-3-large","text-embedding-ada-002"):Q==="gemini"&&F.push("embedding-001"),ce(F)},Ge=(Q,be)=>{if(be&&Array.isArray(be)){const Y=be.find(ve=>ve.provider===Q);if(Y&&Y.models){const ve=Y.models.map(Pe=>Pe.id);console.log(`[AlchemistEngine] Using SDK chat models for ${Q}:`,ve),pe(ve);return}}console.log(`[AlchemistEngine] Using hardcoded chat models for ${Q}`);const F=[];Q==="realtimexai"||Q==="openai"?F.push("gpt-4o","gpt-4o-mini","gpt-4-turbo","gpt-3.5-turbo"):Q==="anthropic"?F.push("claude-3-5-sonnet-20241022","claude-3-5-haiku-20241022","claude-3-opus-20240229"):Q==="google"?F.push("gemini-2.0-flash-exp","gemini-1.5-pro","gemini-1.5-flash"):Q==="ollama"&&F.push("llama3","mistral","codellama","phi"),pe(F)},Kt=async()=>{he(!0);try{const{data:{user:Q}}=await ne.auth.getUser();if(!Q){e("Please log in to save settings","error"),he(!1);return}const{error:be}=await ne.from("alchemy_settings").upsert({user_id:Q.id,llm_provider:a,llm_model:d,llm_base_url:t,llm_model_name:r,llm_api_key:p,embedding_model:S,embedding_provider:N,embedding_base_url:M,embedding_api_key:q,customized_at:new Date().toISOString()},{onConflict:"user_id"});be?(console.error("[AlchemistEngine] Save error:",be),e(`Failed to save: ${be.message}`,"error")):e("LLM settings saved successfully","success")}catch(Q){console.error("[AlchemistEngine] Unexpected error:",Q),e(`Unexpected error: ${Q.message}`,"error")}finally{he(!1)}},vr=async()=>{ie(!0);try{const{data:{user:Q}}=await ne.auth.getUser();if(!Q){e("Please log in to save settings","error"),ie(!1);return}const{error:be}=await ne.from("alchemy_settings").upsert({user_id:Q.id,custom_browser_paths:y},{onConflict:"user_id"});be?(console.error("[AlchemistEngine] Save browser sources error:",be),e(`Failed to save: ${be.message}`,"error")):e("Browser sources saved successfully","success")}catch(Q){console.error("[AlchemistEngine] Unexpected error:",Q),e(`Unexpected error: ${Q.message}`,"error")}finally{ie(!1)}},Rn=async()=>{J(!0);try{const{data:{user:Q}}=await ne.auth.getUser();if(!Q){e("Please log in to save settings","error"),J(!1);return}const be=w.filter(Y=>Y.trim().length>0),{error:F}=await ne.from("alchemy_settings").upsert({user_id:Q.id,blacklist_domains:be},{onConflict:"user_id"});F?(console.error("[AlchemistEngine] Save blacklist error:",F),e(`Failed to save: ${F.message}`,"error")):(e("Blacklist updated successfully","success"),await me())}catch(Q){console.error("[AlchemistEngine] Unexpected error:",Q),e(`Unexpected error: ${Q.message}`,"error")}finally{J(!1)}},rr=async()=>{re(!0);try{const{data:{user:Q}}=await ne.auth.getUser();if(!Q){e("Please log in to save settings","error"),re(!1);return}const be=_.filter(Y=>Y.trim().length>0),{error:F}=await ne.from("alchemy_settings").upsert({user_id:Q.id,blocked_tags:be},{onConflict:"user_id"});F?(console.error("[AlchemistEngine] Save blocked tags error:",F),e(`Failed to save: ${F.message}`,"error")):(e("Blocked tags updated successfully","success"),await me())}catch(Q){console.error("[AlchemistEngine] Unexpected error:",Q),e(`Unexpected error: ${Q.message}`,"error")}finally{re(!1)}},[Hn,de]=T.useState(""),[_e,Me]=T.useState(""),[Te,Ve]=T.useState(!1),Ee=async()=>{const{data:{user:Q}}=await ne.auth.getUser();if(!Q)return;const{data:be}=await ne.from("user_persona").select("*").eq("user_id",Q.id).maybeSingle();be&&(de(be.interest_summary||""),Me(be.anti_patterns||""))},Qe=async()=>{Ve(!0);try{const{data:{user:Q}}=await ne.auth.getUser();if(!Q){e("Please log in to save persona","error"),Ve(!1);return}const{error:be}=await ne.from("user_persona").upsert({user_id:Q.id,interest_summary:Hn,anti_patterns:_e,last_updated_at:new Date().toISOString()},{onConflict:"user_id"});be?(console.error("[AlchemistEngine] Save persona error:",be),e(`Failed to save: ${be.message}`,"error")):e("Persona updated successfully","success")}catch(Q){console.error("[AlchemistEngine] Unexpected error:",Q),e(`Unexpected error: ${Q.message}`,"error")}finally{Ve(!1)}},ht=async()=>{K(!0);try{const{data:Q}=await Ke.post("/api/llm/test",{baseUrl:t,modelName:r,apiKey:p});Q.success?e(`Connection successful! ${Q.model?`Model: ${Q.model}`:""}`,"success"):e(`Connection failed: ${Q.message}`,"error")}catch(Q){console.error("[AlchemistEngine] Test error:",Q),e(`Test failed: ${Q.message}`,"error")}finally{K(!1)}};return u.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[u.jsxs("header",{className:"px-8 py-6 border-b border-border",children:[u.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Intelligence Engine"}),u.jsx("p",{className:"text-sm text-fg/50 font-medium",children:"Fine-tune the Alchemist's cognitive parameters and provider links."})]}),u.jsx("main",{className:"flex-1 overflow-y-auto custom-scrollbar p-8",children:u.jsxs("div",{className:"max-w-7xl mx-auto animate-in fade-in slide-in-from-bottom-2 duration-500",children:[u.jsxs("section",{className:"space-y-6 mb-8",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[u.jsx(W0,{size:14})," AI Configuration"]}),u.jsxs("div",{className:"flex gap-3",children:[u.jsxs("button",{onClick:ht,disabled:ae||W,className:"px-6 py-3 bg-surface hover:bg-surface/80 border border-border text-fg font-bold rounded-xl shadow-sm hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[ae?u.jsx(Et,{size:18,className:"animate-spin"}):u.jsx(Yt,{size:18,className:"text-accent"}),"Test Connection"]}),u.jsxs("button",{onClick:Kt,disabled:W,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[W?u.jsx(Et,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Save Configuration"]})]})]}),u.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[u.jsxs("div",{className:"glass p-6 space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2",children:[u.jsx("h3",{className:"text-sm font-semibold text-fg/80",children:"LLM Provider"}),ue?u.jsxs("span",{className:"text-xs text-green-500 flex items-center gap-1",children:[u.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full"}),"SDK Connected"]}):u.jsxs("span",{className:"text-xs text-orange-500 flex items-center gap-1",children:[u.jsx("span",{className:"w-2 h-2 bg-orange-500 rounded-full"}),"SDK Not Available"]})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-xs font-medium text-fg/60",children:"Provider"}),u.jsxs("select",{value:a,onChange:Q=>{l(Q.target.value),Ge(Q.target.value,D)},className:"w-full px-4 py-3 bg-surface border border-border rounded-xl text-fg focus:outline-none focus:ring-2 focus:ring-primary/50",children:[u.jsx("option",{value:"realtimexai",children:"RealTimeX.AI"}),u.jsx("option",{value:"openai",children:"OpenAI"}),u.jsx("option",{value:"anthropic",children:"Anthropic"}),u.jsx("option",{value:"google",children:"Google"}),u.jsx("option",{value:"ollama",children:"Ollama"})]})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-xs font-medium text-fg/60",children:"Intelligence Model"}),u.jsx("select",{value:d,onChange:Q=>h(Q.target.value),className:"w-full px-4 py-3 bg-surface border border-border rounded-xl text-fg focus:outline-none focus:ring-2 focus:ring-primary/50",children:ye.length>0?ye.map(Q=>u.jsx("option",{value:Q,children:Q},Q)):u.jsxs(u.Fragment,{children:[u.jsx("option",{value:"gpt-4o",children:"gpt-4o"}),u.jsx("option",{value:"gpt-4o-mini",children:"gpt-4o-mini"}),u.jsx("option",{value:"gpt-4-turbo",children:"gpt-4-turbo"})]})})]}),u.jsx("div",{className:"p-3 bg-primary/5 rounded-xl",children:u.jsx("p",{className:"text-[10px] text-primary/60 font-medium leading-relaxed",children:ue?"✓ Using RealTimeX configured provider":"⚠️ RealTimeX SDK not detected. Configure in RealTimeX Desktop."})})]}),u.jsxs("div",{className:"glass p-6 space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2",children:[u.jsx("h3",{className:"text-sm font-semibold text-fg/80",children:"Embedding Provider"}),ue?u.jsxs("span",{className:"text-xs text-green-500 flex items-center gap-1",children:[u.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full"}),"SDK Connected"]}):u.jsxs("span",{className:"text-xs text-orange-500 flex items-center gap-1",children:[u.jsx("span",{className:"w-2 h-2 bg-orange-500 rounded-full"}),"SDK Not Available"]})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-xs font-medium text-fg/60",children:"Provider"}),u.jsxs("select",{value:N,onChange:Q=>{R(Q.target.value),$e(Q.target.value,D)},className:"w-full px-4 py-3 bg-surface border border-border rounded-xl text-fg focus:outline-none focus:ring-2 focus:ring-primary/50",children:[u.jsx("option",{value:"realtimexai",children:"RealTimeX.AI"}),u.jsx("option",{value:"openai",children:"OpenAI"}),u.jsx("option",{value:"gemini",children:"Gemini"})]})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-xs font-medium text-fg/60",children:"Embedding Model"}),u.jsx("select",{value:S,onChange:Q=>E(Q.target.value),className:"w-full px-4 py-3 bg-surface border border-border rounded-xl text-fg focus:outline-none focus:ring-2 focus:ring-primary/50",children:A.length>0?A.map(Q=>u.jsx("option",{value:Q,children:Q},Q)):u.jsxs(u.Fragment,{children:[u.jsx("option",{value:"text-embedding-3-small",children:"text-embedding-3-small"}),u.jsx("option",{value:"text-embedding-3-large",children:"text-embedding-3-large"}),u.jsx("option",{value:"text-embedding-ada-002",children:"text-embedding-ada-002"})]})})]}),u.jsx("div",{className:"p-3 bg-primary/5 rounded-xl",children:u.jsx("p",{className:"text-[10px] text-primary/60 font-medium leading-relaxed",children:ue?"✓ Embeddings are generated using your RealTimeX configured provider":"⚠️ RealTimeX SDK not detected. Configure providers in RealTimeX Desktop."})})]})]})]}),u.jsxs("section",{className:"space-y-6 mb-8",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[u.jsx("span",{className:"text-xl",children:"🧠"})," Persona Memory"]}),u.jsxs("button",{onClick:Qe,disabled:Te,className:"px-6 py-3 bg-surface hover:bg-surface/80 border border-border text-fg font-bold rounded-xl shadow-sm hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[Te?u.jsx(Et,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Save Memory"]})]}),u.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[u.jsxs("div",{className:"glass p-6 space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2",children:[u.jsx("h3",{className:"text-sm font-semibold text-fg/80",children:"Active Interests"}),u.jsx("span",{className:"text-xs text-green-500 bg-green-500/10 px-2 py-1 rounded-full border border-green-500/20",children:"High Priority"})]}),u.jsx("p",{className:"text-xs text-fg/50 leading-relaxed",children:"The Alchemist prioritizes content matching these topics. Updated automatically based on Favorites & Boosts."}),u.jsx("textarea",{value:Hn,onChange:Q=>de(Q.target.value),placeholder:"e.g. User focuses on React performance, Rust backend systems, and AI Agent architecture...",className:"w-full h-32 px-4 py-3 bg-surface border border-border rounded-xl text-sm text-fg placeholder:text-fg/40 focus:outline-none focus:ring-2 focus:ring-green-500/30 resize-none"})]}),u.jsxs("div",{className:"glass p-6 space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2",children:[u.jsx("h3",{className:"text-sm font-semibold text-fg/80",children:"Anti-Patterns"}),u.jsx("span",{className:"text-xs text-red-400 bg-red-500/10 px-2 py-1 rounded-full border border-red-500/20",children:"Avoid"})]}),u.jsx("p",{className:"text-xs text-fg/50 leading-relaxed",children:"The Alchemist filters out or scores down content matching these patterns. Updated via Dismissals."}),u.jsx("textarea",{value:_e,onChange:Q=>Me(Q.target.value),placeholder:"e.g. Dislikes marketing fluff, generic listicles, and crypto hype...",className:"w-full h-32 px-4 py-3 bg-surface border border-border rounded-xl text-sm text-fg placeholder:text-fg/40 focus:outline-none focus:ring-2 focus:ring-red-500/30 resize-none"})]})]})]}),u.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[u.jsx("section",{className:"space-y-6",children:u.jsxs("div",{className:"space-y-4",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[u.jsx(zo,{size:14})," Browser History Sources"]}),u.jsxs("div",{className:"glass p-8 space-y-6",children:[u.jsx(CP,{sources:y,onChange:x}),u.jsx("div",{className:"flex justify-end pt-2",children:u.jsxs("button",{onClick:vr,disabled:se,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[se?u.jsx(Et,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Save Browser Sources"]})})]})]})}),u.jsx("section",{className:"space-y-6",children:u.jsxs("div",{className:"space-y-4",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[u.jsx(Yt,{size:14})," Blacklist Domains"]}),u.jsxs("div",{className:"glass p-8 space-y-6",children:[u.jsx("div",{className:"space-y-2",children:u.jsx("p",{className:"text-sm text-fg/60",children:"URLs containing these patterns will be skipped during mining. Enter one pattern per line."})}),u.jsxs("div",{className:"space-y-2",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Domain Patterns (one per line)"}),u.jsx("textarea",{value:w.join(`
|
|
71
71
|
`),onChange:Q=>b(Q.target.value.split(`
|
|
72
72
|
`).map(be=>be.trim())),placeholder:`google.com/search
|
|
73
73
|
localhost:
|
|
@@ -75,7 +75,7 @@ localhost:
|
|
|
75
75
|
facebook.com
|
|
76
76
|
twitter.com
|
|
77
77
|
instagram.com
|
|
78
|
-
linkedin.com/feed`,className:"w-full h-40 px-4 py-3 rounded-xl border border-border bg-surface text-fg text-sm placeholder:text-fg/40 focus:outline-none focus:border-[var(--border-hover)] transition-all resize-none"}),u.jsx("p",{className:"text-xs text-fg/50 ml-1",children:"Examples: google.com/search, localhost:, facebook.com, twitter.com"})]}),u.jsx("div",{className:"flex justify-end pt-2",children:u.jsxs("button",{onClick:Rn,disabled:ee,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[ee?u.jsx(Et,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Save Blacklist"]})})]})]})})]}),u.jsx("section",{className:"space-y-6 mt-8",children:u.jsxs("div",{className:"space-y-4",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[u.jsx(qh,{size:14})," Blocked Tags"]}),u.jsxs("div",{className:"glass p-8 space-y-6",children:[u.jsx("div",{className:"space-y-2",children:u.jsx("p",{className:"text-sm text-fg/60",children:"Signals with these tags will be excluded from dynamic category generation and newsletters. Enter one tag per line."})}),u.jsxs("div",{className:"space-y-2",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Tags (separated by semicolon)"}),u.jsx("textarea",{value:_.join("; "),onChange:Q=>k(Q.target.value.split(";").map(be=>be.trim())),placeholder:"login; signup; footer; navigation",className:"w-full h-40 px-4 py-3 rounded-xl border border-border bg-surface text-fg text-sm placeholder:text-fg/40 focus:outline-none focus:border-[var(--border-hover)] transition-all resize-none"}),u.jsx("p",{className:"text-xs text-fg/50 ml-1",children:"You have full control. These tags will completely replace the system defaults."})]}),u.jsx("div",{className:"flex justify-end pt-2",children:u.jsxs("button",{onClick:rr,disabled:H,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[H?u.jsx(Et,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Save Blocked Tags"]})})]})]})})]})})]})}const mb=T.createContext(null);function OP({children:e}){const[t,n]=T.useState(!1),r=()=>n(!0),o=()=>n(!1);return u.jsx(mb.Provider,{value:{isExpanded:t,setIsExpanded:n,openTerminal:r,closeTerminal:o},children:e})}function IP(){const e=T.useContext(mb);if(!e)throw new Error("useTerminal must be used within a TerminalProvider");return e}function DP({isExpanded:e,onToggle:t,onNavigate:n,liftUp:r}={}){const[o,a]=T.useState([]),{isExpanded:l,setIsExpanded:d}=IP(),[h,p]=T.useState({}),m=e!==void 0?e:l,y=t||(()=>d(!l)),x=r?"bottom-32":"bottom-6";T.useEffect(()=>{w();const k=ne.channel("processing_events_feed").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events"},S=>{const E=S.new;E.event_type==="error"&&p(N=>({...N,[E.id]:!0})),a(N=>{const R=[E,...N];return R.length>50?R.slice(0,50):R})}).subscribe();return()=>{ne.removeChannel(k)}},[]);const w=async()=>{const{data:k}=await ne.from("processing_events").select("*").order("created_at",{ascending:!1}).limit(30);k&&a(k)},b=k=>{p(S=>({...S,[k]:!S[k]}))},_=(k,S,E,N)=>{if(S==="debug")return u.jsx(dS,{size:14,className:"text-fg/40"});if(E?.is_completion||N?.is_completion)return u.jsx(vs,{size:14,className:"text-success"});switch(k){case"analysis":return u.jsx(V0,{size:14,className:"text-primary"});case"action":return u.jsx(Yt,{size:14,className:"text-accent"});case"error":return u.jsx(Kg,{size:14,className:"text-error"});case"system":return u.jsx(ec,{size:14,className:"text-success"});default:return u.jsx(K0,{size:14,className:"text-fg/40"})}};return m?u.jsxs(ze.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},className:"fixed bottom-6 right-6 z-50 w-[450px] max-h-[600px] glass shadow-2xl flex flex-col overflow-hidden border-primary/10",children:[u.jsxs("div",{className:"p-4 border-b border-border/10 flex items-center justify-between bg-surface/50",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(zl,{size:18,className:"text-primary"}),u.jsx("span",{className:"text-xs font-bold uppercase tracking-widest",children:"Alchemist Engine"}),u.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold bg-success/10 text-success px-2 py-0.5 rounded-full border border-success/10 animate-pulse ml-2",children:[u.jsx(oS,{size:10})," LIVE"]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:()=>a([]),className:"text-[10px] uppercase font-bold text-fg/40 hover:text-fg px-2 py-1 transition-colors",children:"Clear"}),u.jsx("button",{onClick:y,className:"text-fg/40 hover:text-fg p-1 transition-colors",children:u.jsx(TS,{size:18})})]})]}),u.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 custom-scrollbar bg-black/20",children:[o.length===0&&u.jsx("div",{className:"text-center py-12 text-fg/20 italic text-xs",children:"Idle. Awaiting signal mining events..."}),o.map(k=>u.jsxs("div",{className:"relative flex items-start gap-3 group",children:[u.jsx("div",{className:`mt-1 flex-shrink-0 w-6 h-6 rounded-full bg-surface border flex items-center justify-center ${k.metadata?.is_completion||k.details?.is_completion?"border-success/50 bg-success/5":"border-white/5"}`,children:_(k.event_type,k.level,k.metadata,k.details)}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[u.jsx("span",{className:"text-xs font-mono text-fg/60 shrink-0",children:new Date(k.created_at||Date.now()).toLocaleTimeString()}),u.jsx("span",{className:`text-xs font-bold uppercase tracking-wider ${k.level==="error"?"text-error":k.level==="warn"?"text-orange-400":k.event_type==="analysis"?"text-primary":"text-fg/90"}`,children:k.agent_state}),k.metadata?.actionable&&n&&u.jsxs("button",{onClick:()=>n("logs",k.metadata?.actionable),className:"ml-auto flex items-center gap-1 bg-primary/10 text-primary border border-primary/20 px-1.5 py-0.5 rounded text-[10px] uppercase font-bold tracking-wider hover:bg-primary/20 transition-all font-mono",children:[k.metadata.actionable.label,u.jsx(xi,{size:10,className:"-rotate-90"})]}),k.duration_ms&&!k.metadata?.actionable&&u.jsxs("span",{className:"ml-auto text-[10px] font-mono bg-bg/50 px-1.5 py-0.5 rounded flex items-center gap-1 text-fg/40",children:[u.jsx(vi,{size:10}),k.duration_ms,"ms"]})]}),k.metadata?.is_completion||k.details?.is_completion?u.jsxs("div",{className:"bg-success/5 border border-success/20 rounded-lg p-3 space-y-2 mt-2",children:[u.jsxs("div",{className:"flex items-center gap-2 text-success font-bold uppercase text-[9px] tracking-[0.2em]",children:[u.jsx(vs,{className:"w-3.5 h-3.5"}),"Mining Run Completed"]}),u.jsxs("div",{className:"grid grid-cols-3 gap-4 pt-1",children:[u.jsxs("div",{className:"space-y-0.5",children:[u.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:"Signals"}),u.jsx("p",{className:"text-sm font-bold text-primary",children:k.metadata?.signals_found||k.details?.signals_found||0})]}),u.jsxs("div",{className:"space-y-0.5",children:[u.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:"URLs"}),u.jsx("p",{className:"text-sm font-bold",children:k.metadata?.total_urls||k.details?.total_urls||0})]}),u.jsxs("div",{className:"space-y-0.5",children:[u.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:"Skipped"}),u.jsx("p",{className:"text-sm font-bold text-fg/60",children:k.metadata?.skipped||k.details?.skipped||0})]})]}),(k.metadata?.errors||k.details?.errors)>0&&u.jsxs("div",{className:"pt-1 border-t border-success/10 flex items-center justify-between mt-1",children:[u.jsxs("p",{className:"text-[10px] text-error font-bold flex items-center gap-1.5",children:[u.jsx(Kg,{size:12}),k.metadata?.errors||k.details?.errors," URLs failed to process"]}),n&&u.jsxs("button",{onClick:()=>n("logs",{filter:"errors"}),className:"flex items-center gap-1 text-[9px] uppercase font-bold text-error bg-error/10 border border-error/20 px-2 py-1 rounded hover:bg-error/20 transition-all group/btn",children:["View Logs",u.jsx(Cl,{size:10,className:"group-hover/btn:translate-x-0.5 transition-transform"})]})]})]}):u.jsx("p",{className:`text-sm break-words leading-relaxed ${k.level==="debug"?"text-fg/50 font-mono text-xs":""}`,children:k.message}),(k.details||k.metadata)&&u.jsxs("div",{className:"mt-2 text-xs",children:[u.jsxs("button",{onClick:()=>b(k.id),className:"flex items-center gap-1 text-fg/40 hover:text-primary transition-colors",children:[h[k.id]?u.jsx(q0,{size:12}):u.jsx(xi,{size:12}),h[k.id]?"Hide Details":"View Details"]}),u.jsx(Pt,{children:h[k.id]&&u.jsx(ze.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},className:"overflow-hidden",children:u.jsx("pre",{className:"mt-2 p-3 bg-bg/50 rounded border border-white/5 font-mono text-[10px] overflow-x-auto text-fg/70",children:JSON.stringify({...k.details,...k.metadata},null,2)})})})]})]})]},k.id))]})]}):u.jsxs("button",{onClick:y,className:`fixed ${x} right-6 z-50 glass p-4 flex items-center gap-3 hover:bg-surface transition-all shadow-xl group border-primary/10`,children:[u.jsxs("div",{className:"relative",children:[u.jsx(zl,{size:20,className:"text-primary"}),o.length>0&&u.jsxs("span",{className:"absolute -top-1 -right-1 flex h-2 w-2",children:[u.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"}),u.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-primary"})]})]}),u.jsx("span",{className:"text-xs font-bold uppercase tracking-widest hidden group-hover:block animate-in fade-in slide-in-from-right-2",children:"Live Engine Log"})]})}const gb="1.0.0",LP="20260127000000";async function MP(e){try{const{data:t,error:n}=await e.rpc("get_latest_migration_timestamp");return n?n.code==="42883"?{version:null,latestMigrationTimestamp:"0"}:{version:null,latestMigrationTimestamp:null}:{version:gb,latestMigrationTimestamp:t||null}}catch{return{version:null,latestMigrationTimestamp:null}}}async function zP(e){const t=gb,n=LP,r=await MP(e);if(r.latestMigrationTimestamp&&r.latestMigrationTimestamp.trim()!==""){const o=n,a=r.latestMigrationTimestamp;return o>a?{needsMigration:!0,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:a,message:`New migrations available. Database is at ${a}, app has ${o}.`}:{needsMigration:!1,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:a,message:"Database schema is up-to-date."}}return{needsMigration:!0,appVersion:t,dbVersion:null,latestMigrationTimestamp:null,message:"Database schema unknown. Migration required."}}function UP(){const[e,t]=T.useState("profile"),[n,r]=T.useState(!1);return u.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[u.jsxs("header",{className:"px-8 py-6 border-b border-border",children:[u.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Account Configuration"}),u.jsx("p",{className:"text-sm text-fg/50 font-medium",children:"Manage your Alchemist profile and essence links."})]}),u.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[u.jsxs("aside",{className:"w-64 border-r border-border p-4 space-y-1",children:[u.jsx(Md,{active:e==="profile",onClick:()=>t("profile"),icon:u.jsx(tc,{size:18}),label:"Profile"}),u.jsx(Md,{active:e==="security",onClick:()=>t("security"),icon:u.jsx(G0,{size:18}),label:"Security"}),u.jsx(Md,{active:e==="supabase",onClick:()=>t("supabase"),icon:u.jsx(zo,{size:18}),label:"Supabase"})]}),u.jsxs("main",{className:"flex-1 overflow-y-auto custom-scrollbar p-8",children:[e==="profile"&&u.jsx(FP,{}),e==="security"&&u.jsx(BP,{}),e==="supabase"&&u.jsx($P,{})]})]})]})}function FP(){const[e,t]=T.useState(""),[n,r]=T.useState(""),[o,a]=T.useState(""),[l,d]=T.useState(!1),[h,p]=T.useState(!1),[m,y]=T.useState(null),[x,w]=T.useState(!0);T.useEffect(()=>{b()},[]);const b=async()=>{const{data:{user:S}}=await ne.auth.getUser();if(!S)return;a(S.email||"");const{data:E}=await ne.from("profiles").select("*").eq("id",S.id).maybeSingle();E&&(t(E.first_name||""),r(E.last_name||""),y(E.avatar_url));const{data:N}=await ne.from("alchemy_settings").select("sound_enabled").eq("user_id",S.id).maybeSingle();N&&w(N.sound_enabled??!0)},_=async()=>{d(!0);const{data:{user:S}}=await ne.auth.getUser();S&&(await ne.from("profiles").upsert({id:S.id,first_name:e,last_name:n,full_name:e&&n?`${e} ${n}`:e||n||null}),await ne.from("alchemy_settings").update({sound_enabled:x}).eq("user_id",S.id),d(!1))},k=async S=>{const E=S.target.files?.[0];if(E){p(!0);try{const{data:{user:N}}=await ne.auth.getUser();if(!N)return;const R=E.name.split(".").pop(),M=`${N.id}/avatar-${Date.now()}.${R}`,{error:O}=await ne.storage.from("avatars").upload(M,E,{upsert:!0});if(O)throw O;const{data:{publicUrl:q}}=ne.storage.from("avatars").getPublicUrl(M);await ne.from("profiles").update({avatar_url:q}).eq("id",N.id),y(q)}catch(N){console.error("Avatar upload failed:",N)}finally{p(!1)}}};return u.jsxs("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:[u.jsxs("section",{className:"flex items-start gap-8",children:[u.jsxs("div",{className:"relative group",children:[u.jsx("div",{className:"w-32 h-32 rounded-3xl bg-surface border border-border flex items-center justify-center overflow-hidden shadow-xl",children:m?u.jsx("img",{src:m,alt:"Avatar",className:"w-full h-full object-cover"}):u.jsx(tc,{size:48,className:"text-fg/20"})}),u.jsxs("label",{className:"absolute inset-0 flex items-center justify-center bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer rounded-3xl",children:[u.jsx(fS,{size:24,className:"text-white"}),u.jsx("input",{type:"file",className:"hidden",accept:"image/*",onChange:k,disabled:h})]}),h&&u.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40 rounded-3xl",children:u.jsx(Et,{size:24,className:"text-primary animate-spin"})})]}),u.jsxs("div",{className:"flex-1 space-y-4",children:[u.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.jsx(Yl,{label:"First Name",value:e,onChange:t,placeholder:"Zosimos"}),u.jsx(Yl,{label:"Last Name",value:n,onChange:r,placeholder:"of Panopolis"})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Email Address (Locked)"}),u.jsx("input",{type:"email",value:o,readOnly:!0,className:"w-full bg-black/5 border border-border rounded-xl py-3 px-4 text-sm text-fg/40 cursor-not-allowed"})]})]})]}),u.jsxs("section",{className:"glass p-6 space-y-4",children:[u.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[x?u.jsx(Zg,{size:20,className:"text-primary"}):u.jsx(ey,{size:20,className:"text-fg/40"}),"Sound Effects"]}),u.jsx("p",{className:"text-xs text-fg/40",children:"Enable audio feedback for sync events and signal discoveries."}),u.jsx("button",{onClick:()=>w(!x),className:`w-full p-4 rounded-xl border-2 transition-all ${x?"bg-primary/10 border-primary/30 text-primary":"bg-surface border-border text-fg/40"}`,children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("span",{className:"font-semibold text-sm",children:x?"Enabled":"Disabled"}),x?u.jsx(Zg,{size:18}):u.jsx(ey,{size:18})]})})]}),u.jsxs("section",{className:"glass p-6 space-y-4",children:[u.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[u.jsx(Yg,{size:20,className:"text-error"}),"Sign Out"]}),u.jsx("p",{className:"text-xs text-fg/40",children:"End your current session and return to the login screen."}),u.jsx("button",{onClick:()=>ne.auth.signOut(),className:"w-full p-4 rounded-xl border-2 bg-error/10 border-error/30 text-error hover:bg-error hover:text-white transition-all",children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("span",{className:"font-semibold text-sm",children:"Logout"}),u.jsx(Yg,{size:18})]})})]}),u.jsx("div",{className:"flex justify-end pt-4 border-t border-border",children:u.jsxs("button",{onClick:_,disabled:l,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[l?u.jsx(Et,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Preserve Profile"]})})]})}function BP(){const[e,t]=T.useState(""),[n,r]=T.useState(""),[o,a]=T.useState(!1),[l,d]=T.useState(null),[h,p]=T.useState(!1),m=async()=>{if(!e||e!==n){d("Complexity keys do not match.");return}if(e.length<8){d("Entropy too low. Minimum 8 characters.");return}a(!0),d(null),p(!1);const{error:y}=await ne.auth.updateUser({password:e});y?d(y.message):(p(!0),t(""),r("")),a(!1)};return u.jsx("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:u.jsxs("div",{className:"glass p-6 space-y-6",children:[u.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[u.jsx(SS,{size:20,className:"text-error"})," Update Entropy Key"]}),u.jsxs("div",{className:"space-y-4",children:[u.jsx(Yl,{label:"New Password",type:"password",value:e,onChange:t,placeholder:"••••••••"}),u.jsx(Yl,{label:"Confirm Password",type:"password",value:n,onChange:r,placeholder:"••••••••"})]}),l&&u.jsx("p",{className:"text-xs text-error font-mono bg-error/5 p-3 rounded-lg border border-error/10",children:l}),h&&u.jsx("p",{className:"text-xs text-success font-mono bg-success/5 p-3 rounded-lg border border-success/10",children:"Key rotation successful."}),u.jsx("div",{className:"flex justify-end pt-2",children:u.jsxs("button",{onClick:m,disabled:o,className:"px-6 py-3 bg-error/10 text-error hover:bg-error hover:text-white font-bold rounded-xl border border-error/20 transition-all flex items-center gap-2",children:[o?u.jsx(Et,{size:18,className:"animate-spin"}):u.jsx(G0,{size:18}),"Rotate Key"]})})]})})}function $P(){const[e,t]=T.useState(!1),[n,r]=T.useState(null),o=ks(),a=bP();T.useEffect(()=>{o&&zP(ne).then(r)},[]);const l=()=>{confirm("Sever connection to this essence? This will reset local resonance.")&&(vP(),window.location.reload())};return u.jsxs("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:[u.jsxs("section",{className:"space-y-6",children:[u.jsx("div",{className:"flex items-center justify-between",children:u.jsxs("div",{children:[u.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[u.jsx(zo,{size:20,className:"text-primary"})," Essence Resonance"]}),u.jsx("p",{className:"text-xs text-fg/40 font-medium",children:"Bring Your Own Keys (BYOK) for intelligence persistence."})]})}),u.jsx("div",{className:"glass p-8 space-y-8",children:o?u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex items-start gap-4 p-4 glass bg-emerald-500/5 border border-emerald-500/20 rounded-2xl",children:[u.jsx(vs,{className:"w-6 h-6 text-emerald-500 mt-1"}),u.jsxs("div",{className:"flex-1 space-y-1",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("p",{className:"font-bold text-fg italic uppercase tracking-tighter",children:"Established Link"}),n?.latestMigrationTimestamp&&u.jsxs("span",{className:"text-[10px] font-mono bg-emerald-500/10 text-emerald-500 px-2 py-0.5 rounded-full border border-emerald-500/20",children:["v",n.latestMigrationTimestamp]})]}),u.jsx("p",{className:"text-xs font-mono text-fg/40 break-all",children:o.url})]})]}),a==="env"&&u.jsxs("div",{className:"flex items-center gap-3 p-3 bg-amber-500/5 border border-amber-500/10 rounded-xl",children:[u.jsx(pr,{size:16,className:"text-amber-500"}),u.jsx("p",{className:"text-[10px] text-amber-500 font-bold uppercase tracking-widest leading-none",children:"Active from environment variables. UI override enabled."})]}),u.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.jsxs("button",{onClick:()=>t(!0),className:"px-4 py-3 glass hover:bg-surface text-xs font-bold uppercase tracking-widest transition-all flex items-center justify-center gap-2",children:[u.jsx(ec,{size:14})," Realign Link"]}),a==="ui"&&u.jsxs("button",{onClick:l,className:"px-4 py-3 glass border-error/10 hover:bg-error/10 text-error/60 hover:text-error text-xs font-bold uppercase tracking-widest transition-all flex items-center justify-center gap-2",children:[u.jsx(Wh,{size:14})," Sever Link"]})]}),u.jsxs("div",{className:"space-y-1 pt-4 border-t border-border/10",children:[u.jsx("label",{className:"text-[9px] font-bold uppercase tracking-widest text-fg/20 ml-1",children:"Anon Secret Fragment"}),u.jsxs("div",{className:"p-3 bg-surface/50 rounded-xl font-mono text-[11px] text-fg/30 break-all border border-border",children:[o.anonKey.substring(0,32),"..."]})]})]}):u.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-6",children:[u.jsx(zo,{size:48,className:"text-fg/10"}),u.jsxs("div",{className:"space-y-2",children:[u.jsx("p",{className:"font-bold italic uppercase tracking-tighter",children:"No Essence Resonance"}),u.jsx("p",{className:"text-xs text-fg/40 max-w-[240px]",children:"The Alchemist requires a cloud core to store intelligence fragments."})]}),u.jsx("button",{onClick:()=>t(!0),className:"px-8 py-3 bg-primary text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] transition-all uppercase tracking-widest text-xs",children:"Initiate Link"})]})})]}),u.jsx(hb,{open:e,onComplete:()=>t(!1),canClose:!0})]})}function Md({active:e,icon:t,label:n,onClick:r}){return u.jsxs("button",{onClick:r,className:`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${e?"glass bg-primary/10 text-primary border-primary/20 shadow-sm":"text-fg/40 hover:bg-surface hover:text-fg"}`,children:[e?Mo.cloneElement(t,{className:"text-primary"}):t,u.jsx("span",{className:"font-semibold text-sm",children:n})]})}function Yl({label:e,value:t,onChange:n,placeholder:r,type:o="text"}){return u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:e}),u.jsx("input",{type:o,value:t,onChange:a=>n(a.target.value),className:"w-full bg-surface border border-border rounded-xl py-3 px-4 text-sm text-fg placeholder:text-fg/40 focus:border-[var(--border-hover)] outline-none transition-all",placeholder:r})]})}function VP({signal:e,onClose:t}){const[n,r]=Mo.useState(!1);if(!e)return null;const o=()=>{const d=`# ${e.title}
|
|
78
|
+
linkedin.com/feed`,className:"w-full h-40 px-4 py-3 rounded-xl border border-border bg-surface text-fg text-sm placeholder:text-fg/40 focus:outline-none focus:border-[var(--border-hover)] transition-all resize-none"}),u.jsx("p",{className:"text-xs text-fg/50 ml-1",children:"Examples: google.com/search, localhost:, facebook.com, twitter.com"})]}),u.jsx("div",{className:"flex justify-end pt-2",children:u.jsxs("button",{onClick:Rn,disabled:ee,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[ee?u.jsx(Et,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Save Blacklist"]})})]})]})})]}),u.jsx("section",{className:"space-y-6 mt-8",children:u.jsxs("div",{className:"space-y-4",children:[u.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[u.jsx(qh,{size:14})," Blocked Tags"]}),u.jsxs("div",{className:"glass p-8 space-y-6",children:[u.jsx("div",{className:"space-y-2",children:u.jsx("p",{className:"text-sm text-fg/60",children:"Signals with these tags will be excluded from dynamic category generation and newsletters. Enter one tag per line."})}),u.jsxs("div",{className:"space-y-2",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Tags (separated by semicolon)"}),u.jsx("textarea",{value:_.join("; "),onChange:Q=>k(Q.target.value.split(";").map(be=>be.trim())),placeholder:"login; signup; footer; navigation",className:"w-full h-40 px-4 py-3 rounded-xl border border-border bg-surface text-fg text-sm placeholder:text-fg/40 focus:outline-none focus:border-[var(--border-hover)] transition-all resize-none"}),u.jsx("p",{className:"text-xs text-fg/50 ml-1",children:"You have full control. These tags will completely replace the system defaults."})]}),u.jsx("div",{className:"flex justify-end pt-2",children:u.jsxs("button",{onClick:rr,disabled:H,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[H?u.jsx(Et,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Save Blocked Tags"]})})]})]})})]})})]})}const mb=T.createContext(null);function OP({children:e}){const[t,n]=T.useState(!1),r=()=>n(!0),o=()=>n(!1);return u.jsx(mb.Provider,{value:{isExpanded:t,setIsExpanded:n,openTerminal:r,closeTerminal:o},children:e})}function IP(){const e=T.useContext(mb);if(!e)throw new Error("useTerminal must be used within a TerminalProvider");return e}function DP({isExpanded:e,onToggle:t,onNavigate:n,liftUp:r}={}){const[o,a]=T.useState([]),{isExpanded:l,setIsExpanded:d}=IP(),[h,p]=T.useState({}),m=e!==void 0?e:l,y=t||(()=>d(!l)),x=r?"bottom-32":"bottom-6";T.useEffect(()=>{w();const k=ne.channel("processing_events_feed").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events"},S=>{const E=S.new;E.event_type==="error"&&p(N=>({...N,[E.id]:!0})),a(N=>{const R=[E,...N];return R.length>50?R.slice(0,50):R})}).subscribe();return()=>{ne.removeChannel(k)}},[]);const w=async()=>{const{data:k}=await ne.from("processing_events").select("*").order("created_at",{ascending:!1}).limit(30);k&&a(k)},b=k=>{p(S=>({...S,[k]:!S[k]}))},_=(k,S,E,N)=>{if(S==="debug")return u.jsx(dS,{size:14,className:"text-fg/40"});if(E?.is_completion||N?.is_completion)return u.jsx(vs,{size:14,className:"text-success"});switch(k){case"analysis":return u.jsx(V0,{size:14,className:"text-primary"});case"action":return u.jsx(Yt,{size:14,className:"text-accent"});case"error":return u.jsx(Kg,{size:14,className:"text-error"});case"system":return u.jsx(ec,{size:14,className:"text-success"});default:return u.jsx(K0,{size:14,className:"text-fg/40"})}};return m?u.jsxs(ze.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},className:"fixed bottom-6 right-6 z-50 w-[450px] max-h-[600px] glass shadow-2xl flex flex-col overflow-hidden border-primary/10",children:[u.jsxs("div",{className:"p-4 border-b border-border/10 flex items-center justify-between bg-surface/50",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(zl,{size:18,className:"text-primary"}),u.jsx("span",{className:"text-xs font-bold uppercase tracking-widest",children:"Alchemist Engine"}),u.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold bg-success/10 text-success px-2 py-0.5 rounded-full border border-success/10 animate-pulse ml-2",children:[u.jsx(oS,{size:10})," LIVE"]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:()=>a([]),className:"text-[10px] uppercase font-bold text-fg/40 hover:text-fg px-2 py-1 transition-colors",children:"Clear"}),u.jsx("button",{onClick:y,className:"text-fg/40 hover:text-fg p-1 transition-colors",children:u.jsx(TS,{size:18})})]})]}),u.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 custom-scrollbar bg-black/20",children:[o.length===0&&u.jsx("div",{className:"text-center py-12 text-fg/20 italic text-xs",children:"Idle. Awaiting signal mining events..."}),o.map(k=>u.jsxs("div",{className:"relative flex items-start gap-3 group",children:[u.jsx("div",{className:`mt-1 flex-shrink-0 w-6 h-6 rounded-full bg-surface border flex items-center justify-center ${k.metadata?.is_completion||k.details?.is_completion?"border-success/50 bg-success/5":"border-white/5"}`,children:_(k.event_type,k.level,k.metadata,k.details)}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[u.jsx("span",{className:"text-xs font-mono text-fg/60 shrink-0",children:new Date(k.created_at||Date.now()).toLocaleTimeString()}),u.jsx("span",{className:`text-xs font-bold uppercase tracking-wider ${k.level==="error"?"text-error":k.level==="warn"?"text-orange-400":k.event_type==="analysis"?"text-primary":"text-fg/90"}`,children:k.agent_state}),k.metadata?.actionable&&n&&u.jsxs("button",{onClick:()=>n("logs",k.metadata?.actionable),className:"ml-auto flex items-center gap-1 bg-primary/10 text-primary border border-primary/20 px-1.5 py-0.5 rounded text-[10px] uppercase font-bold tracking-wider hover:bg-primary/20 transition-all font-mono",children:[k.metadata.actionable.label,u.jsx(xi,{size:10,className:"-rotate-90"})]}),k.duration_ms&&!k.metadata?.actionable&&u.jsxs("span",{className:"ml-auto text-[10px] font-mono bg-bg/50 px-1.5 py-0.5 rounded flex items-center gap-1 text-fg/40",children:[u.jsx(vi,{size:10}),k.duration_ms,"ms"]})]}),k.metadata?.is_completion||k.details?.is_completion?u.jsxs("div",{className:"bg-success/5 border border-success/20 rounded-lg p-3 space-y-2 mt-2",children:[u.jsxs("div",{className:"flex items-center gap-2 text-success font-bold uppercase text-[9px] tracking-[0.2em]",children:[u.jsx(vs,{className:"w-3.5 h-3.5"}),"Mining Run Completed"]}),u.jsxs("div",{className:"grid grid-cols-3 gap-4 pt-1",children:[u.jsxs("div",{className:"space-y-0.5",children:[u.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:"Signals"}),u.jsx("p",{className:"text-sm font-bold text-primary",children:k.metadata?.signals_found||k.details?.signals_found||0})]}),u.jsxs("div",{className:"space-y-0.5",children:[u.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:"URLs"}),u.jsx("p",{className:"text-sm font-bold",children:k.metadata?.total_urls||k.details?.total_urls||0})]}),u.jsxs("div",{className:"space-y-0.5",children:[u.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:"Skipped"}),u.jsx("p",{className:"text-sm font-bold text-fg/60",children:k.metadata?.skipped||k.details?.skipped||0})]})]}),(k.metadata?.errors||k.details?.errors)>0&&u.jsxs("div",{className:"pt-1 border-t border-success/10 flex items-center justify-between mt-1",children:[u.jsxs("p",{className:"text-[10px] text-error font-bold flex items-center gap-1.5",children:[u.jsx(Kg,{size:12}),k.metadata?.errors||k.details?.errors," URLs failed to process"]}),n&&u.jsxs("button",{onClick:()=>n("logs",{filter:"errors"}),className:"flex items-center gap-1 text-[9px] uppercase font-bold text-error bg-error/10 border border-error/20 px-2 py-1 rounded hover:bg-error/20 transition-all group/btn",children:["View Logs",u.jsx(Cl,{size:10,className:"group-hover/btn:translate-x-0.5 transition-transform"})]})]})]}):u.jsx("p",{className:`text-sm break-words leading-relaxed ${k.level==="debug"?"text-fg/50 font-mono text-xs":""}`,children:k.message}),(k.details||k.metadata)&&u.jsxs("div",{className:"mt-2 text-xs",children:[u.jsxs("button",{onClick:()=>b(k.id),className:"flex items-center gap-1 text-fg/40 hover:text-primary transition-colors",children:[h[k.id]?u.jsx(q0,{size:12}):u.jsx(xi,{size:12}),h[k.id]?"Hide Details":"View Details"]}),u.jsx(Pt,{children:h[k.id]&&u.jsx(ze.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},className:"overflow-hidden",children:u.jsx("pre",{className:"mt-2 p-3 bg-bg/50 rounded border border-white/5 font-mono text-[10px] overflow-x-auto text-fg/70",children:JSON.stringify({...k.details,...k.metadata},null,2)})})})]})]})]},k.id))]})]}):u.jsxs("button",{onClick:y,className:`fixed ${x} right-6 z-50 glass p-4 flex items-center gap-3 hover:bg-surface transition-all shadow-xl group border-primary/10`,children:[u.jsxs("div",{className:"relative",children:[u.jsx(zl,{size:20,className:"text-primary"}),o.length>0&&u.jsxs("span",{className:"absolute -top-1 -right-1 flex h-2 w-2",children:[u.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"}),u.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-primary"})]})]}),u.jsx("span",{className:"text-xs font-bold uppercase tracking-widest hidden group-hover:block animate-in fade-in slide-in-from-right-2",children:"Live Engine Log"})]})}const gb="1.0.0",LP="20260127000002";async function MP(e){try{const{data:t,error:n}=await e.rpc("get_latest_migration_timestamp");return n?n.code==="42883"?{version:null,latestMigrationTimestamp:"0"}:{version:null,latestMigrationTimestamp:null}:{version:gb,latestMigrationTimestamp:t||null}}catch{return{version:null,latestMigrationTimestamp:null}}}async function zP(e){const t=gb,n=LP,r=await MP(e);if(r.latestMigrationTimestamp&&r.latestMigrationTimestamp.trim()!==""){const o=n,a=r.latestMigrationTimestamp;return o>a?{needsMigration:!0,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:a,message:`New migrations available. Database is at ${a}, app has ${o}.`}:{needsMigration:!1,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:a,message:"Database schema is up-to-date."}}return{needsMigration:!0,appVersion:t,dbVersion:null,latestMigrationTimestamp:null,message:"Database schema unknown. Migration required."}}function UP(){const[e,t]=T.useState("profile"),[n,r]=T.useState(!1);return u.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[u.jsxs("header",{className:"px-8 py-6 border-b border-border",children:[u.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Account Configuration"}),u.jsx("p",{className:"text-sm text-fg/50 font-medium",children:"Manage your Alchemist profile and essence links."})]}),u.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[u.jsxs("aside",{className:"w-64 border-r border-border p-4 space-y-1",children:[u.jsx(Md,{active:e==="profile",onClick:()=>t("profile"),icon:u.jsx(tc,{size:18}),label:"Profile"}),u.jsx(Md,{active:e==="security",onClick:()=>t("security"),icon:u.jsx(G0,{size:18}),label:"Security"}),u.jsx(Md,{active:e==="supabase",onClick:()=>t("supabase"),icon:u.jsx(zo,{size:18}),label:"Supabase"})]}),u.jsxs("main",{className:"flex-1 overflow-y-auto custom-scrollbar p-8",children:[e==="profile"&&u.jsx(FP,{}),e==="security"&&u.jsx(BP,{}),e==="supabase"&&u.jsx($P,{})]})]})]})}function FP(){const[e,t]=T.useState(""),[n,r]=T.useState(""),[o,a]=T.useState(""),[l,d]=T.useState(!1),[h,p]=T.useState(!1),[m,y]=T.useState(null),[x,w]=T.useState(!0);T.useEffect(()=>{b()},[]);const b=async()=>{const{data:{user:S}}=await ne.auth.getUser();if(!S)return;a(S.email||"");const{data:E}=await ne.from("profiles").select("*").eq("id",S.id).maybeSingle();E&&(t(E.first_name||""),r(E.last_name||""),y(E.avatar_url));const{data:N}=await ne.from("alchemy_settings").select("sound_enabled").eq("user_id",S.id).maybeSingle();N&&w(N.sound_enabled??!0)},_=async()=>{d(!0);const{data:{user:S}}=await ne.auth.getUser();S&&(await ne.from("profiles").upsert({id:S.id,first_name:e,last_name:n,full_name:e&&n?`${e} ${n}`:e||n||null}),await ne.from("alchemy_settings").update({sound_enabled:x}).eq("user_id",S.id),d(!1))},k=async S=>{const E=S.target.files?.[0];if(E){p(!0);try{const{data:{user:N}}=await ne.auth.getUser();if(!N)return;const R=E.name.split(".").pop(),M=`${N.id}/avatar-${Date.now()}.${R}`,{error:O}=await ne.storage.from("avatars").upload(M,E,{upsert:!0});if(O)throw O;const{data:{publicUrl:q}}=ne.storage.from("avatars").getPublicUrl(M);await ne.from("profiles").update({avatar_url:q}).eq("id",N.id),y(q)}catch(N){console.error("Avatar upload failed:",N)}finally{p(!1)}}};return u.jsxs("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:[u.jsxs("section",{className:"flex items-start gap-8",children:[u.jsxs("div",{className:"relative group",children:[u.jsx("div",{className:"w-32 h-32 rounded-3xl bg-surface border border-border flex items-center justify-center overflow-hidden shadow-xl",children:m?u.jsx("img",{src:m,alt:"Avatar",className:"w-full h-full object-cover"}):u.jsx(tc,{size:48,className:"text-fg/20"})}),u.jsxs("label",{className:"absolute inset-0 flex items-center justify-center bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer rounded-3xl",children:[u.jsx(fS,{size:24,className:"text-white"}),u.jsx("input",{type:"file",className:"hidden",accept:"image/*",onChange:k,disabled:h})]}),h&&u.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40 rounded-3xl",children:u.jsx(Et,{size:24,className:"text-primary animate-spin"})})]}),u.jsxs("div",{className:"flex-1 space-y-4",children:[u.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.jsx(Yl,{label:"First Name",value:e,onChange:t,placeholder:"Zosimos"}),u.jsx(Yl,{label:"Last Name",value:n,onChange:r,placeholder:"of Panopolis"})]}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:"Email Address (Locked)"}),u.jsx("input",{type:"email",value:o,readOnly:!0,className:"w-full bg-black/5 border border-border rounded-xl py-3 px-4 text-sm text-fg/40 cursor-not-allowed"})]})]})]}),u.jsxs("section",{className:"glass p-6 space-y-4",children:[u.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[x?u.jsx(Zg,{size:20,className:"text-primary"}):u.jsx(ey,{size:20,className:"text-fg/40"}),"Sound Effects"]}),u.jsx("p",{className:"text-xs text-fg/40",children:"Enable audio feedback for sync events and signal discoveries."}),u.jsx("button",{onClick:()=>w(!x),className:`w-full p-4 rounded-xl border-2 transition-all ${x?"bg-primary/10 border-primary/30 text-primary":"bg-surface border-border text-fg/40"}`,children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("span",{className:"font-semibold text-sm",children:x?"Enabled":"Disabled"}),x?u.jsx(Zg,{size:18}):u.jsx(ey,{size:18})]})})]}),u.jsxs("section",{className:"glass p-6 space-y-4",children:[u.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[u.jsx(Yg,{size:20,className:"text-error"}),"Sign Out"]}),u.jsx("p",{className:"text-xs text-fg/40",children:"End your current session and return to the login screen."}),u.jsx("button",{onClick:()=>ne.auth.signOut(),className:"w-full p-4 rounded-xl border-2 bg-error/10 border-error/30 text-error hover:bg-error hover:text-white transition-all",children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("span",{className:"font-semibold text-sm",children:"Logout"}),u.jsx(Yg,{size:18})]})})]}),u.jsx("div",{className:"flex justify-end pt-4 border-t border-border",children:u.jsxs("button",{onClick:_,disabled:l,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[l?u.jsx(Et,{size:18,className:"animate-spin"}):u.jsx(fr,{size:18}),"Preserve Profile"]})})]})}function BP(){const[e,t]=T.useState(""),[n,r]=T.useState(""),[o,a]=T.useState(!1),[l,d]=T.useState(null),[h,p]=T.useState(!1),m=async()=>{if(!e||e!==n){d("Complexity keys do not match.");return}if(e.length<8){d("Entropy too low. Minimum 8 characters.");return}a(!0),d(null),p(!1);const{error:y}=await ne.auth.updateUser({password:e});y?d(y.message):(p(!0),t(""),r("")),a(!1)};return u.jsx("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:u.jsxs("div",{className:"glass p-6 space-y-6",children:[u.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[u.jsx(SS,{size:20,className:"text-error"})," Update Entropy Key"]}),u.jsxs("div",{className:"space-y-4",children:[u.jsx(Yl,{label:"New Password",type:"password",value:e,onChange:t,placeholder:"••••••••"}),u.jsx(Yl,{label:"Confirm Password",type:"password",value:n,onChange:r,placeholder:"••••••••"})]}),l&&u.jsx("p",{className:"text-xs text-error font-mono bg-error/5 p-3 rounded-lg border border-error/10",children:l}),h&&u.jsx("p",{className:"text-xs text-success font-mono bg-success/5 p-3 rounded-lg border border-success/10",children:"Key rotation successful."}),u.jsx("div",{className:"flex justify-end pt-2",children:u.jsxs("button",{onClick:m,disabled:o,className:"px-6 py-3 bg-error/10 text-error hover:bg-error hover:text-white font-bold rounded-xl border border-error/20 transition-all flex items-center gap-2",children:[o?u.jsx(Et,{size:18,className:"animate-spin"}):u.jsx(G0,{size:18}),"Rotate Key"]})})]})})}function $P(){const[e,t]=T.useState(!1),[n,r]=T.useState(null),o=ks(),a=bP();T.useEffect(()=>{o&&zP(ne).then(r)},[]);const l=()=>{confirm("Sever connection to this essence? This will reset local resonance.")&&(vP(),window.location.reload())};return u.jsxs("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:[u.jsxs("section",{className:"space-y-6",children:[u.jsx("div",{className:"flex items-center justify-between",children:u.jsxs("div",{children:[u.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[u.jsx(zo,{size:20,className:"text-primary"})," Essence Resonance"]}),u.jsx("p",{className:"text-xs text-fg/40 font-medium",children:"Bring Your Own Keys (BYOK) for intelligence persistence."})]})}),u.jsx("div",{className:"glass p-8 space-y-8",children:o?u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex items-start gap-4 p-4 glass bg-emerald-500/5 border border-emerald-500/20 rounded-2xl",children:[u.jsx(vs,{className:"w-6 h-6 text-emerald-500 mt-1"}),u.jsxs("div",{className:"flex-1 space-y-1",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("p",{className:"font-bold text-fg italic uppercase tracking-tighter",children:"Established Link"}),n?.latestMigrationTimestamp&&u.jsxs("span",{className:"text-[10px] font-mono bg-emerald-500/10 text-emerald-500 px-2 py-0.5 rounded-full border border-emerald-500/20",children:["v",n.latestMigrationTimestamp]})]}),u.jsx("p",{className:"text-xs font-mono text-fg/40 break-all",children:o.url})]})]}),a==="env"&&u.jsxs("div",{className:"flex items-center gap-3 p-3 bg-amber-500/5 border border-amber-500/10 rounded-xl",children:[u.jsx(pr,{size:16,className:"text-amber-500"}),u.jsx("p",{className:"text-[10px] text-amber-500 font-bold uppercase tracking-widest leading-none",children:"Active from environment variables. UI override enabled."})]}),u.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.jsxs("button",{onClick:()=>t(!0),className:"px-4 py-3 glass hover:bg-surface text-xs font-bold uppercase tracking-widest transition-all flex items-center justify-center gap-2",children:[u.jsx(ec,{size:14})," Realign Link"]}),a==="ui"&&u.jsxs("button",{onClick:l,className:"px-4 py-3 glass border-error/10 hover:bg-error/10 text-error/60 hover:text-error text-xs font-bold uppercase tracking-widest transition-all flex items-center justify-center gap-2",children:[u.jsx(Wh,{size:14})," Sever Link"]})]}),u.jsxs("div",{className:"space-y-1 pt-4 border-t border-border/10",children:[u.jsx("label",{className:"text-[9px] font-bold uppercase tracking-widest text-fg/20 ml-1",children:"Anon Secret Fragment"}),u.jsxs("div",{className:"p-3 bg-surface/50 rounded-xl font-mono text-[11px] text-fg/30 break-all border border-border",children:[o.anonKey.substring(0,32),"..."]})]})]}):u.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-6",children:[u.jsx(zo,{size:48,className:"text-fg/10"}),u.jsxs("div",{className:"space-y-2",children:[u.jsx("p",{className:"font-bold italic uppercase tracking-tighter",children:"No Essence Resonance"}),u.jsx("p",{className:"text-xs text-fg/40 max-w-[240px]",children:"The Alchemist requires a cloud core to store intelligence fragments."})]}),u.jsx("button",{onClick:()=>t(!0),className:"px-8 py-3 bg-primary text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] transition-all uppercase tracking-widest text-xs",children:"Initiate Link"})]})})]}),u.jsx(hb,{open:e,onComplete:()=>t(!1),canClose:!0})]})}function Md({active:e,icon:t,label:n,onClick:r}){return u.jsxs("button",{onClick:r,className:`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${e?"glass bg-primary/10 text-primary border-primary/20 shadow-sm":"text-fg/40 hover:bg-surface hover:text-fg"}`,children:[e?Mo.cloneElement(t,{className:"text-primary"}):t,u.jsx("span",{className:"font-semibold text-sm",children:n})]})}function Yl({label:e,value:t,onChange:n,placeholder:r,type:o="text"}){return u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:e}),u.jsx("input",{type:o,value:t,onChange:a=>n(a.target.value),className:"w-full bg-surface border border-border rounded-xl py-3 px-4 text-sm text-fg placeholder:text-fg/40 focus:border-[var(--border-hover)] outline-none transition-all",placeholder:r})]})}function VP({signal:e,onClose:t}){const[n,r]=Mo.useState(!1);if(!e)return null;const o=()=>{const d=`# ${e.title}
|
|
79
79
|
|
|
80
80
|
**Category**: ${e.category||"Research"}
|
|
81
81
|
**Intelligence Score**: ${e.score}/100
|
|
@@ -122,4 +122,4 @@ ${e.content}`:""}`,h=new Blob([d],{type:"text/markdown"}),p=URL.createObjectURL(
|
|
|
122
122
|
`}),n}function P0(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function R0(e,t){const n=qI(e,t),r=n.one(e,void 0),o=OI(n),a=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return o&&a.children.push({type:"text",value:`
|
|
123
123
|
`},o),a}function JI(e,t){return e&&"run"in e?async function(n,r){const o=R0(n,{file:r,...t});await e.run(o,r)}:function(n,r){return R0(n,{file:r,...e||t})}}function O0(e){if(e)throw e}var Vd,I0;function YI(){if(I0)return Vd;I0=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,o=function(p){return typeof Array.isArray=="function"?Array.isArray(p):t.call(p)==="[object Array]"},a=function(p){if(!p||t.call(p)!=="[object Object]")return!1;var m=e.call(p,"constructor"),y=p.constructor&&p.constructor.prototype&&e.call(p.constructor.prototype,"isPrototypeOf");if(p.constructor&&!m&&!y)return!1;var x;for(x in p);return typeof x>"u"||e.call(p,x)},l=function(p,m){n&&m.name==="__proto__"?n(p,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):p[m.name]=m.newValue},d=function(p,m){if(m==="__proto__")if(e.call(p,m)){if(r)return r(p,m).value}else return;return p[m]};return Vd=function h(){var p,m,y,x,w,b,_=arguments[0],k=1,S=arguments.length,E=!1;for(typeof _=="boolean"&&(E=_,_=arguments[1]||{},k=2),(_==null||typeof _!="object"&&typeof _!="function")&&(_={});k<S;++k)if(p=arguments[k],p!=null)for(m in p)y=d(_,m),x=d(p,m),_!==x&&(E&&x&&(a(x)||(w=o(x)))?(w?(w=!1,b=y&&o(y)?y:[]):b=y&&a(y)?y:{},l(_,{name:m,newValue:h(E,b,x)})):typeof x<"u"&&l(_,{name:m,newValue:x}));return _},Vd}var XI=YI();const qd=Zl(XI);function Fh(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function QI(){const e=[],t={run:n,use:r};return t;function n(...o){let a=-1;const l=o.pop();if(typeof l!="function")throw new TypeError("Expected function as last argument, not "+l);d(null,...o);function d(h,...p){const m=e[++a];let y=-1;if(h){l(h);return}for(;++y<o.length;)(p[y]===null||p[y]===void 0)&&(p[y]=o[y]);o=p,m?ZI(m,d)(...p):l(null,...p)}}function r(o){if(typeof o!="function")throw new TypeError("Expected `middelware` to be a function, not "+o);return e.push(o),t}}function ZI(e,t){let n;return r;function r(...l){const d=e.length>l.length;let h;d&&l.push(o);try{h=e.apply(this,l)}catch(p){const m=p;if(d&&n)throw m;return o(m)}d||(h&&h.then&&typeof h.then=="function"?h.then(a,o):h instanceof Error?o(h):a(h))}function o(l,...d){n||(n=!0,t(l,...d))}function a(l){o(null,l)}}const Qn={basename:e5,dirname:t5,extname:n5,join:r5,sep:"/"};function e5(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');aa(e);let n=0,r=-1,o=e.length,a;if(t===void 0||t.length===0||t.length>e.length){for(;o--;)if(e.codePointAt(o)===47){if(a){n=o+1;break}}else r<0&&(a=!0,r=o+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let l=-1,d=t.length-1;for(;o--;)if(e.codePointAt(o)===47){if(a){n=o+1;break}}else l<0&&(a=!0,l=o+1),d>-1&&(e.codePointAt(o)===t.codePointAt(d--)?d<0&&(r=o):(d=-1,r=l));return n===r?r=l:r<0&&(r=e.length),e.slice(n,r)}function t5(e){if(aa(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function n5(e){aa(e);let t=e.length,n=-1,r=0,o=-1,a=0,l;for(;t--;){const d=e.codePointAt(t);if(d===47){if(l){r=t+1;break}continue}n<0&&(l=!0,n=t+1),d===46?o<0?o=t:a!==1&&(a=1):o>-1&&(a=-1)}return o<0||n<0||a===0||a===1&&o===n-1&&o===r+1?"":e.slice(o,n)}function r5(...e){let t=-1,n;for(;++t<e.length;)aa(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":s5(n)}function s5(e){aa(e);const t=e.codePointAt(0)===47;let n=i5(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function i5(e,t){let n="",r=0,o=-1,a=0,l=-1,d,h;for(;++l<=e.length;){if(l<e.length)d=e.codePointAt(l);else{if(d===47)break;d=47}if(d===47){if(!(o===l-1||a===1))if(o!==l-1&&a===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(h=n.lastIndexOf("/"),h!==n.length-1){h<0?(n="",r=0):(n=n.slice(0,h),r=n.length-1-n.lastIndexOf("/")),o=l,a=0;continue}}else if(n.length>0){n="",r=0,o=l,a=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(o+1,l):n=e.slice(o+1,l),r=l-o-1;o=l,a=0}else d===46&&a>-1?a++:a=-1}return n}function aa(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const o5={cwd:a5};function a5(){return"/"}function Bh(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function l5(e){if(typeof e=="string")e=new URL(e);else if(!Bh(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return c5(e)}function c5(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const r=t.codePointAt(n+2);if(r===70||r===102){const o=new TypeError("File URL path must not include encoded / characters");throw o.code="ERR_INVALID_FILE_URL_PATH",o}}return decodeURIComponent(t)}const Hd=["history","path","basename","stem","extname","dirname"];class Zb{constructor(t){let n;t?Bh(t)?n={path:t}:typeof t=="string"||u5(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":o5.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<Hd.length;){const a=Hd[r];a in n&&n[a]!==void 0&&n[a]!==null&&(this[a]=a==="history"?[...n[a]]:n[a])}let o;for(o in n)Hd.includes(o)||(this[o]=n[o])}get basename(){return typeof this.path=="string"?Qn.basename(this.path):void 0}set basename(t){Kd(t,"basename"),Wd(t,"basename"),this.path=Qn.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?Qn.dirname(this.path):void 0}set dirname(t){D0(this.basename,"dirname"),this.path=Qn.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?Qn.extname(this.path):void 0}set extname(t){if(Wd(t,"extname"),D0(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=Qn.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Bh(t)&&(t=l5(t)),Kd(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?Qn.basename(this.path,this.extname):void 0}set stem(t){Kd(t,"stem"),Wd(t,"stem"),this.path=Qn.join(this.dirname||"",t+(this.extname||""))}fail(t,n,r){const o=this.message(t,n,r);throw o.fatal=!0,o}info(t,n,r){const o=this.message(t,n,r);return o.fatal=void 0,o}message(t,n,r){const o=new Wt(t,n,r);return this.path&&(o.name=this.path+":"+o.name,o.file=this.path),o.fatal=!1,this.messages.push(o),o}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function Wd(e,t){if(e&&e.includes(Qn.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+Qn.sep+"`")}function Kd(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function D0(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function u5(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const d5=(function(e){const r=this.constructor.prototype,o=r[e],a=function(){return o.apply(a,arguments)};return Object.setPrototypeOf(a,r),a}),h5={}.hasOwnProperty;class Zf extends d5{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=QI()}copy(){const t=new Zf;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];t.use(...r)}return t.data(qd(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(Yd("data",this.frozen),this.namespace[t]=n,this):h5.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Yd("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const o=n.call(t,...r);typeof o=="function"&&this.transformers.use(o)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=Nl(t),r=this.parser||this.Parser;return Gd("parse",r),r(String(n),n)}process(t,n){const r=this;return this.freeze(),Gd("process",this.parser||this.Parser),Jd("process",this.compiler||this.Compiler),n?o(void 0,n):new Promise(o);function o(a,l){const d=Nl(t),h=r.parse(d);r.run(h,d,function(m,y,x){if(m||!y||!x)return p(m);const w=y,b=r.stringify(w,x);m5(b)?x.value=b:x.result=b,p(m,x)});function p(m,y){m||!y?l(m):a?a(y):n(void 0,y)}}}processSync(t){let n=!1,r;return this.freeze(),Gd("processSync",this.parser||this.Parser),Jd("processSync",this.compiler||this.Compiler),this.process(t,o),M0("processSync","process",n),r;function o(a,l){n=!0,O0(a),r=l}}run(t,n,r){L0(t),this.freeze();const o=this.transformers;return!r&&typeof n=="function"&&(r=n,n=void 0),r?a(void 0,r):new Promise(a);function a(l,d){const h=Nl(n);o.run(t,h,p);function p(m,y,x){const w=y||t;m?d(m):l?l(w):r(void 0,w,x)}}}runSync(t,n){let r=!1,o;return this.run(t,n,a),M0("runSync","run",r),o;function a(l,d){O0(l),o=d,r=!0}}stringify(t,n){this.freeze();const r=Nl(n),o=this.compiler||this.Compiler;return Jd("stringify",o),L0(t),o(t,r)}use(t,...n){const r=this.attachers,o=this.namespace;if(Yd("use",this.frozen),t!=null)if(typeof t=="function")h(t,n);else if(typeof t=="object")Array.isArray(t)?d(t):l(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function a(p){if(typeof p=="function")h(p,[]);else if(typeof p=="object")if(Array.isArray(p)){const[m,...y]=p;h(m,y)}else l(p);else throw new TypeError("Expected usable value, not `"+p+"`")}function l(p){if(!("plugins"in p)&&!("settings"in p))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");d(p.plugins),p.settings&&(o.settings=qd(!0,o.settings,p.settings))}function d(p){let m=-1;if(p!=null)if(Array.isArray(p))for(;++m<p.length;){const y=p[m];a(y)}else throw new TypeError("Expected a list of plugins, not `"+p+"`")}function h(p,m){let y=-1,x=-1;for(;++y<r.length;)if(r[y][0]===p){x=y;break}if(x===-1)r.push([p,...m]);else if(m.length>0){let[w,...b]=m;const _=r[x][1];Fh(_)&&Fh(w)&&(w=qd(!0,_,w)),r[x]=[p,w,...b]}}}}const f5=new Zf().freeze();function Gd(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Jd(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Yd(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function L0(e){if(!Fh(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function M0(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function Nl(e){return p5(e)?e:new Zb(e)}function p5(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function m5(e){return typeof e=="string"||g5(e)}function g5(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const y5="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",z0=[],U0={allowDangerousHtml:!0},x5=/^(https?|ircs?|mailto|xmpp)$/i,v5=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function ep(e){const t=w5(e),n=b5(e);return k5(t.runSync(t.parse(n),n),e)}function w5(e){const t=e.rehypePlugins||z0,n=e.remarkPlugins||z0,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...U0}:U0;return f5().use(eI).use(n).use(JI,r).use(t)}function b5(e){const t=e.children||"",n=new Zb;return typeof t=="string"&&(n.value=t),n}function k5(e,t){const n=t.allowedElements,r=t.allowElement,o=t.components,a=t.disallowedElements,l=t.skipHtml,d=t.unwrapDisallowed,h=t.urlTransform||S5;for(const m of v5)Object.hasOwn(t,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+y5+m.id,void 0);return Qb(e,p),OR(e,{Fragment:u.Fragment,components:o,ignoreInvalidStyle:!0,jsx:u.jsx,jsxs:u.jsxs,passKeys:!0,passNode:!0});function p(m,y,x){if(m.type==="raw"&&x&&typeof y=="number")return l?x.children.splice(y,1):x.children[y]={type:"text",value:m.value},y;if(m.type==="element"){let w;for(w in Fd)if(Object.hasOwn(Fd,w)&&Object.hasOwn(m.properties,w)){const b=m.properties[w],_=Fd[w];(_===null||_.includes(m.tagName))&&(m.properties[w]=h(String(b||""),w,m))}}if(m.type==="element"){let w=n?!n.includes(m.tagName):a?a.includes(m.tagName):!1;if(!w&&r&&typeof y=="number"&&(w=!r(m,y,x)),w&&x&&typeof y=="number")return d&&m.children?x.children.splice(y,1,...m.children):x.children.splice(y,1),y}}}function S5(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),o=e.indexOf("/");return t===-1||o!==-1&&t>o||n!==-1&&t>n||r!==-1&&t>r||x5.test(e.slice(0,t))?e:""}function _5({message:e}){const t=e.role==="user";return u.jsx("div",{className:`flex w-full ${t?"justify-end":"justify-start"}`,children:u.jsxs("div",{className:`flex gap-3 max-w-[85%] ${t?"flex-row-reverse":"flex-row"}`,children:[u.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${t?"bg-primary text-white":"bg-gradient-to-br from-indigo-500 to-purple-600 text-white shadow-lg glow-primary"}`,children:t?u.jsx(tc,{size:16}):u.jsx(cS,{size:16})}),u.jsxs("div",{className:`flex flex-col ${t?"items-end":"items-start"}`,children:[u.jsx("div",{className:`px-5 py-3.5 rounded-2xl text-sm leading-relaxed shadow-sm ${t?"bg-primary/10 text-fg border border-primary/20 rounded-tr-none":"bg-surface/80 backdrop-blur-md text-fg border border-border/40 rounded-tl-none"}`,children:t?u.jsx("p",{className:"whitespace-pre-wrap",children:e.content}):u.jsx("div",{className:"markdown-body",children:u.jsx(ep,{components:{p:({node:n,...r})=>u.jsx("p",{className:"mb-2 last:mb-0",...r}),a:({node:n,...r})=>u.jsx("a",{className:"text-primary hover:underline",...r}),ul:({node:n,...r})=>u.jsx("ul",{className:"list-disc ml-4 mb-2",...r}),ol:({node:n,...r})=>u.jsx("ol",{className:"list-decimal ml-4 mb-2",...r}),code:({node:n,...r})=>u.jsx("code",{className:"bg-black/20 rounded px-1 py-0.5 font-mono text-xs",...r})},children:e.content})})}),u.jsx("span",{className:"text-[10px] text-fg/30 mt-1 px-1",children:new Date(e.created_at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]})]})})}function j5({sessionId:e,onContextUpdate:t,onNewSession:n,onSessionCreated:r}){const[o,a]=T.useState([]),[l,d]=T.useState(""),[h,p]=T.useState(!1),[m,y]=T.useState(!1),x=T.useRef(null),w=T.useRef(null);T.useEffect(()=>{e?b(e):(a([]),t([]))},[e,t]),T.useEffect(()=>{x.current&&x.current.scrollIntoView({behavior:"smooth"})},[o,m]);const b=async S=>{try{const{data:{session:E}}=await ne.auth.getSession();if(!E)return;const N=await Ke.get(`/api/chat/sessions/${S}/messages`,{headers:{"x-user-id":E.user.id}});if(N.data.success){a(N.data.messages);const R=N.data.messages[N.data.messages.length-1];R&&R.role==="assistant"&&R.context_sources&&t(R.context_sources)}}catch(E){console.error("Failed to fetch messages",E)}},_=async S=>{if(S?.preventDefault(),!l.trim()||h)return;const E=l.trim();d(""),w.current&&(w.current.style.height="auto");const{data:{session:N}}=await ne.auth.getSession();if(!N)return;const R=N.user.id;p(!0),y(!0);try{let M=e;if(!M){const V=await Ke.post("/api/chat/sessions",{},{headers:{"x-user-id":R}});if(V.data.success)M=V.data.session.id,r(M);else throw new Error("Failed to create session")}const O={id:"temp-"+Date.now(),role:"user",content:E,created_at:new Date().toISOString()};a(V=>[...V,O]);const q=await Ke.post("/api/chat/message",{sessionId:M,content:E},{headers:{"x-user-id":R}});if(q.data.success){const V=q.data.message;a(W=>[...W,V]),V.context_sources&&t(V.context_sources)}}catch(M){console.error("Message failed",M),a(O=>[...O,{id:"err-"+Date.now(),role:"assistant",content:"Sorry, I encountered an error processing your request.",created_at:new Date().toISOString()}])}finally{p(!1),y(!1)}},k=S=>{S.key==="Enter"&&!S.shiftKey&&(S.preventDefault(),_())};return u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[o.length===0?u.jsxs("div",{className:"h-full flex flex-col items-center justify-center p-8 text-center opacity-60",children:[u.jsx("div",{className:"w-16 h-16 bg-primary/10 rounded-2xl flex items-center justify-center mb-4 text-primary animate-pulse",children:u.jsx(LS,{size:32})}),u.jsx("h3",{className:"text-xl font-bold mb-2",children:"Ask Alchemist"}),u.jsx("p",{className:"text-sm max-w-md mx-auto mb-8",children:"I can help you recall information, summarize topics, and find insights from your browsing history."}),u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 max-w-lg w-full",children:["What have I read about React recently?","Summarize the latest AI news I visited.","Do I have any notes on Finance?","Find articles about 'Performance'"].map((S,E)=>u.jsx("button",{onClick:()=>d(S),className:"text-left p-3 text-xs bg-surface/50 hover:bg-surface border border-border/30 rounded-xl transition-all hover:scale-[1.02]",children:S},E))})]}):u.jsxs(u.Fragment,{children:[o.map((S,E)=>u.jsx(_5,{message:S},S.id||E)),m&&u.jsx(ze.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"flex justify-start w-full",children:u.jsxs("div",{className:"bg-surface/50 border border-border/30 rounded-2xl px-4 py-3 flex items-center gap-3",children:[u.jsxs("div",{className:"flex gap-1",children:[u.jsx("span",{className:"w-1.5 h-1.5 bg-primary/60 rounded-full animate-bounce",style:{animationDelay:"0s"}}),u.jsx("span",{className:"w-1.5 h-1.5 bg-primary/60 rounded-full animate-bounce",style:{animationDelay:"0.1s"}}),u.jsx("span",{className:"w-1.5 h-1.5 bg-primary/60 rounded-full animate-bounce",style:{animationDelay:"0.2s"}})]}),u.jsx("span",{className:"text-xs text-fg/50 font-mono",children:"Exploring memory..."})]})})]}),u.jsx("div",{ref:x})]}),u.jsx("div",{className:"p-4 bg-surface/30 border-t border-border/10 backdrop-blur-md",children:u.jsx("form",{onSubmit:_,className:"relative max-w-4xl mx-auto",children:u.jsxs("div",{className:"relative flex items-end gap-2 bg-surface/80 border border-border/40 rounded-2xl px-2 py-2 shadow-sm focus-within:ring-2 focus-within:ring-primary/50 focus-within:border-primary/50 transition-all",children:[u.jsx("textarea",{ref:w,value:l,onChange:S=>{d(S.target.value),S.target.style.height="auto",S.target.style.height=S.target.scrollHeight+"px"},onKeyDown:k,placeholder:"Ask about your history...",rows:1,className:"w-full bg-transparent border-none focus:ring-0 focus:outline-none py-2 pl-2 text-fg resize-none min-h-[24px] max-h-[200px] placeholder:text-fg/40",disabled:h}),u.jsx("button",{type:"submit",disabled:!l.trim()||h,className:"p-2 mb-0.5 bg-primary text-white rounded-xl shadow-lg hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all shrink-0",children:h?u.jsx(ec,{size:18,className:"animate-spin"}):u.jsx(IS,{size:18})})]})})})]})}function E5({sources:e,onClose:t}){return!e||e.length===0?null:u.jsxs(ze.div,{initial:{opacity:0,x:20,width:0},animate:{opacity:1,x:0,width:300},exit:{opacity:0,x:20,width:0},className:"glass rounded-2xl border border-border/40 overflow-hidden flex flex-col",children:[u.jsxs("div",{className:"p-4 border-b border-border/10 flex items-center justify-between bg-surface/30",children:[u.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-fg/80",children:[u.jsx($0,{size:16,className:"text-secondary"}),u.jsx("span",{children:"Relevant Context"})]}),u.jsx("button",{onClick:t,className:"p-1 hover:bg-surface rounded-md text-fg/40 hover:text-fg transition-colors",children:u.jsx(wn,{size:14})})]}),u.jsx("div",{className:"flex-1 overflow-y-auto p-3 space-y-3",children:e.map((n,r)=>u.jsxs("div",{className:"p-3 bg-surface/40 hover:bg-surface/60 border border-border/20 rounded-xl transition-all group",children:[u.jsxs("div",{className:"flex justify-between items-start mb-2",children:[u.jsxs("div",{className:"flex items-center gap-1.5",children:[u.jsx("span",{className:"flex items-center justify-center w-4 h-4 bg-primary/10 text-primary text-[10px] font-bold rounded",children:r+1}),u.jsxs("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded border ${n.score>=80?"bg-yellow-500/10 text-yellow-500 border-yellow-500/20":"bg-blue-500/10 text-blue-400 border-blue-500/20"}`,children:[n.score,"% Match"]})]}),u.jsx("a",{href:n.url,target:"_blank",rel:"noopener noreferrer",className:"opacity-0 group-hover:opacity-100 text-fg/40 hover:text-primary transition-opacity",children:u.jsx(Ei,{size:12})})]}),u.jsx("a",{href:n.url,target:"_blank",rel:"noopener noreferrer",className:"text-xs font-bold text-fg/90 block mb-1 hover:text-primary transition-colors line-clamp-2",children:n.title}),u.jsx("p",{className:"text-[10px] text-fg/50 line-clamp-3 leading-relaxed",children:n.summary})]},r))}),u.jsxs("div",{className:"p-3 border-t border-border/10 bg-surface/30 text-[10px] text-center text-fg/30",children:["Alchemist used these ",e.length," signals to answer"]})]})}function N5(){const[e,t]=T.useState(null),[n,r]=T.useState([]),[o,a]=T.useState(!0);return u.jsxs("div",{className:"flex h-full gap-4 overflow-hidden",children:[u.jsx(sR,{activeSessionId:e,onSelectSession:t}),u.jsx("div",{className:"flex-1 flex flex-col min-w-0 glass rounded-2xl overflow-hidden border border-border/40 relative",children:u.jsx(j5,{sessionId:e,onContextUpdate:l=>{r(l),l.length>0&&a(!0)},onNewSession:()=>t(null),onSessionCreated:l=>t(l)})}),o&&u.jsx(E5,{sources:n,onClose:()=>a(!1)})]})}function C5({isOpen:e,onClose:t}){const[n,r]=T.useState(""),[o,a]=T.useState(!0);T.useEffect(()=>{e&&l()},[e]);const l=async()=>{a(!0);try{const h=await(await fetch("/CHANGELOG.md")).text();r(h)}catch(d){console.error("Failed to load changelog:",d),r(`# Error
|
|
124
124
|
|
|
125
|
-
Failed to load changelog.`)}finally{a(!1)}};return u.jsx(Pt,{children:e&&u.jsxs(u.Fragment,{children:[u.jsx(ze.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:t,className:"fixed inset-0 bg-black/60 backdrop-blur-sm z-50"}),u.jsx(ze.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{type:"spring",damping:25,stiffness:300},className:"fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none",children:u.jsxs("div",{className:"glass w-full max-w-3xl max-h-[80vh] overflow-hidden pointer-events-auto shadow-2xl",children:[u.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx($0,{size:24,className:"text-primary"}),u.jsx("h2",{className:"text-xl font-bold",children:"Release Notes"})]}),u.jsx("button",{onClick:t,className:"p-2 hover:bg-surface rounded-lg transition-colors",children:u.jsx(wn,{size:20,className:"text-fg/60"})})]}),u.jsx("div",{className:"p-6 overflow-y-auto custom-scrollbar max-h-[calc(80vh-88px)]",children:o?u.jsx("div",{className:"flex items-center justify-center py-12",children:u.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-primary border-t-transparent"})}):u.jsx(ep,{components:{h1:({children:d})=>u.jsx("h1",{className:"text-2xl font-bold text-fg mb-6 mt-0",children:d}),h2:({children:d})=>u.jsx("h2",{className:"text-xl font-bold text-fg mt-8 mb-3 pb-2 border-b border-border first:mt-0",children:d}),h3:({children:d})=>u.jsx("h3",{className:"text-lg font-bold text-primary mt-6 mb-2",children:d}),p:({children:d})=>u.jsx("p",{className:"text-sm text-fg/70 mb-3 leading-relaxed",children:d}),ul:({children:d})=>u.jsx("ul",{className:"list-none space-y-1 mb-4 ml-0",children:d}),li:({children:d})=>u.jsx("li",{className:"text-sm text-fg/80 ml-4 mb-1 before:content-['•'] before:mr-2 before:text-primary",children:d}),a:({href:d,children:h})=>u.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:text-primary/80 underline transition-colors",children:h}),code:({children:d})=>u.jsx("code",{className:"bg-surface/50 text-accent px-1.5 py-0.5 rounded text-xs font-mono border border-border",children:d}),strong:({children:d})=>u.jsx("strong",{className:"font-bold text-fg",children:d})},children:n})})]})})]})})}function T5({asset:e,onClose:t}){const n=()=>{e.content&&navigator.clipboard.writeText(e.content)},r=()=>{if(!e.content)return;const o=new Blob([e.content],{type:"text/markdown"}),a=URL.createObjectURL(o),l=document.createElement("a");l.href=a,l.download=`${e.title.replace(/[^a-z0-9]/gi,"_").toLowerCase()}.md`,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(a)};return u.jsx(Pt,{children:e&&u.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:u.jsxs(ze.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[u.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"p-2 rounded-lg bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400",children:e.type==="audio"?u.jsx(Zd,{className:"w-5 h-5"}):u.jsx(wi,{className:"w-5 h-5"})}),u.jsxs("div",{children:[u.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e.title}),u.jsxs("p",{className:"text-xs text-gray-500",children:["Generated ",new Date(e.created_at).toLocaleString()," • ",e.metadata?.source_signal_count||0," sources"]})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:n,className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",title:"Copy Content",children:u.jsx(Vh,{className:"w-4 h-4"})}),u.jsx("button",{onClick:r,className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",title:"Download File",children:u.jsx(Xd,{className:"w-4 h-4"})}),u.jsx("div",{className:"w-px h-6 bg-gray-200 dark:bg-gray-700 mx-1"}),u.jsx("button",{onClick:t,className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:u.jsx(wn,{className:"w-5 h-5"})})]})]}),u.jsx("div",{className:"flex-1 overflow-y-auto p-6 bg-white dark:bg-gray-950",children:e.status&&e.status!=="completed"?u.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-4",children:[u.jsx(Et,{className:"w-12 h-12 animate-spin text-purple-500"}),u.jsxs("div",{className:"text-center",children:[u.jsx("h4",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:e.status==="processing"?"Generating Asset...":"Queued for Desktop..."}),u.jsx("p",{className:"text-sm text-gray-500 max-w-xs mt-1",children:"The RealTimeX Desktop app is processing this request. This modal will update automatically once finished."})]})]}):e.type==="markdown"?u.jsx("div",{className:"prose dark:prose-invert max-w-none",children:u.jsx(ep,{children:e.content||""})}):e.type==="audio"?u.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-4",children:[u.jsx("div",{className:"w-16 h-16 rounded-full bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center animate-pulse",children:u.jsx(Zd,{className:"w-8 h-8 text-purple-600 dark:text-purple-400"})}),u.jsx("p",{className:"text-gray-500",children:"Audio playback not yet implemented (Simulated)"}),u.jsxs("audio",{controls:!0,className:"w-full max-w-md mt-4",children:[u.jsx("source",{src:e.content||"",type:"audio/mpeg"}),"Your browser does not support the audio element."]})]}):u.jsx("div",{className:"text-gray-500 text-center py-10",children:"Unsupported asset type"})})]})})})}function F0({engine:e,onClose:t,onSave:n,onDelete:r}){const{showToast:o}=yc(),[a,l]=T.useState({title:"",type:"newsletter",status:"active",config:{schedule:"",min_score:70,categories:[],custom_prompt:"",max_signals:10,execution_mode:"local"}}),[d,h]=T.useState(!1);T.useEffect(()=>{e&&l({title:e.title,type:e.type,status:e.status,config:{schedule:e.config.schedule||"",min_score:e.config.filters?.min_score||70,categories:Array.isArray(e.config.category)?e.config.category:e.config.category?[e.config.category]:[],custom_prompt:e.config.custom_prompt||"",max_signals:e.config.max_signals||10,execution_mode:e.config.execution_mode||"local"}})},[e]);const p=async()=>{try{const x={title:a.title,type:a.type,status:a.status,config:{schedule:a.config.schedule,filters:{min_score:a.config.min_score,category:a.config.category},custom_prompt:a.config.custom_prompt,max_signals:a.config.max_signals,execution_mode:a.config.execution_mode}};if(e){const{data:w,error:b}=await ne.from("engines").update(x).eq("id",e.id).select().single();if(b)throw b;n(w),o("Engine updated successfully","success")}else{const{data:{user:w}}=await ne.auth.getUser();if(!w)throw new Error("Not authenticated");const{data:b,error:_}=await ne.from("engines").insert({...x,user_id:w.id}).select().single();if(_)throw _;n(b),o("Engine created successfully","success")}t()}catch(x){console.error("Save error:",x),o(x.message||"Failed to save engine","error")}},m=async()=>{if(!(!e||!r))try{const{error:x}=await ne.from("engines").delete().eq("id",e.id);if(x)throw x;r(e.id),o("Engine deleted","success"),t()}catch(x){o(x.message||"Failed to delete engine","error")}},y=()=>{h(!1),t()};return!e&&!t?null:u.jsx(Pt,{children:u.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:u.jsxs(ze.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-2xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[u.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800",children:[u.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:e?"Edit Engine":"Create Engine"}),u.jsx("button",{onClick:y,className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:u.jsx(wn,{className:"w-5 h-5"})})]}),u.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Engine Name"}),u.jsx("input",{type:"text",value:a.title,onChange:x=>l({...a,title:x.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:"e.g., Daily Tech Brief"})]}),u.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Type"}),u.jsxs("select",{value:a.type,onChange:x=>l({...a,type:x.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[u.jsx("option",{value:"newsletter",children:"Newsletter"}),u.jsx("option",{value:"thread",children:"Thread"}),u.jsx("option",{value:"audio",children:"Audio Brief"}),u.jsx("option",{value:"report",children:"Report"})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Status"}),u.jsxs("select",{value:a.status,onChange:x=>l({...a,status:x.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[u.jsx("option",{value:"active",children:"Active"}),u.jsx("option",{value:"paused",children:"Paused"}),u.jsx("option",{value:"draft",children:"Draft"})]})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Execution Environment"}),u.jsxs("select",{value:a.config.execution_mode,onChange:x=>l({...a,config:{...a.config,execution_mode:x.target.value}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[u.jsx("option",{value:"local",children:"Local (Alchemy LLM)"}),u.jsx("option",{value:"desktop",children:"RealTimeX Desktop (Agent Swarm)"})]}),u.jsx("p",{className:"text-[10px] text-gray-500 mt-1",children:a.config.execution_mode==="desktop"?"Delegates heavy tasks like Audio/Video to the desktop app.":"Runs simple Markdown tasks directly in Alchemy."})]})]}),u.jsxs("div",{className:"space-y-4",children:[u.jsx("h4",{className:"font-medium text-gray-900 dark:text-gray-100",children:"Signal Filters"}),u.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Min Score"}),u.jsx("input",{type:"number",min:"0",max:"100",value:a.config.min_score,onChange:x=>l({...a,config:{...a.config,min_score:parseInt(x.target.value)||0}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Max Signals"}),u.jsx("input",{type:"number",min:"1",max:"50",value:a.config.max_signals,onChange:x=>l({...a,config:{...a.config,max_signals:parseInt(x.target.value)||10}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Category Filter (multi-select)"}),u.jsxs("select",{multiple:!0,value:a.config.categories,onChange:x=>{const w=Array.from(x.target.selectedOptions,b=>b.value);l({...a,config:{...a.config,categories:w}})},className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 min-h-[100px]",children:[u.jsx("option",{value:"AI & ML",children:"AI & ML"}),u.jsx("option",{value:"Technology",children:"Technology"}),u.jsx("option",{value:"Business",children:"Business"}),u.jsx("option",{value:"Finance",children:"Finance"}),u.jsx("option",{value:"Science",children:"Science"}),u.jsx("option",{value:"Politics",children:"Politics"})]}),u.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Hold Cmd/Ctrl to select multiple categories"})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Schedule (optional)"}),u.jsx("input",{type:"text",value:a.config.schedule,onChange:x=>l({...a,config:{...a.config,schedule:x.target.value}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",placeholder:"e.g., Daily @ 9am, Manual"}),u.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Note: Scheduling is not yet automated"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Custom Prompt Override (optional)"}),u.jsx("textarea",{value:a.config.custom_prompt,onChange:x=>l({...a,config:{...a.config,custom_prompt:x.target.value}}),rows:4,className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 resize-none",placeholder:"Override the default prompt for this engine type..."})]})]}),u.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50",children:[e&&r?d?u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("span",{className:"text-sm text-red-600 font-medium",children:"Really delete?"}),u.jsx("button",{onClick:m,className:"px-3 py-1.5 bg-red-600 text-white text-xs rounded-lg hover:bg-red-700 transition-colors",children:"Confirm"}),u.jsx("button",{onClick:()=>h(!1),className:"px-3 py-1.5 text-gray-500 hover:text-gray-700 text-xs rounded-lg",children:"Cancel"})]}):u.jsxs("button",{onClick:()=>h(!0),className:"flex items-center gap-2 px-4 py-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:[u.jsx(Wh,{className:"w-4 h-4"}),"Delete"]}):u.jsx("div",{}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx("button",{onClick:y,className:"px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:"Cancel"}),u.jsxs("button",{onClick:p,className:"flex items-center gap-2 px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors",children:[u.jsx(fr,{className:"w-4 h-4"}),"Save"]})]})]})]})})})}const A5=({engine:e,onRun:t,onEdit:n,onToggle:r,onViewBrief:o,isLoading:a})=>{const l=!!e.config.tag,d={newsletter:l?u.jsx(qh,{className:"w-5 h-5 text-blue-500"}):u.jsx(wi,{className:"w-5 h-5 text-emerald-500"}),thread:u.jsx(Yt,{className:"w-5 h-5 text-blue-500"}),audio:u.jsx(Zd,{className:"w-5 h-5 text-purple-500"}),report:u.jsx(Ml,{className:"w-5 h-5 text-orange-500"})};return u.jsxs(ze.div,{layout:!0,initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:`p-5 rounded-2xl border ${e.status==="active"?"bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700 shadow-sm":"bg-gray-50 dark:bg-gray-900 border-dashed border-gray-300 dark:border-gray-700 opacity-75"} transition-all hover:shadow-md group`,children:[u.jsxs("div",{className:"flex justify-between items-start mb-4",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"p-2 rounded-xl bg-gray-100 dark:bg-gray-800",children:d[e.type]||u.jsx(wi,{className:"w-5 h-5"})}),u.jsxs("div",{children:[u.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e.title}),u.jsxs("p",{className:"text-xs text-gray-500 capitalize",children:[l?"Topic":e.type," Pipeline"]})]})]}),u.jsxs("div",{className:"flex gap-1",children:[u.jsx("button",{onClick:()=>r(e.id,e.status),className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:e.status==="active"?u.jsx(PS,{className:"w-4 h-4"}):u.jsx(Xg,{className:"w-4 h-4"})}),u.jsx("button",{onClick:()=>o(e.id),title:"View Production Brief JSON",className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:u.jsx(H0,{className:"w-4 h-4"})}),u.jsx("button",{onClick:()=>n(e.id),className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:u.jsx(Ml,{className:"w-4 h-4"})})]})]}),u.jsxs("div",{className:"space-y-2 mb-4",children:[u.jsxs("div",{className:"text-xs text-gray-500 flex justify-between",children:[u.jsx("span",{children:"Last Run"}),u.jsx("span",{children:e.last_run_at?new Date(e.last_run_at).toLocaleDateString():"Never"})]}),u.jsxs("div",{className:"text-xs text-gray-500 flex justify-between",children:[u.jsx("span",{children:"Schedule"}),u.jsx("span",{children:e.config.schedule||"Manual"})]})]}),u.jsxs("button",{onClick:()=>t(e.id),disabled:a||e.status!=="active",className:"w-full flex items-center justify-center gap-2 py-2 rounded-xl bg-gray-900 dark:bg-white text-white dark:text-gray-900 font-medium hover:opacity-90 disabled:opacity-50 transition-all text-sm",children:[a?u.jsx(Et,{className:"w-4 h-4 animate-spin"}):u.jsx(Xg,{className:"w-4 h-4"}),a?"Running...":"Run Engine"]})]})};function P5(){const[e,t]=T.useState([]),[n,r]=T.useState(!0),[o,a]=T.useState(new Set),[l,d]=T.useState(null),[h,p]=T.useState(null),[m,y]=T.useState(!1),[x,w]=T.useState(null),[b,_]=T.useState(!1),[k,S]=T.useState(!1),{showToast:E}=yc();T.useEffect(()=>{(async()=>R())();const J=ne.channel("asset-updates").on("postgres_changes",{event:"UPDATE",schema:"public",table:"assets"},H=>{const re=H.new;d(ae=>ae?.id===re.id?re:ae),re.status==="completed"&&H.old.status!=="completed"&&E(`Asset "${re.title}" is ready!`,"success")}).subscribe();return()=>{ne.removeChannel(J)}},[]);const N=async()=>{if(!k)try{S(!0),E("Scanning for new categories and topics...","info");const{data:{session:ee}}=await ne.auth.getSession(),J=ks(),H={"Content-Type":"application/json","x-user-id":ee?.user?.id||""};if(ee?.access_token&&(H.Authorization=`Bearer ${ee.access_token}`),J&&(H["x-supabase-url"]=J.url,H["x-supabase-key"]=J.anonKey),!(await fetch("/api/engines/ensure-defaults",{method:"POST",headers:H})).ok)throw new Error("Failed to generate engines");E("Engine discovery complete!","success"),await R()}catch(ee){console.error("Failed to generate engines:",ee),E("Discovery failed. Check settings.","error")}finally{S(!1)}},R=async()=>{try{r(!0);const{data:{user:ee}}=await ne.auth.getUser();if(!ee)return;const{data:J,error:H}=await ne.from("engines").select("*").eq("user_id",ee.id).order("created_at",{ascending:!1});if(H)throw H;t(J)}catch(ee){console.error("Error fetching engines:",ee),E("Failed to load engines","error")}finally{r(!1)}},M=async ee=>{if(!o.has(ee))try{a(C=>new Set(C).add(ee)),E("Starting engine run...","info");const{data:{session:J}}=await ne.auth.getSession(),H=J?.access_token,re=ks(),ae={"Content-Type":"application/json","x-user-id":J?.user?.id||""};H&&(ae.Authorization=`Bearer ${H}`),re&&(ae["x-supabase-url"]=re.url,ae["x-supabase-key"]=re.anonKey);const K=await fetch(`/api/engines/${ee}/run`,{method:"POST",headers:ae});if(!K.ok){const C=await K.json();throw new Error(C.error||"Run failed")}const ue=await K.json();ue.status==="completed"?E(`Engine run complete! Created: ${ue.title}`,"success"):E(`Engine run started on Desktop. Tracking as: ${ue.id}`,"info"),d(ue),t(C=>C.map(D=>D.id===ee?{...D,last_run_at:new Date().toISOString()}:D))}catch(J){console.error("Engine run error:",J),E(J.message||"Failed to run engine","error")}finally{a(J=>{const H=new Set(J);return H.delete(ee),H})}},O=async ee=>{try{y(!0);const{data:{session:J}}=await ne.auth.getSession(),H=ks(),re={"Content-Type":"application/json","x-user-id":J?.user?.id||""};J?.access_token&&(re.Authorization=`Bearer ${J.access_token}`),H&&(re["x-supabase-url"]=H.url,re["x-supabase-key"]=H.anonKey);const ae=await fetch(`/api/engines/${ee}/brief`,{headers:re});if(!ae.ok)throw new Error("Failed to fetch brief");const K=await ae.json();p(K)}catch{E("Failed to generate production brief","error")}finally{y(!1)}},q=async(ee,J)=>{const H=J==="active"?"paused":"active";t(re=>re.map(ae=>ae.id===ee?{...ae,status:H}:ae));try{const{error:re}=await ne.from("engines").update({status:H}).eq("id",ee);if(re)throw re;E(`Engine ${H==="active"?"resumed":"paused"}`,"success")}catch{t(ae=>ae.map(K=>K.id===ee?{...K,status:J}:K)),E("Failed to update status","error")}},V=()=>{_(!0)},W=ee=>{const J=e.find(H=>H.id===ee);J&&w(J)},he=ee=>{t(J=>J.find(re=>re.id===ee.id)?J.map(re=>re.id===ee.id?ee:re):[ee,...J])},se=ee=>{t(J=>J.filter(H=>H.id!==ee))},ie=()=>{w(null),_(!1)};return u.jsxs("div",{className:"h-full flex flex-col bg-gray-50/50 dark:bg-[#0A0A0A]",children:[u.jsx("div",{className:"flex-none p-6 border-b border-gray-200 dark:border-gray-800 bg-white/50 dark:bg-gray-900/50 backdrop-blur-sm z-10 sticky top-0",children:u.jsxs("div",{className:"flex justify-between items-center max-w-7xl mx-auto w-full",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-purple-500 to-blue-500",children:"Transmute Engine"}),u.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:"Active Generation Pipelines & Assets"})]}),u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsxs("button",{onClick:N,disabled:k,className:"flex items-center gap-2 px-4 py-2 bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 rounded-xl font-medium hover:bg-purple-100 dark:hover:bg-purple-900/40 transition-all border border-purple-200 dark:border-purple-800 disabled:opacity-50",children:[k?u.jsx(Et,{className:"w-4 h-4 animate-spin"}):u.jsx(Yt,{className:"w-4 h-4"}),"Generate Engines"]}),u.jsxs("button",{onClick:V,className:"flex items-center gap-2 px-4 py-2 bg-gray-900 dark:bg-white text-white dark:text-gray-900 rounded-xl font-medium hover:opacity-90 transition-opacity shadow-lg shadow-purple-500/10",children:[u.jsx(Hh,{className:"w-4 h-4"}),"New Engine"]})]})]})}),u.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:u.jsx("div",{className:"max-w-7xl mx-auto w-full",children:n?u.jsx("div",{className:"flex items-center justify-center h-64",children:u.jsx(Et,{className:"w-8 h-8 animate-spin text-purple-500"})}):e.length===0?u.jsxs("div",{className:"flex flex-col items-center justify-center h-96 text-center",children:[u.jsx("div",{className:"w-16 h-16 rounded-2xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-4",children:u.jsx(Yt,{className:"w-8 h-8 text-gray-400"})}),u.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"No Engines Configured"}),u.jsx("p",{className:"text-gray-500 max-w-sm mt-2 mb-6",children:"Create your first pipeline to automatically turn signals into newsletters, threads, or audio briefs."}),u.jsx("button",{onClick:V,className:"px-6 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",children:"Create Engine"})]}):u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:u.jsx(Pt,{children:e.map(ee=>u.jsx(A5,{engine:ee,onRun:M,onEdit:W,onToggle:q,onViewBrief:O,isLoading:o.has(ee.id)},ee.id))})})})}),u.jsx(Pt,{children:h&&u.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/60 backdrop-blur-md",children:u.jsxs(ze.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[u.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"p-2 rounded-lg bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400",children:u.jsx(H0,{className:"w-5 h-5"})}),u.jsxs("div",{children:[u.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:"Production Brief JSON"}),u.jsx("p",{className:"text-xs text-gray-500",children:"Stateless & Self-Contained Contract"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:()=>{navigator.clipboard.writeText(JSON.stringify(h,null,2)),E("JSON copied to clipboard","info")},className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",children:u.jsx(Vh,{className:"w-4 h-4"})}),u.jsx("button",{onClick:()=>p(null),className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:u.jsx(wn,{className:"w-5 h-5"})})]})]}),u.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-[#0D1117] font-mono text-sm",children:u.jsx("pre",{className:"text-blue-300",children:JSON.stringify(h,null,2)})}),u.jsx("div",{className:"p-4 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50 text-[10px] text-gray-500 text-center",children:"This JSON contains the full context (Signals + User Persona) required for the Desktop Studio."})]})})}),m&&u.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/20 backdrop-blur-sm",children:u.jsx(Et,{className:"w-10 h-10 animate-spin text-white"})}),u.jsx(T5,{asset:l,onClose:()=>d(null)}),x&&u.jsx(F0,{engine:x,onClose:ie,onSave:he,onDelete:se}),b&&u.jsx(F0,{engine:null,onClose:ie,onSave:he})]})}class R5{audioContext=null;enabled=!0;constructor(){}getAudioContext(){return this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),this.audioContext}setEnabled(t){this.enabled=t}isEnabled(){return this.enabled}playTone(t,n,r=.3){if(this.enabled)try{const o=this.getAudioContext(),a=o.createOscillator(),l=o.createGain();a.connect(l),l.connect(o.destination),a.frequency.value=t,a.type="sine",l.gain.setValueAtTime(r,o.currentTime),l.gain.exponentialRampToValueAtTime(.01,o.currentTime+n),a.start(o.currentTime),a.stop(o.currentTime+n)}catch(o){console.warn("[Sound] Failed to play tone:",o)}}playSequence(t,n=.3){if(!this.enabled)return;let r=0;t.forEach(o=>{setTimeout(()=>{this.playTone(o.freq,o.duration,n)},r),r+=o.delay})}syncStart(){this.playSequence([{freq:261.63,duration:.15,delay:0},{freq:329.63,duration:.15,delay:100},{freq:392,duration:.2,delay:100}],.2)}signalFound(){this.playSequence([{freq:392,duration:.1,delay:0},{freq:523.25,duration:.15,delay:80}],.25)}syncComplete(){this.playSequence([{freq:261.63,duration:.12,delay:0},{freq:329.63,duration:.12,delay:80},{freq:392,duration:.12,delay:80},{freq:523.25,duration:.2,delay:80}],.2)}error(){this.playSequence([{freq:329.63,duration:.15,delay:0},{freq:261.63,duration:.2,delay:100}],.3)}click(){this.playTone(440,.05,.15)}}const So=new R5;function O5(){const[e,t]=T.useState([]),[n,r]=T.useState([]),[o,a]=T.useState("discovery"),[l,d]=T.useState(!1),[h,p]=T.useState(null),[m,y]=T.useState(!0),[x,w]=T.useState(!t0),[b,_]=T.useState(!0),[k,S]=T.useState(!1),[E,N]=T.useState(!1),[R,M]=T.useState(null),[O,q]=T.useState(!1),[V,W]=T.useState(!1),[he,se]=T.useState(!1),[ie,ee]=T.useState(!0),[J,H]=T.useState(()=>localStorage.getItem("theme")||"dark"),[re,ae]=T.useState(null),K=T.useRef(null);T.useMemo(()=>{const ce=n.length;let ye=0,pe=0,me=null;for(const Ge of n){ye+=Ge.score,Ge.score>pe&&(pe=Ge.score);const Kt=new Date(Ge.date);(!me||Kt>new Date(me.date))&&(me=Ge)}const Ae=ce?Math.round(ye/ce):0,$e=me?new Date(me.date):null;return{total:ce,average:Ae,top:pe,latestTimestamp:$e,latestTitle:me?.title??me?.category??null}},[n]),T.useEffect(()=>{(async()=>{if(!t0){w(!0),y(!1);return}try{const{data:pe,error:me}=await ne.from("init_state").select("is_initialized").single();me?(console.warn("[App] Init check error (might be fresh DB):",me),me.code==="42P01"&&_(!1)):_(pe.is_initialized>0);const{data:{session:Ae}}=await ne.auth.getSession();p(Ae?.user??null)}catch(pe){console.error("[App] Status check failed:",pe)}finally{y(!1)}})();const{data:{subscription:ye}}=ne.auth.onAuthStateChange((pe,me)=>{p(me?.user??null)});return()=>ye.unsubscribe()},[]),T.useEffect(()=>{document.documentElement.setAttribute("data-theme",J),localStorage.setItem("theme",J)},[J]);const[ue,C]=T.useState({});T.useEffect(()=>{(async()=>{if(!h)return;const{data:ye}=await ne.from("alchemy_settings").select("sync_start_date, last_sync_checkpoint").eq("user_id",h.id).maybeSingle();ye&&C(ye)})()},[h,O]),T.useEffect(()=>{if(!h)return;(async()=>{const{data:pe}=await ne.from("alchemy_settings").select("sound_enabled").eq("user_id",h.id).maybeSingle();if(pe){const me=pe.sound_enabled??!0;ee(me),So.setEnabled(me)}})();const ye=ne.channel("processing_events").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events",filter:`user_id=eq.${h.id}`},pe=>{const me=pe.new;me.agent_state==="Mining"&&!V&&(W(!0),se(!0),ie&&So.syncStart()),me.agent_state==="Signal"&&ie&&So.signalFound(),me.agent_state==="Completed"&&(W(!1),ie&&(me.metadata?.errors>0?So.error():So.syncComplete()),setTimeout(()=>{se(!1)},5e3),D())}).subscribe();return()=>{ne.removeChannel(ye)}},[h,V,ie]),T.useEffect(()=>{const ce=new EventSource("/events");return ce.onmessage=ye=>{const pe=JSON.parse(ye.data);pe.type==="history"?t(me=>[...pe.data,...me].slice(0,100)):t(me=>[pe,...me].slice(0,100))},D(),()=>ce.close()},[h]),T.useEffect(()=>{K.current&&K.current.scrollIntoView({behavior:"smooth"})},[e]);const D=async()=>{try{if(h){const{data:ye,error:pe}=await ne.from("signals").select("*").order("created_at",{ascending:!1});if(!pe&&ye){r(ye.map(me=>({id:me.id,title:me.title,score:me.score,summary:me.summary,date:me.created_at,category:me.category,entities:me.entities})));return}}const ce=await Ke.get("/api/signals");r(ce.data)}catch(ce){console.error("Failed to fetch signals",ce)}},G=async()=>{d(!0);try{await Ke.post("/api/mine"),D()}catch(ce){console.error("Mining failed:",ce)}finally{d(!1)}},A=(ce,ye)=>{ce==="logs"?(ae(ye),a("logs")):a(ce)};return m?u.jsx("div",{className:"flex items-center justify-center h-screen bg-bg",children:u.jsx("div",{className:"w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"})}):x?u.jsx(hb,{onComplete:()=>w(!1)}):h?u.jsx(TP,{children:u.jsx(OP,{children:u.jsxs("div",{className:"flex h-screen w-screen overflow-hidden bg-bg text-fg",children:[u.jsxs(ze.aside,{animate:{width:k?72:240},className:"glass m-4 mr-0 flex flex-col relative",children:[u.jsxs("div",{className:`px-4 py-3 pb-4 flex items-center gap-3 ${k?"justify-center":""}`,children:[u.jsx("div",{className:"w-10 h-10 min-w-[40px] bg-gradient-to-br from-primary to-accent rounded-xl flex items-center justify-center shadow-lg glow-primary",children:u.jsx(Yt,{className:"text-white fill-current",size:24})}),!k&&u.jsx(ze.h1,{initial:{opacity:0},animate:{opacity:1},className:"text-xl font-bold tracking-tight",children:"Alchemist"})]}),u.jsxs("nav",{className:"flex-1 flex flex-col gap-1 px-3",children:[u.jsx(si,{active:o==="discovery",onClick:()=>a("discovery"),icon:u.jsx(jS,{size:20}),label:"Discovery",collapsed:k}),u.jsx(si,{active:o==="chat",onClick:()=>a("chat"),icon:u.jsx(Qd,{size:20}),label:"Chat",collapsed:k}),u.jsx(si,{active:o==="transmute",onClick:()=>a("transmute"),icon:u.jsx(Yt,{size:20}),label:"Transmute",collapsed:k}),u.jsx(si,{active:o==="engine",onClick:()=>a("engine"),icon:u.jsx(Ml,{size:20}),label:"Settings",collapsed:k}),u.jsx(si,{active:o==="logs",onClick:()=>a("logs"),icon:u.jsx(zl,{size:20}),label:"System Logs",collapsed:k}),u.jsx(si,{active:o==="account",onClick:()=>a("account"),icon:u.jsx(tc,{size:20}),label:"Account",collapsed:k})]}),u.jsx("div",{className:"px-3 pb-2",children:u.jsxs("button",{onClick:()=>H(J==="dark"?"light":"dark"),className:`w-full flex items-center ${k?"justify-center":"gap-3"} px-4 py-2.5 rounded-lg text-fg/40 hover:text-fg hover:bg-surface/50 transition-all text-xs font-medium`,title:k?J==="dark"?"Switch to Light Mode":"Switch to Dark Mode":"",children:[u.jsx("div",{className:"min-w-[20px] flex justify-center",children:J==="dark"?u.jsx(zS,{size:18}):u.jsx(AS,{size:18})}),!k&&u.jsx(ze.span,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"whitespace-nowrap",children:J==="dark"?"Light Mode":"Dark Mode"})]})}),u.jsxs("div",{className:"px-3 pb-3",children:[u.jsx("button",{onClick:()=>S(!k),className:`w-full flex items-center px-4 py-2.5 rounded-lg text-fg/40 hover:text-fg hover:bg-surface/50 transition-all text-xs font-medium ${k?"justify-center":"gap-3"}`,children:k?u.jsx(gS,{size:20}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"min-w-[20px] flex justify-center",children:u.jsx(mS,{size:20})}),u.jsx("span",{children:"Collapse"})]})}),u.jsxs("button",{onClick:()=>N(!0),className:"w-full flex items-center justify-center gap-2 px-3 py-2 mt-2 text-[10px] font-mono text-fg/30 hover:text-primary hover:bg-surface/30 rounded-lg transition-all group",title:"View Changelog",children:[!k&&u.jsxs(u.Fragment,{children:[u.jsx(eh,{size:12,className:"group-hover:text-primary transition-colors"}),u.jsxs("span",{children:["v","1.0.50"]})]}),k&&u.jsx(eh,{size:14,className:"group-hover:text-primary transition-colors"})]})]})]}),u.jsxs("main",{className:"flex-1 flex flex-col p-4 gap-4 overflow-hidden relative",children:[o==="discovery"&&u.jsxs(u.Fragment,{children:[u.jsxs("header",{className:"flex justify-between items-center px-4 py-2",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"text-2xl font-bold",children:"Discovery"}),u.jsx("p",{className:"text-sm text-fg/50",children:"Passive intelligence mining from your browser history."})]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsxs("button",{onClick:()=>q(!0),className:"px-6 py-3 glass hover:bg-surface transition-colors flex items-center gap-2 text-sm font-medium",children:[u.jsx(Ml,{size:16}),u.jsxs("div",{className:"flex flex-col items-start",children:[u.jsx("span",{children:"Sync Settings"}),u.jsx("span",{className:"text-[10px] text-fg/40 font-mono",children:ue.sync_start_date?`From: ${new Date(ue.sync_start_date).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:ue.last_sync_checkpoint?`Checkpoint: ${new Date(ue.last_sync_checkpoint).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:"All time"})]})]}),u.jsxs("button",{onClick:G,disabled:V,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-105 active:scale-95 transition-all flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100",children:[u.jsx(ec,{size:18,className:V?"animate-spin":""}),V?"Syncing...":"Sync History"]})]})]}),u.jsx(rR,{onOpenUrl:ce=>window.open(ce,"_blank","noopener,noreferrer"),onCopyText:ce=>{navigator.clipboard.writeText(ce)}})]}),o==="chat"&&u.jsx(N5,{}),o==="transmute"&&u.jsx(P5,{}),o==="engine"&&u.jsx(RP,{}),o==="account"&&u.jsx(UP,{}),o==="logs"&&u.jsx(JP,{initialState:re}),u.jsx(DP,{isExpanded:he,onToggle:()=>se(!he),onNavigate:A,liftUp:o==="chat"})]}),u.jsx(VP,{signal:R,onClose:()=>M(null)}),u.jsx(qP,{isOpen:O,onClose:()=>q(!1)}),u.jsx(C5,{isOpen:E,onClose:()=>N(!1)})]})})}):u.jsx(jP,{onAuthSuccess:()=>D(),isInitialized:b})}function si({active:e,icon:t,label:n,onClick:r,collapsed:o}){return u.jsx("button",{onClick:r,title:o?n:"",className:`w-full flex items-center ${o?"justify-center":"gap-3"} px-4 py-3 rounded-xl transition-all ${e?"bg-primary/10 text-primary shadow-sm":"text-fg/60 hover:bg-surface hover:text-fg"}`,children:o?Mo.cloneElement(t,{className:e?"text-primary":""}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"min-w-[20px] flex justify-center",children:Mo.cloneElement(t,{className:e?"text-primary":""})}),u.jsx(ze.span,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"font-semibold text-sm whitespace-nowrap",children:n})]})})}function I5(){Ke.interceptors.request.use(async e=>{try{const{data:{session:t}}=await ne.auth.getSession();t?.access_token&&(e.headers.Authorization=`Bearer ${t.access_token}`);const n=ks();n&&(e.headers["x-supabase-url"]=n.url,e.headers["x-supabase-key"]=n.anonKey)}catch(t){console.error("[Axios] Error injecting headers:",t)}return e})}I5();rS.createRoot(document.getElementById("root")).render(u.jsx(Mo.StrictMode,{children:u.jsx(O5,{})}));
|
|
125
|
+
Failed to load changelog.`)}finally{a(!1)}};return u.jsx(Pt,{children:e&&u.jsxs(u.Fragment,{children:[u.jsx(ze.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:t,className:"fixed inset-0 bg-black/60 backdrop-blur-sm z-50"}),u.jsx(ze.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{type:"spring",damping:25,stiffness:300},className:"fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none",children:u.jsxs("div",{className:"glass w-full max-w-3xl max-h-[80vh] overflow-hidden pointer-events-auto shadow-2xl",children:[u.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx($0,{size:24,className:"text-primary"}),u.jsx("h2",{className:"text-xl font-bold",children:"Release Notes"})]}),u.jsx("button",{onClick:t,className:"p-2 hover:bg-surface rounded-lg transition-colors",children:u.jsx(wn,{size:20,className:"text-fg/60"})})]}),u.jsx("div",{className:"p-6 overflow-y-auto custom-scrollbar max-h-[calc(80vh-88px)]",children:o?u.jsx("div",{className:"flex items-center justify-center py-12",children:u.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-primary border-t-transparent"})}):u.jsx(ep,{components:{h1:({children:d})=>u.jsx("h1",{className:"text-2xl font-bold text-fg mb-6 mt-0",children:d}),h2:({children:d})=>u.jsx("h2",{className:"text-xl font-bold text-fg mt-8 mb-3 pb-2 border-b border-border first:mt-0",children:d}),h3:({children:d})=>u.jsx("h3",{className:"text-lg font-bold text-primary mt-6 mb-2",children:d}),p:({children:d})=>u.jsx("p",{className:"text-sm text-fg/70 mb-3 leading-relaxed",children:d}),ul:({children:d})=>u.jsx("ul",{className:"list-none space-y-1 mb-4 ml-0",children:d}),li:({children:d})=>u.jsx("li",{className:"text-sm text-fg/80 ml-4 mb-1 before:content-['•'] before:mr-2 before:text-primary",children:d}),a:({href:d,children:h})=>u.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:text-primary/80 underline transition-colors",children:h}),code:({children:d})=>u.jsx("code",{className:"bg-surface/50 text-accent px-1.5 py-0.5 rounded text-xs font-mono border border-border",children:d}),strong:({children:d})=>u.jsx("strong",{className:"font-bold text-fg",children:d})},children:n})})]})})]})})}function T5({asset:e,onClose:t}){const n=()=>{e.content&&navigator.clipboard.writeText(e.content)},r=()=>{if(!e.content)return;const o=new Blob([e.content],{type:"text/markdown"}),a=URL.createObjectURL(o),l=document.createElement("a");l.href=a,l.download=`${e.title.replace(/[^a-z0-9]/gi,"_").toLowerCase()}.md`,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(a)};return u.jsx(Pt,{children:e&&u.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:u.jsxs(ze.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[u.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"p-2 rounded-lg bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400",children:e.type==="audio"?u.jsx(Zd,{className:"w-5 h-5"}):u.jsx(wi,{className:"w-5 h-5"})}),u.jsxs("div",{children:[u.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e.title}),u.jsxs("p",{className:"text-xs text-gray-500",children:["Generated ",new Date(e.created_at).toLocaleString()," • ",e.metadata?.source_signal_count||0," sources"]})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:n,className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",title:"Copy Content",children:u.jsx(Vh,{className:"w-4 h-4"})}),u.jsx("button",{onClick:r,className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",title:"Download File",children:u.jsx(Xd,{className:"w-4 h-4"})}),u.jsx("div",{className:"w-px h-6 bg-gray-200 dark:bg-gray-700 mx-1"}),u.jsx("button",{onClick:t,className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:u.jsx(wn,{className:"w-5 h-5"})})]})]}),u.jsx("div",{className:"flex-1 overflow-y-auto p-6 bg-white dark:bg-gray-950",children:e.status&&e.status!=="completed"?u.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-4",children:[u.jsx(Et,{className:"w-12 h-12 animate-spin text-purple-500"}),u.jsxs("div",{className:"text-center",children:[u.jsx("h4",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:e.status==="processing"?"Generating Asset...":"Queued for Desktop..."}),u.jsx("p",{className:"text-sm text-gray-500 max-w-xs mt-1",children:"The RealTimeX Desktop app is processing this request. This modal will update automatically once finished."})]})]}):e.type==="markdown"?u.jsx("div",{className:"prose dark:prose-invert max-w-none",children:u.jsx(ep,{children:e.content||""})}):e.type==="audio"?u.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-4",children:[u.jsx("div",{className:"w-16 h-16 rounded-full bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center animate-pulse",children:u.jsx(Zd,{className:"w-8 h-8 text-purple-600 dark:text-purple-400"})}),u.jsx("p",{className:"text-gray-500",children:"Audio playback not yet implemented (Simulated)"}),u.jsxs("audio",{controls:!0,className:"w-full max-w-md mt-4",children:[u.jsx("source",{src:e.content||"",type:"audio/mpeg"}),"Your browser does not support the audio element."]})]}):u.jsx("div",{className:"text-gray-500 text-center py-10",children:"Unsupported asset type"})})]})})})}function F0({engine:e,onClose:t,onSave:n,onDelete:r}){const{showToast:o}=yc(),[a,l]=T.useState({title:"",type:"newsletter",status:"active",config:{schedule:"",min_score:70,categories:[],custom_prompt:"",max_signals:10,execution_mode:"local"}}),[d,h]=T.useState(!1);T.useEffect(()=>{e&&l({title:e.title,type:e.type,status:e.status,config:{schedule:e.config.schedule||"",min_score:e.config.filters?.min_score||70,categories:Array.isArray(e.config.category)?e.config.category:e.config.category?[e.config.category]:[],custom_prompt:e.config.custom_prompt||"",max_signals:e.config.max_signals||10,execution_mode:e.config.execution_mode||"local"}})},[e]);const p=async()=>{try{const x={title:a.title,type:a.type,status:a.status,config:{schedule:a.config.schedule,filters:{min_score:a.config.min_score,category:a.config.category},custom_prompt:a.config.custom_prompt,max_signals:a.config.max_signals,execution_mode:a.config.execution_mode}};if(e){const{data:w,error:b}=await ne.from("engines").update(x).eq("id",e.id).select().single();if(b)throw b;n(w),o("Engine updated successfully","success")}else{const{data:{user:w}}=await ne.auth.getUser();if(!w)throw new Error("Not authenticated");const{data:b,error:_}=await ne.from("engines").insert({...x,user_id:w.id}).select().single();if(_)throw _;n(b),o("Engine created successfully","success")}t()}catch(x){console.error("Save error:",x),o(x.message||"Failed to save engine","error")}},m=async()=>{if(!(!e||!r))try{const{error:x}=await ne.from("engines").delete().eq("id",e.id);if(x)throw x;r(e.id),o("Engine deleted","success"),t()}catch(x){o(x.message||"Failed to delete engine","error")}},y=()=>{h(!1),t()};return!e&&!t?null:u.jsx(Pt,{children:u.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:u.jsxs(ze.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-2xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[u.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800",children:[u.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:e?"Edit Engine":"Create Engine"}),u.jsx("button",{onClick:y,className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:u.jsx(wn,{className:"w-5 h-5"})})]}),u.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Engine Name"}),u.jsx("input",{type:"text",value:a.title,onChange:x=>l({...a,title:x.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:"e.g., Daily Tech Brief"})]}),u.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Type"}),u.jsxs("select",{value:a.type,onChange:x=>l({...a,type:x.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[u.jsx("option",{value:"newsletter",children:"Newsletter"}),u.jsx("option",{value:"thread",children:"Thread"}),u.jsx("option",{value:"audio",children:"Audio Brief"}),u.jsx("option",{value:"report",children:"Report"})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Status"}),u.jsxs("select",{value:a.status,onChange:x=>l({...a,status:x.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[u.jsx("option",{value:"active",children:"Active"}),u.jsx("option",{value:"paused",children:"Paused"}),u.jsx("option",{value:"draft",children:"Draft"})]})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Execution Environment"}),u.jsxs("select",{value:a.config.execution_mode,onChange:x=>l({...a,config:{...a.config,execution_mode:x.target.value}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[u.jsx("option",{value:"local",children:"Local (Alchemy LLM)"}),u.jsx("option",{value:"desktop",children:"RealTimeX Desktop (Agent Swarm)"})]}),u.jsx("p",{className:"text-[10px] text-gray-500 mt-1",children:a.config.execution_mode==="desktop"?"Delegates heavy tasks like Audio/Video to the desktop app.":"Runs simple Markdown tasks directly in Alchemy."})]})]}),u.jsxs("div",{className:"space-y-4",children:[u.jsx("h4",{className:"font-medium text-gray-900 dark:text-gray-100",children:"Signal Filters"}),u.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Min Score"}),u.jsx("input",{type:"number",min:"0",max:"100",value:a.config.min_score,onChange:x=>l({...a,config:{...a.config,min_score:parseInt(x.target.value)||0}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Max Signals"}),u.jsx("input",{type:"number",min:"1",max:"50",value:a.config.max_signals,onChange:x=>l({...a,config:{...a.config,max_signals:parseInt(x.target.value)||10}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Category Filter (multi-select)"}),u.jsxs("select",{multiple:!0,value:a.config.categories,onChange:x=>{const w=Array.from(x.target.selectedOptions,b=>b.value);l({...a,config:{...a.config,categories:w}})},className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 min-h-[100px]",children:[u.jsx("option",{value:"AI & ML",children:"AI & ML"}),u.jsx("option",{value:"Technology",children:"Technology"}),u.jsx("option",{value:"Business",children:"Business"}),u.jsx("option",{value:"Finance",children:"Finance"}),u.jsx("option",{value:"Science",children:"Science"}),u.jsx("option",{value:"Politics",children:"Politics"})]}),u.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Hold Cmd/Ctrl to select multiple categories"})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Schedule (optional)"}),u.jsx("input",{type:"text",value:a.config.schedule,onChange:x=>l({...a,config:{...a.config,schedule:x.target.value}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",placeholder:"e.g., Daily @ 9am, Manual"}),u.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Note: Scheduling is not yet automated"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Custom Prompt Override (optional)"}),u.jsx("textarea",{value:a.config.custom_prompt,onChange:x=>l({...a,config:{...a.config,custom_prompt:x.target.value}}),rows:4,className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 resize-none",placeholder:"Override the default prompt for this engine type..."})]})]}),u.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50",children:[e&&r?d?u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("span",{className:"text-sm text-red-600 font-medium",children:"Really delete?"}),u.jsx("button",{onClick:m,className:"px-3 py-1.5 bg-red-600 text-white text-xs rounded-lg hover:bg-red-700 transition-colors",children:"Confirm"}),u.jsx("button",{onClick:()=>h(!1),className:"px-3 py-1.5 text-gray-500 hover:text-gray-700 text-xs rounded-lg",children:"Cancel"})]}):u.jsxs("button",{onClick:()=>h(!0),className:"flex items-center gap-2 px-4 py-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:[u.jsx(Wh,{className:"w-4 h-4"}),"Delete"]}):u.jsx("div",{}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx("button",{onClick:y,className:"px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:"Cancel"}),u.jsxs("button",{onClick:p,className:"flex items-center gap-2 px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors",children:[u.jsx(fr,{className:"w-4 h-4"}),"Save"]})]})]})]})})})}const A5=({engine:e,onRun:t,onEdit:n,onToggle:r,onViewBrief:o,isLoading:a})=>{const l=!!e.config.tag,d={newsletter:l?u.jsx(qh,{className:"w-5 h-5 text-blue-500"}):u.jsx(wi,{className:"w-5 h-5 text-emerald-500"}),thread:u.jsx(Yt,{className:"w-5 h-5 text-blue-500"}),audio:u.jsx(Zd,{className:"w-5 h-5 text-purple-500"}),report:u.jsx(Ml,{className:"w-5 h-5 text-orange-500"})};return u.jsxs(ze.div,{layout:!0,initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:`p-5 rounded-2xl border ${e.status==="active"?"bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700 shadow-sm":"bg-gray-50 dark:bg-gray-900 border-dashed border-gray-300 dark:border-gray-700 opacity-75"} transition-all hover:shadow-md group`,children:[u.jsxs("div",{className:"flex justify-between items-start mb-4",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"p-2 rounded-xl bg-gray-100 dark:bg-gray-800",children:d[e.type]||u.jsx(wi,{className:"w-5 h-5"})}),u.jsxs("div",{children:[u.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e.title}),u.jsxs("p",{className:"text-xs text-gray-500 capitalize",children:[l?"Topic":e.type," Pipeline"]})]})]}),u.jsxs("div",{className:"flex gap-1",children:[u.jsx("button",{onClick:()=>r(e.id,e.status),className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:e.status==="active"?u.jsx(PS,{className:"w-4 h-4"}):u.jsx(Xg,{className:"w-4 h-4"})}),u.jsx("button",{onClick:()=>o(e.id),title:"View Production Brief JSON",className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:u.jsx(H0,{className:"w-4 h-4"})}),u.jsx("button",{onClick:()=>n(e.id),className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:u.jsx(Ml,{className:"w-4 h-4"})})]})]}),u.jsxs("div",{className:"space-y-2 mb-4",children:[u.jsxs("div",{className:"text-xs text-gray-500 flex justify-between",children:[u.jsx("span",{children:"Last Run"}),u.jsx("span",{children:e.last_run_at?new Date(e.last_run_at).toLocaleDateString():"Never"})]}),u.jsxs("div",{className:"text-xs text-gray-500 flex justify-between",children:[u.jsx("span",{children:"Schedule"}),u.jsx("span",{children:e.config.schedule||"Manual"})]})]}),u.jsxs("button",{onClick:()=>t(e.id),disabled:a||e.status!=="active",className:"w-full flex items-center justify-center gap-2 py-2 rounded-xl bg-gray-900 dark:bg-white text-white dark:text-gray-900 font-medium hover:opacity-90 disabled:opacity-50 transition-all text-sm",children:[a?u.jsx(Et,{className:"w-4 h-4 animate-spin"}):u.jsx(Xg,{className:"w-4 h-4"}),a?"Running...":"Run Engine"]})]})};function P5(){const[e,t]=T.useState([]),[n,r]=T.useState(!0),[o,a]=T.useState(new Set),[l,d]=T.useState(null),[h,p]=T.useState(null),[m,y]=T.useState(!1),[x,w]=T.useState(null),[b,_]=T.useState(!1),[k,S]=T.useState(!1),{showToast:E}=yc();T.useEffect(()=>{(async()=>R())();const J=ne.channel("asset-updates").on("postgres_changes",{event:"UPDATE",schema:"public",table:"assets"},H=>{const re=H.new;d(ae=>ae?.id===re.id?re:ae),re.status==="completed"&&H.old.status!=="completed"&&E(`Asset "${re.title}" is ready!`,"success")}).subscribe();return()=>{ne.removeChannel(J)}},[]);const N=async()=>{if(!k)try{S(!0),E("Scanning for new categories and topics...","info");const{data:{session:ee}}=await ne.auth.getSession(),J=ks(),H={"Content-Type":"application/json","x-user-id":ee?.user?.id||""};if(ee?.access_token&&(H.Authorization=`Bearer ${ee.access_token}`),J&&(H["x-supabase-url"]=J.url,H["x-supabase-key"]=J.anonKey),!(await fetch("/api/engines/ensure-defaults",{method:"POST",headers:H})).ok)throw new Error("Failed to generate engines");E("Engine discovery complete!","success"),await R()}catch(ee){console.error("Failed to generate engines:",ee),E("Discovery failed. Check settings.","error")}finally{S(!1)}},R=async()=>{try{r(!0);const{data:{user:ee}}=await ne.auth.getUser();if(!ee)return;const{data:J,error:H}=await ne.from("engines").select("*").eq("user_id",ee.id).order("created_at",{ascending:!1});if(H)throw H;t(J)}catch(ee){console.error("Error fetching engines:",ee),E("Failed to load engines","error")}finally{r(!1)}},M=async ee=>{if(!o.has(ee))try{a(C=>new Set(C).add(ee)),E("Starting engine run...","info");const{data:{session:J}}=await ne.auth.getSession(),H=J?.access_token,re=ks(),ae={"Content-Type":"application/json","x-user-id":J?.user?.id||""};H&&(ae.Authorization=`Bearer ${H}`),re&&(ae["x-supabase-url"]=re.url,ae["x-supabase-key"]=re.anonKey);const K=await fetch(`/api/engines/${ee}/run`,{method:"POST",headers:ae});if(!K.ok){const C=await K.json();throw new Error(C.error||"Run failed")}const ue=await K.json();ue.status==="completed"?E(`Engine run complete! Created: ${ue.title}`,"success"):E(`Engine run started on Desktop. Tracking as: ${ue.id}`,"info"),d(ue),t(C=>C.map(D=>D.id===ee?{...D,last_run_at:new Date().toISOString()}:D))}catch(J){console.error("Engine run error:",J),E(J.message||"Failed to run engine","error")}finally{a(J=>{const H=new Set(J);return H.delete(ee),H})}},O=async ee=>{try{y(!0);const{data:{session:J}}=await ne.auth.getSession(),H=ks(),re={"Content-Type":"application/json","x-user-id":J?.user?.id||""};J?.access_token&&(re.Authorization=`Bearer ${J.access_token}`),H&&(re["x-supabase-url"]=H.url,re["x-supabase-key"]=H.anonKey);const ae=await fetch(`/api/engines/${ee}/brief`,{headers:re});if(!ae.ok)throw new Error("Failed to fetch brief");const K=await ae.json();p(K)}catch{E("Failed to generate production brief","error")}finally{y(!1)}},q=async(ee,J)=>{const H=J==="active"?"paused":"active";t(re=>re.map(ae=>ae.id===ee?{...ae,status:H}:ae));try{const{error:re}=await ne.from("engines").update({status:H}).eq("id",ee);if(re)throw re;E(`Engine ${H==="active"?"resumed":"paused"}`,"success")}catch{t(ae=>ae.map(K=>K.id===ee?{...K,status:J}:K)),E("Failed to update status","error")}},V=()=>{_(!0)},W=ee=>{const J=e.find(H=>H.id===ee);J&&w(J)},he=ee=>{t(J=>J.find(re=>re.id===ee.id)?J.map(re=>re.id===ee.id?ee:re):[ee,...J])},se=ee=>{t(J=>J.filter(H=>H.id!==ee))},ie=()=>{w(null),_(!1)};return u.jsxs("div",{className:"h-full flex flex-col bg-gray-50/50 dark:bg-[#0A0A0A]",children:[u.jsx("div",{className:"flex-none p-6 border-b border-gray-200 dark:border-gray-800 bg-white/50 dark:bg-gray-900/50 backdrop-blur-sm z-10 sticky top-0",children:u.jsxs("div",{className:"flex justify-between items-center max-w-7xl mx-auto w-full",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-purple-500 to-blue-500",children:"Transmute Engine"}),u.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:"Active Generation Pipelines & Assets"})]}),u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsxs("button",{onClick:N,disabled:k,className:"flex items-center gap-2 px-4 py-2 bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 rounded-xl font-medium hover:bg-purple-100 dark:hover:bg-purple-900/40 transition-all border border-purple-200 dark:border-purple-800 disabled:opacity-50",children:[k?u.jsx(Et,{className:"w-4 h-4 animate-spin"}):u.jsx(Yt,{className:"w-4 h-4"}),"Generate Engines"]}),u.jsxs("button",{onClick:V,className:"flex items-center gap-2 px-4 py-2 bg-gray-900 dark:bg-white text-white dark:text-gray-900 rounded-xl font-medium hover:opacity-90 transition-opacity shadow-lg shadow-purple-500/10",children:[u.jsx(Hh,{className:"w-4 h-4"}),"New Engine"]})]})]})}),u.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:u.jsx("div",{className:"max-w-7xl mx-auto w-full",children:n?u.jsx("div",{className:"flex items-center justify-center h-64",children:u.jsx(Et,{className:"w-8 h-8 animate-spin text-purple-500"})}):e.length===0?u.jsxs("div",{className:"flex flex-col items-center justify-center h-96 text-center",children:[u.jsx("div",{className:"w-16 h-16 rounded-2xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-4",children:u.jsx(Yt,{className:"w-8 h-8 text-gray-400"})}),u.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"No Engines Configured"}),u.jsx("p",{className:"text-gray-500 max-w-sm mt-2 mb-6",children:"Create your first pipeline to automatically turn signals into newsletters, threads, or audio briefs."}),u.jsx("button",{onClick:V,className:"px-6 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",children:"Create Engine"})]}):u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:u.jsx(Pt,{children:e.map(ee=>u.jsx(A5,{engine:ee,onRun:M,onEdit:W,onToggle:q,onViewBrief:O,isLoading:o.has(ee.id)},ee.id))})})})}),u.jsx(Pt,{children:h&&u.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/60 backdrop-blur-md",children:u.jsxs(ze.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[u.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"p-2 rounded-lg bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400",children:u.jsx(H0,{className:"w-5 h-5"})}),u.jsxs("div",{children:[u.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:"Production Brief JSON"}),u.jsx("p",{className:"text-xs text-gray-500",children:"Stateless & Self-Contained Contract"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:()=>{navigator.clipboard.writeText(JSON.stringify(h,null,2)),E("JSON copied to clipboard","info")},className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",children:u.jsx(Vh,{className:"w-4 h-4"})}),u.jsx("button",{onClick:()=>p(null),className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:u.jsx(wn,{className:"w-5 h-5"})})]})]}),u.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-[#0D1117] font-mono text-sm",children:u.jsx("pre",{className:"text-blue-300",children:JSON.stringify(h,null,2)})}),u.jsx("div",{className:"p-4 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50 text-[10px] text-gray-500 text-center",children:"This JSON contains the full context (Signals + User Persona) required for the Desktop Studio."})]})})}),m&&u.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/20 backdrop-blur-sm",children:u.jsx(Et,{className:"w-10 h-10 animate-spin text-white"})}),u.jsx(T5,{asset:l,onClose:()=>d(null)}),x&&u.jsx(F0,{engine:x,onClose:ie,onSave:he,onDelete:se}),b&&u.jsx(F0,{engine:null,onClose:ie,onSave:he})]})}class R5{audioContext=null;enabled=!0;constructor(){}getAudioContext(){return this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),this.audioContext}setEnabled(t){this.enabled=t}isEnabled(){return this.enabled}playTone(t,n,r=.3){if(this.enabled)try{const o=this.getAudioContext(),a=o.createOscillator(),l=o.createGain();a.connect(l),l.connect(o.destination),a.frequency.value=t,a.type="sine",l.gain.setValueAtTime(r,o.currentTime),l.gain.exponentialRampToValueAtTime(.01,o.currentTime+n),a.start(o.currentTime),a.stop(o.currentTime+n)}catch(o){console.warn("[Sound] Failed to play tone:",o)}}playSequence(t,n=.3){if(!this.enabled)return;let r=0;t.forEach(o=>{setTimeout(()=>{this.playTone(o.freq,o.duration,n)},r),r+=o.delay})}syncStart(){this.playSequence([{freq:261.63,duration:.15,delay:0},{freq:329.63,duration:.15,delay:100},{freq:392,duration:.2,delay:100}],.2)}signalFound(){this.playSequence([{freq:392,duration:.1,delay:0},{freq:523.25,duration:.15,delay:80}],.25)}syncComplete(){this.playSequence([{freq:261.63,duration:.12,delay:0},{freq:329.63,duration:.12,delay:80},{freq:392,duration:.12,delay:80},{freq:523.25,duration:.2,delay:80}],.2)}error(){this.playSequence([{freq:329.63,duration:.15,delay:0},{freq:261.63,duration:.2,delay:100}],.3)}click(){this.playTone(440,.05,.15)}}const So=new R5;function O5(){const[e,t]=T.useState([]),[n,r]=T.useState([]),[o,a]=T.useState("discovery"),[l,d]=T.useState(!1),[h,p]=T.useState(null),[m,y]=T.useState(!0),[x,w]=T.useState(!t0),[b,_]=T.useState(!0),[k,S]=T.useState(!1),[E,N]=T.useState(!1),[R,M]=T.useState(null),[O,q]=T.useState(!1),[V,W]=T.useState(!1),[he,se]=T.useState(!1),[ie,ee]=T.useState(!0),[J,H]=T.useState(()=>localStorage.getItem("theme")||"dark"),[re,ae]=T.useState(null),K=T.useRef(null);T.useMemo(()=>{const ce=n.length;let ye=0,pe=0,me=null;for(const Ge of n){ye+=Ge.score,Ge.score>pe&&(pe=Ge.score);const Kt=new Date(Ge.date);(!me||Kt>new Date(me.date))&&(me=Ge)}const Ae=ce?Math.round(ye/ce):0,$e=me?new Date(me.date):null;return{total:ce,average:Ae,top:pe,latestTimestamp:$e,latestTitle:me?.title??me?.category??null}},[n]),T.useEffect(()=>{(async()=>{if(!t0){w(!0),y(!1);return}try{const{data:pe,error:me}=await ne.from("init_state").select("is_initialized").single();me?(console.warn("[App] Init check error (might be fresh DB):",me),me.code==="42P01"&&_(!1)):_(pe.is_initialized>0);const{data:{session:Ae}}=await ne.auth.getSession();p(Ae?.user??null)}catch(pe){console.error("[App] Status check failed:",pe)}finally{y(!1)}})();const{data:{subscription:ye}}=ne.auth.onAuthStateChange((pe,me)=>{p(me?.user??null)});return()=>ye.unsubscribe()},[]),T.useEffect(()=>{document.documentElement.setAttribute("data-theme",J),localStorage.setItem("theme",J)},[J]);const[ue,C]=T.useState({});T.useEffect(()=>{(async()=>{if(!h)return;const{data:ye}=await ne.from("alchemy_settings").select("sync_start_date, last_sync_checkpoint").eq("user_id",h.id).maybeSingle();ye&&C(ye)})()},[h,O]),T.useEffect(()=>{if(!h)return;(async()=>{const{data:pe}=await ne.from("alchemy_settings").select("sound_enabled").eq("user_id",h.id).maybeSingle();if(pe){const me=pe.sound_enabled??!0;ee(me),So.setEnabled(me)}})();const ye=ne.channel("processing_events").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events",filter:`user_id=eq.${h.id}`},pe=>{const me=pe.new;me.agent_state==="Mining"&&!V&&(W(!0),se(!0),ie&&So.syncStart()),me.agent_state==="Signal"&&ie&&So.signalFound(),me.agent_state==="Completed"&&(W(!1),ie&&(me.metadata?.errors>0?So.error():So.syncComplete()),setTimeout(()=>{se(!1)},5e3),D())}).subscribe();return()=>{ne.removeChannel(ye)}},[h,V,ie]),T.useEffect(()=>{const ce=new EventSource("/events");return ce.onmessage=ye=>{const pe=JSON.parse(ye.data);pe.type==="history"?t(me=>[...pe.data,...me].slice(0,100)):t(me=>[pe,...me].slice(0,100))},D(),()=>ce.close()},[h]),T.useEffect(()=>{K.current&&K.current.scrollIntoView({behavior:"smooth"})},[e]);const D=async()=>{try{if(h){const{data:ye,error:pe}=await ne.from("signals").select("*").order("created_at",{ascending:!1});if(!pe&&ye){r(ye.map(me=>({id:me.id,title:me.title,score:me.score,summary:me.summary,date:me.created_at,category:me.category,entities:me.entities})));return}}const ce=await Ke.get("/api/signals");r(ce.data)}catch(ce){console.error("Failed to fetch signals",ce)}},G=async()=>{d(!0);try{await Ke.post("/api/mine"),D()}catch(ce){console.error("Mining failed:",ce)}finally{d(!1)}},A=(ce,ye)=>{ce==="logs"?(ae(ye),a("logs")):a(ce)};return m?u.jsx("div",{className:"flex items-center justify-center h-screen bg-bg",children:u.jsx("div",{className:"w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"})}):x?u.jsx(hb,{onComplete:()=>w(!1)}):h?u.jsx(TP,{children:u.jsx(OP,{children:u.jsxs("div",{className:"flex h-screen w-screen overflow-hidden bg-bg text-fg",children:[u.jsxs(ze.aside,{animate:{width:k?72:240},className:"glass m-4 mr-0 flex flex-col relative",children:[u.jsxs("div",{className:`px-4 py-3 pb-4 flex items-center gap-3 ${k?"justify-center":""}`,children:[u.jsx("div",{className:"w-10 h-10 min-w-[40px] bg-gradient-to-br from-primary to-accent rounded-xl flex items-center justify-center shadow-lg glow-primary",children:u.jsx(Yt,{className:"text-white fill-current",size:24})}),!k&&u.jsx(ze.h1,{initial:{opacity:0},animate:{opacity:1},className:"text-xl font-bold tracking-tight",children:"Alchemist"})]}),u.jsxs("nav",{className:"flex-1 flex flex-col gap-1 px-3",children:[u.jsx(si,{active:o==="discovery",onClick:()=>a("discovery"),icon:u.jsx(jS,{size:20}),label:"Discovery",collapsed:k}),u.jsx(si,{active:o==="chat",onClick:()=>a("chat"),icon:u.jsx(Qd,{size:20}),label:"Chat",collapsed:k}),u.jsx(si,{active:o==="transmute",onClick:()=>a("transmute"),icon:u.jsx(Yt,{size:20}),label:"Transmute",collapsed:k}),u.jsx(si,{active:o==="engine",onClick:()=>a("engine"),icon:u.jsx(Ml,{size:20}),label:"Settings",collapsed:k}),u.jsx(si,{active:o==="logs",onClick:()=>a("logs"),icon:u.jsx(zl,{size:20}),label:"System Logs",collapsed:k}),u.jsx(si,{active:o==="account",onClick:()=>a("account"),icon:u.jsx(tc,{size:20}),label:"Account",collapsed:k})]}),u.jsx("div",{className:"px-3 pb-2",children:u.jsxs("button",{onClick:()=>H(J==="dark"?"light":"dark"),className:`w-full flex items-center ${k?"justify-center":"gap-3"} px-4 py-2.5 rounded-lg text-fg/40 hover:text-fg hover:bg-surface/50 transition-all text-xs font-medium`,title:k?J==="dark"?"Switch to Light Mode":"Switch to Dark Mode":"",children:[u.jsx("div",{className:"min-w-[20px] flex justify-center",children:J==="dark"?u.jsx(zS,{size:18}):u.jsx(AS,{size:18})}),!k&&u.jsx(ze.span,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"whitespace-nowrap",children:J==="dark"?"Light Mode":"Dark Mode"})]})}),u.jsxs("div",{className:"px-3 pb-3",children:[u.jsx("button",{onClick:()=>S(!k),className:`w-full flex items-center px-4 py-2.5 rounded-lg text-fg/40 hover:text-fg hover:bg-surface/50 transition-all text-xs font-medium ${k?"justify-center":"gap-3"}`,children:k?u.jsx(gS,{size:20}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"min-w-[20px] flex justify-center",children:u.jsx(mS,{size:20})}),u.jsx("span",{children:"Collapse"})]})}),u.jsxs("button",{onClick:()=>N(!0),className:"w-full flex items-center justify-center gap-2 px-3 py-2 mt-2 text-[10px] font-mono text-fg/30 hover:text-primary hover:bg-surface/30 rounded-lg transition-all group",title:"View Changelog",children:[!k&&u.jsxs(u.Fragment,{children:[u.jsx(eh,{size:12,className:"group-hover:text-primary transition-colors"}),u.jsxs("span",{children:["v","1.0.51"]})]}),k&&u.jsx(eh,{size:14,className:"group-hover:text-primary transition-colors"})]})]})]}),u.jsxs("main",{className:"flex-1 flex flex-col p-4 gap-4 overflow-hidden relative",children:[o==="discovery"&&u.jsxs(u.Fragment,{children:[u.jsxs("header",{className:"flex justify-between items-center px-4 py-2",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"text-2xl font-bold",children:"Discovery"}),u.jsx("p",{className:"text-sm text-fg/50",children:"Passive intelligence mining from your browser history."})]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsxs("button",{onClick:()=>q(!0),className:"px-6 py-3 glass hover:bg-surface transition-colors flex items-center gap-2 text-sm font-medium",children:[u.jsx(Ml,{size:16}),u.jsxs("div",{className:"flex flex-col items-start",children:[u.jsx("span",{children:"Sync Settings"}),u.jsx("span",{className:"text-[10px] text-fg/40 font-mono",children:ue.sync_start_date?`From: ${new Date(ue.sync_start_date).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:ue.last_sync_checkpoint?`Checkpoint: ${new Date(ue.last_sync_checkpoint).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:"All time"})]})]}),u.jsxs("button",{onClick:G,disabled:V,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-105 active:scale-95 transition-all flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100",children:[u.jsx(ec,{size:18,className:V?"animate-spin":""}),V?"Syncing...":"Sync History"]})]})]}),u.jsx(rR,{onOpenUrl:ce=>window.open(ce,"_blank","noopener,noreferrer"),onCopyText:ce=>{navigator.clipboard.writeText(ce)}})]}),o==="chat"&&u.jsx(N5,{}),o==="transmute"&&u.jsx(P5,{}),o==="engine"&&u.jsx(RP,{}),o==="account"&&u.jsx(UP,{}),o==="logs"&&u.jsx(JP,{initialState:re}),u.jsx(DP,{isExpanded:he,onToggle:()=>se(!he),onNavigate:A,liftUp:o==="chat"})]}),u.jsx(VP,{signal:R,onClose:()=>M(null)}),u.jsx(qP,{isOpen:O,onClose:()=>q(!1)}),u.jsx(C5,{isOpen:E,onClose:()=>N(!1)})]})})}):u.jsx(jP,{onAuthSuccess:()=>D(),isInitialized:b})}function si({active:e,icon:t,label:n,onClick:r,collapsed:o}){return u.jsx("button",{onClick:r,title:o?n:"",className:`w-full flex items-center ${o?"justify-center":"gap-3"} px-4 py-3 rounded-xl transition-all ${e?"bg-primary/10 text-primary shadow-sm":"text-fg/60 hover:bg-surface hover:text-fg"}`,children:o?Mo.cloneElement(t,{className:e?"text-primary":""}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"min-w-[20px] flex justify-center",children:Mo.cloneElement(t,{className:e?"text-primary":""})}),u.jsx(ze.span,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"font-semibold text-sm whitespace-nowrap",children:n})]})})}function I5(){Ke.interceptors.request.use(async e=>{try{const{data:{session:t}}=await ne.auth.getSession();t?.access_token&&(e.headers.Authorization=`Bearer ${t.access_token}`);const n=ks();n&&(e.headers["x-supabase-url"]=n.url,e.headers["x-supabase-key"]=n.anonKey)}catch(t){console.error("[Axios] Error injecting headers:",t)}return e})}I5();rS.createRoot(document.getElementById("root")).render(u.jsx(Mo.StrictMode,{children:u.jsx(O5,{})}));
|
package/dist/index.html
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
10
10
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
11
11
|
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&family=Outfit:wght@300;400;600;800&display=swap" rel="stylesheet">
|
|
12
|
-
<script type="module" crossorigin src="/assets/index-
|
|
12
|
+
<script type="module" crossorigin src="/assets/index-Cb2XPDey.js"></script>
|
|
13
13
|
<link rel="stylesheet" crossorigin href="/assets/index-BcolxI8u.css">
|
|
14
14
|
</head>
|
|
15
15
|
<body>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@realtimex/realtimex-alchemy",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.51",
|
|
4
4
|
"description": "Passive Intelligence engine for RealTimeX Alchemy. Transmute your reading time into high-density insights.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/api/index.js",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"@anthropic-ai/sdk": "^0.24.1",
|
|
45
45
|
"@mozilla/readability": "^0.6.0",
|
|
46
|
-
"@realtimex/sdk": "^1.1.
|
|
46
|
+
"@realtimex/sdk": "^1.1.4",
|
|
47
47
|
"@supabase/supabase-js": "^2.39.0",
|
|
48
48
|
"@types/jsdom": "^27.0.0",
|
|
49
49
|
"@types/mozilla-readability": "^0.2.1",
|
|
@@ -82,4 +82,4 @@
|
|
|
82
82
|
"typescript": "^5.3.3",
|
|
83
83
|
"vite": "^7.3.1"
|
|
84
84
|
}
|
|
85
|
-
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
-- Enable pgvector extension
|
|
2
|
+
CREATE EXTENSION IF NOT EXISTS vector;
|
|
3
|
+
|
|
4
|
+
-- Vectors table (separate from signals for flexibility)
|
|
5
|
+
CREATE TABLE alchemy_vectors (
|
|
6
|
+
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
7
|
+
signal_id UUID NOT NULL REFERENCES signals(id) ON DELETE CASCADE,
|
|
8
|
+
user_id UUID NOT NULL,
|
|
9
|
+
embedding vector(1536) NOT NULL, -- OpenAI text-embedding-3-small dimension
|
|
10
|
+
model TEXT NOT NULL DEFAULT 'text-embedding-3-small',
|
|
11
|
+
created_at TIMESTAMPTZ DEFAULT now(),
|
|
12
|
+
|
|
13
|
+
UNIQUE(signal_id, model)
|
|
14
|
+
);
|
|
15
|
+
|
|
16
|
+
-- Indexes
|
|
17
|
+
CREATE INDEX idx_vectors_user ON alchemy_vectors(user_id);
|
|
18
|
+
CREATE INDEX idx_vectors_signal ON alchemy_vectors(signal_id);
|
|
19
|
+
|
|
20
|
+
-- HNSW index for fast similarity search
|
|
21
|
+
CREATE INDEX idx_vectors_embedding ON alchemy_vectors
|
|
22
|
+
USING hnsw (embedding vector_cosine_ops);
|
|
23
|
+
|
|
24
|
+
-- RLS
|
|
25
|
+
ALTER TABLE alchemy_vectors ENABLE ROW LEVEL SECURITY;
|
|
26
|
+
|
|
27
|
+
CREATE POLICY "Users can manage their own vectors"
|
|
28
|
+
ON alchemy_vectors FOR ALL
|
|
29
|
+
USING (auth.uid() = user_id)
|
|
30
|
+
WITH CHECK (auth.uid() = user_id);
|
|
31
|
+
|
|
32
|
+
-- Similarity search function (called via supabase.rpc())
|
|
33
|
+
CREATE OR REPLACE FUNCTION match_vectors(
|
|
34
|
+
query_embedding vector(1536),
|
|
35
|
+
match_threshold FLOAT DEFAULT 0.5,
|
|
36
|
+
match_count INT DEFAULT 10,
|
|
37
|
+
target_user_id UUID DEFAULT auth.uid()
|
|
38
|
+
)
|
|
39
|
+
RETURNS TABLE (
|
|
40
|
+
id UUID,
|
|
41
|
+
signal_id UUID,
|
|
42
|
+
similarity FLOAT,
|
|
43
|
+
title TEXT,
|
|
44
|
+
summary TEXT,
|
|
45
|
+
url TEXT,
|
|
46
|
+
category TEXT
|
|
47
|
+
)
|
|
48
|
+
LANGUAGE plpgsql
|
|
49
|
+
AS $$
|
|
50
|
+
BEGIN
|
|
51
|
+
RETURN QUERY
|
|
52
|
+
SELECT
|
|
53
|
+
v.id,
|
|
54
|
+
v.signal_id,
|
|
55
|
+
(1 - (v.embedding <=> query_embedding))::FLOAT AS similarity,
|
|
56
|
+
s.title,
|
|
57
|
+
s.summary,
|
|
58
|
+
s.url,
|
|
59
|
+
s.category
|
|
60
|
+
FROM alchemy_vectors v
|
|
61
|
+
JOIN signals s ON s.id = v.signal_id
|
|
62
|
+
WHERE v.user_id = target_user_id
|
|
63
|
+
AND 1 - (v.embedding <=> query_embedding) > match_threshold
|
|
64
|
+
ORDER BY v.embedding <=> query_embedding
|
|
65
|
+
LIMIT match_count;
|
|
66
|
+
END;
|
|
67
|
+
$$;
|