@realtimex/realtimex-alchemy 1.0.56 → 1.0.57
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
CHANGED
|
@@ -5,11 +5,12 @@ 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.
|
|
8
|
+
## [1.0.57] - 2026-01-28
|
|
9
9
|
|
|
10
10
|
### Improved
|
|
11
|
-
- **
|
|
12
|
-
- **
|
|
11
|
+
- **Windows Compatibility**: Replaced Unix-specific shell scripts (`cp`, `chmod`, `.sh`) with cross-platform Node.js and `tsx` scripts. Ported `migrate.sh` to `migrate.ts` for native Windows 11 support.
|
|
12
|
+
- **Chat Interface**: Enhanced message rendering with GitHub Flavored Markdown (GFM) support and custom styling for code blocks and tables.
|
|
13
|
+
- **Build Process**: Standardized build hooks to use Node.js for file operations, ensuring reliability across all operating systems.
|
|
13
14
|
|
|
14
15
|
## [1.0.55] - 2026-01-28
|
|
15
16
|
|
|
@@ -131,7 +131,7 @@ ${e.content}`:""}`,p=new Blob([h],{type:"text/markdown"}),m=URL.createObjectURL(
|
|
|
131
131
|
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:x,table:l,tableCell:h,tableRow:u}};function l(w,_,k,S){return p(m(w,k,S),w.align)}function u(w,_,k,S){const E=y(w,k,S),T=p([E]);return T.slice(0,T.indexOf(`
|
|
132
132
|
`))}function h(w,_,k,S){const E=k.enter("tableCell"),T=k.enter("phrasing"),j=k.containerPhrasing(w,{...S,before:a,after:a});return T(),E(),j}function p(w,_){return UM(w,{align:_,alignDelimiters:s,padding:r,stringLength:i})}function m(w,_,k){const S=w.children;let E=-1;const T=[],j=_.enter("table");for(;++E<S.length;)T[E]=y(S[E],_,k);return j(),T}function y(w,_,k){const S=w.children;let E=-1;const T=[],j=_.enter("tableRow");for(;++E<S.length;)T[E]=h(S[E],w,_,k);return j(),T}function x(w,_,k){let S=Bk.inlineCode(w,_,k);return k.stack.includes("tableCell")&&(S=S.replace(/\|/g,"\\$&")),S}}function T3(){return{exit:{taskListCheckValueChecked:nw,taskListCheckValueUnchecked:nw,paragraph:A3}}}function N3(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:R3}}}function nw(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function A3(e){const n=this.stack[this.stack.length-2];if(n&&n.type==="listItem"&&typeof n.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const s=r.children[0];if(s&&s.type==="text"){const i=n.children;let a=-1,l;for(;++a<i.length;){const u=i[a];if(u.type==="paragraph"){l=u;break}}l===r&&(s.value=s.value.slice(1),s.value.length===0?r.children.shift():r.position&&s.position&&typeof s.position.start.offset=="number"&&(s.position.start.column++,s.position.start.offset++,r.position.start=Object.assign({},s.position.start)))}}this.exit(e)}function R3(e,n,r,s){const i=e.children[0],a=typeof e.checked=="boolean"&&i&&i.type==="paragraph",l="["+(e.checked?"x":" ")+"] ",u=r.createTracker(s);a&&u.move(l);let h=Bk.listItem(e,n,r,{...s,...u.current()});return a&&(h=h.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,p)),h;function p(m){return m+l}}function P3(){return[uM(),RM(),IM(),b3(),T3()]}function O3(e){return{extensions:[dM(),PM(e),DM(),C3(e),N3()]}}const L3={tokenize:$3,partial:!0},Vk={tokenize:U3,partial:!0},qk={tokenize:B3,partial:!0},Hk={tokenize:V3,partial:!0},I3={tokenize:q3,partial:!0},Kk={name:"wwwAutolink",tokenize:z3,previous:Gk},Wk={name:"protocolAutolink",tokenize:F3,previous:Jk},Cr={name:"emailAutolink",tokenize:M3,previous:Xk},dr={};function D3(){return{text:dr}}let vs=48;for(;vs<123;)dr[vs]=Cr,vs++,vs===58?vs=65:vs===91&&(vs=97);dr[43]=Cr;dr[45]=Cr;dr[46]=Cr;dr[95]=Cr;dr[72]=[Cr,Wk];dr[104]=[Cr,Wk];dr[87]=[Cr,Kk];dr[119]=[Cr,Kk];function M3(e,n,r){const s=this;let i,a;return l;function l(y){return!If(y)||!Xk.call(s,s.previous)||Xp(s.events)?r(y):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),u(y))}function u(y){return If(y)?(e.consume(y),u):y===64?(e.consume(y),h):r(y)}function h(y){return y===46?e.check(I3,m,p)(y):y===45||y===95||Xt(y)?(a=!0,e.consume(y),h):m(y)}function p(y){return e.consume(y),i=!0,h}function m(y){return a&&i&&nn(s.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(y)):r(y)}}function z3(e,n,r){const s=this;return i;function i(l){return l!==87&&l!==119||!Gk.call(s,s.previous)||Xp(s.events)?r(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(L3,e.attempt(Vk,e.attempt(qk,a),r),r)(l))}function a(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function F3(e,n,r){const s=this;let i="",a=!1;return l;function l(y){return(y===72||y===104)&&Jk.call(s,s.previous)&&!Xp(s.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),i+=String.fromCodePoint(y),e.consume(y),u):r(y)}function u(y){if(nn(y)&&i.length<5)return i+=String.fromCodePoint(y),e.consume(y),u;if(y===58){const x=i.toLowerCase();if(x==="http"||x==="https")return e.consume(y),h}return r(y)}function h(y){return y===47?(e.consume(y),a?p:(a=!0,h)):r(y)}function p(y){return y===null||kc(y)||it(y)||Ds(y)||Gc(y)?r(y):e.attempt(Vk,e.attempt(qk,m),r)(y)}function m(y){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(y)}}function $3(e,n,r){let s=0;return i;function i(l){return(l===87||l===119)&&s<3?(s++,e.consume(l),i):l===46&&s===3?(e.consume(l),a):r(l)}function a(l){return l===null?r(l):n(l)}}function U3(e,n,r){let s,i,a;return l;function l(p){return p===46||p===95?e.check(Hk,h,u)(p):p===null||it(p)||Ds(p)||p!==45&&Gc(p)?h(p):(a=!0,e.consume(p),l)}function u(p){return p===95?s=!0:(i=s,s=void 0),e.consume(p),l}function h(p){return i||s||!a?r(p):n(p)}}function B3(e,n){let r=0,s=0;return i;function i(l){return l===40?(r++,e.consume(l),i):l===41&&s<r?a(l):l===33||l===34||l===38||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===60||l===63||l===93||l===95||l===126?e.check(Hk,n,a)(l):l===null||it(l)||Ds(l)?n(l):(e.consume(l),i)}function a(l){return l===41&&s++,e.consume(l),i}}function V3(e,n,r){return s;function s(u){return u===33||u===34||u===39||u===41||u===42||u===44||u===46||u===58||u===59||u===63||u===95||u===126?(e.consume(u),s):u===38?(e.consume(u),a):u===93?(e.consume(u),i):u===60||u===null||it(u)||Ds(u)?n(u):r(u)}function i(u){return u===null||u===40||u===91||it(u)||Ds(u)?n(u):s(u)}function a(u){return nn(u)?l(u):r(u)}function l(u){return u===59?(e.consume(u),s):nn(u)?(e.consume(u),l):r(u)}}function q3(e,n,r){return s;function s(a){return e.consume(a),i}function i(a){return Xt(a)?r(a):n(a)}}function Gk(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||it(e)}function Jk(e){return!nn(e)}function Xk(e){return!(e===47||If(e))}function If(e){return e===43||e===45||e===46||e===95||Xt(e)}function Xp(e){let n=e.length,r=!1;for(;n--;){const s=e[n][1];if((s.type==="labelLink"||s.type==="labelImage")&&!s._balanced){r=!0;break}if(s._gfmAutolinkLiteralWalkedInto){r=!1;break}}return e.length>0&&!r&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const H3={tokenize:Z3,partial:!0};function K3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:X3,continuation:{tokenize:Y3},exit:Q3}},text:{91:{name:"gfmFootnoteCall",tokenize:J3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:W3,resolveTo:G3}}}}function W3(e,n,r){const s=this;let i=s.events.length;const a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let l;for(;i--;){const h=s.events[i][1];if(h.type==="labelImage"){l=h;break}if(h.type==="gfmFootnoteCall"||h.type==="labelLink"||h.type==="label"||h.type==="image"||h.type==="link")break}return u;function u(h){if(!l||!l._balanced)return r(h);const p=Xn(s.sliceSerialize({start:l.end,end:s.now()}));return p.codePointAt(0)!==94||!a.includes(p.slice(1))?r(h):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),n(h))}}function G3(e,n){let r=e.length;for(;r--;)if(e[r][1].type==="labelImage"&&e[r][0]==="enter"){e[r][1];break}e[r+1][1].type="data",e[r+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[r+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:"gfmFootnoteCallMarker",start:Object.assign({},e[r+3][1].end),end:Object.assign({},e[r+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;const a={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},a.start),end:Object.assign({},a.end)},u=[e[r+1],e[r+2],["enter",s,n],e[r+3],e[r+4],["enter",i,n],["exit",i,n],["enter",a,n],["enter",l,n],["exit",l,n],["exit",a,n],e[e.length-2],e[e.length-1],["exit",s,n]];return e.splice(r,e.length-r+1,...u),e}function J3(e,n,r){const s=this,i=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let a=0,l;return u;function u(y){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(y),e.exit("gfmFootnoteCallLabelMarker"),h}function h(y){return y!==94?r(y):(e.enter("gfmFootnoteCallMarker"),e.consume(y),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",p)}function p(y){if(a>999||y===93&&!l||y===null||y===91||it(y))return r(y);if(y===93){e.exit("chunkString");const x=e.exit("gfmFootnoteCallString");return i.includes(Xn(s.sliceSerialize(x)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(y),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):r(y)}return it(y)||(l=!0),a++,e.consume(y),y===92?m:p}function m(y){return y===91||y===92||y===93?(e.consume(y),a++,p):p(y)}}function X3(e,n,r){const s=this,i=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let a,l=0,u;return h;function h(_){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(_),e.exit("gfmFootnoteDefinitionLabelMarker"),p}function p(_){return _===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(_),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):r(_)}function m(_){if(l>999||_===93&&!u||_===null||_===91||it(_))return r(_);if(_===93){e.exit("chunkString");const k=e.exit("gfmFootnoteDefinitionLabelString");return a=Xn(s.sliceSerialize(k)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(_),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),x}return it(_)||(u=!0),l++,e.consume(_),_===92?y:m}function y(_){return _===91||_===92||_===93?(e.consume(_),l++,m):m(_)}function x(_){return _===58?(e.enter("definitionMarker"),e.consume(_),e.exit("definitionMarker"),i.includes(a)||i.push(a),Je(e,w,"gfmFootnoteDefinitionWhitespace")):r(_)}function w(_){return n(_)}}function Y3(e,n,r){return e.check(Ca,n,e.attempt(H3,n,r))}function Q3(e){e.exit("gfmFootnoteDefinition")}function Z3(e,n,r){const s=this;return Je(e,i,"gfmFootnoteDefinitionIndent",5);function i(a){const l=s.events[s.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?n(a):r(a)}}function ez(e){let r=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:a,resolveAll:i};return r==null&&(r=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function i(l,u){let h=-1;for(;++h<l.length;)if(l[h][0]==="enter"&&l[h][1].type==="strikethroughSequenceTemporary"&&l[h][1]._close){let p=h;for(;p--;)if(l[p][0]==="exit"&&l[p][1].type==="strikethroughSequenceTemporary"&&l[p][1]._open&&l[h][1].end.offset-l[h][1].start.offset===l[p][1].end.offset-l[p][1].start.offset){l[h][1].type="strikethroughSequence",l[p][1].type="strikethroughSequence";const m={type:"strikethrough",start:Object.assign({},l[p][1].start),end:Object.assign({},l[h][1].end)},y={type:"strikethroughText",start:Object.assign({},l[p][1].end),end:Object.assign({},l[h][1].start)},x=[["enter",m,u],["enter",l[p][1],u],["exit",l[p][1],u],["enter",y,u]],w=u.parser.constructs.insideSpan.null;w&&Cn(x,x.length,0,Jc(w,l.slice(p+1,h),u)),Cn(x,x.length,0,[["exit",y,u],["enter",l[h][1],u],["exit",l[h][1],u],["exit",m,u]]),Cn(l,p-1,h-p+3,x),h=p+x.length-2;break}}for(h=-1;++h<l.length;)l[h][1].type==="strikethroughSequenceTemporary"&&(l[h][1].type="data");return l}function a(l,u,h){const p=this.previous,m=this.events;let y=0;return x;function x(_){return p===126&&m[m.length-1][1].type!=="characterEscape"?h(_):(l.enter("strikethroughSequenceTemporary"),w(_))}function w(_){const k=$i(p);if(_===126)return y>1?h(_):(l.consume(_),y++,w);if(y<2&&!r)return h(_);const S=l.exit("strikethroughSequenceTemporary"),E=$i(_);return S._open=!E||E===2&&!!k,S._close=!k||k===2&&!!E,u(_)}}}class tz{constructor(){this.map=[]}add(n,r,s){nz(this,n,r,s)}consume(n){if(this.map.sort(function(a,l){return a[0]-l[0]}),this.map.length===0)return;let r=this.map.length;const s=[];for(;r>0;)r-=1,s.push(n.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),n.length=this.map[r][0];s.push(n.slice()),n.length=0;let i=s.pop();for(;i;){for(const a of i)n.push(a);i=s.pop()}this.map.length=0}}function nz(e,n,r,s){let i=0;if(!(r===0&&s.length===0)){for(;i<e.map.length;){if(e.map[i][0]===n){e.map[i][1]+=r,e.map[i][2].push(...s);return}i+=1}e.map.push([n,r,s])}}function rz(e,n){let r=!1;const s=[];for(;n<e.length;){const i=e[n];if(r){if(i[0]==="enter")i[1].type==="tableContent"&&s.push(e[n+1][1].type==="tableDelimiterMarker"?"left":"none");else if(i[1].type==="tableContent"){if(e[n-1][1].type==="tableDelimiterMarker"){const a=s.length-1;s[a]=s[a]==="left"?"center":"right"}}else if(i[1].type==="tableDelimiterRow")break}else i[0]==="enter"&&i[1].type==="tableDelimiterRow"&&(r=!0);n+=1}return s}function sz(){return{flow:{null:{name:"table",tokenize:iz,resolveAll:oz}}}}function iz(e,n,r){const s=this;let i=0,a=0,l;return u;function u(D){let Q=s.events.length-1;for(;Q>-1;){const W=s.events[Q][1].type;if(W==="lineEnding"||W==="linePrefix")Q--;else break}const Y=Q>-1?s.events[Q][1].type:null,he=Y==="tableHead"||Y==="tableRow"?R:h;return he===R&&s.parser.lazy[s.now().line]?r(D):he(D)}function h(D){return e.enter("tableHead"),e.enter("tableRow"),p(D)}function p(D){return D===124||(l=!0,a+=1),m(D)}function m(D){return D===null?r(D):Pe(D)?a>1?(a=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(D),e.exit("lineEnding"),w):r(D):Ge(D)?Je(e,m,"whitespace")(D):(a+=1,l&&(l=!1,i+=1),D===124?(e.enter("tableCellDivider"),e.consume(D),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),y(D)))}function y(D){return D===null||D===124||it(D)?(e.exit("data"),m(D)):(e.consume(D),D===92?x:y)}function x(D){return D===92||D===124?(e.consume(D),y):y(D)}function w(D){return s.interrupt=!1,s.parser.lazy[s.now().line]?r(D):(e.enter("tableDelimiterRow"),l=!1,Ge(D)?Je(e,_,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(D):_(D))}function _(D){return D===45||D===58?S(D):D===124?(l=!0,e.enter("tableCellDivider"),e.consume(D),e.exit("tableCellDivider"),k):A(D)}function k(D){return Ge(D)?Je(e,S,"whitespace")(D):S(D)}function S(D){return D===58?(a+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(D),e.exit("tableDelimiterMarker"),E):D===45?(a+=1,E(D)):D===null||Pe(D)?P(D):A(D)}function E(D){return D===45?(e.enter("tableDelimiterFiller"),T(D)):A(D)}function T(D){return D===45?(e.consume(D),T):D===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(D),e.exit("tableDelimiterMarker"),j):(e.exit("tableDelimiterFiller"),j(D))}function j(D){return Ge(D)?Je(e,P,"whitespace")(D):P(D)}function P(D){return D===124?_(D):D===null||Pe(D)?!l||i!==a?A(D):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(D)):A(D)}function A(D){return r(D)}function R(D){return e.enter("tableRow"),U(D)}function U(D){return D===124?(e.enter("tableCellDivider"),e.consume(D),e.exit("tableCellDivider"),U):D===null||Pe(D)?(e.exit("tableRow"),n(D)):Ge(D)?Je(e,U,"whitespace")(D):(e.enter("data"),V(D))}function V(D){return D===null||D===124||it(D)?(e.exit("data"),U(D)):(e.consume(D),D===92?H:V)}function H(D){return D===92||D===124?(e.consume(D),V):V(D)}}function oz(e,n){let r=-1,s=!0,i=0,a=[0,0,0,0],l=[0,0,0,0],u=!1,h=0,p,m,y;const x=new tz;for(;++r<e.length;){const w=e[r],_=w[1];w[0]==="enter"?_.type==="tableHead"?(u=!1,h!==0&&(rw(x,n,h,p,m),m=void 0,h=0),p={type:"table",start:Object.assign({},_.start),end:Object.assign({},_.end)},x.add(r,0,[["enter",p,n]])):_.type==="tableRow"||_.type==="tableDelimiterRow"?(s=!0,y=void 0,a=[0,0,0,0],l=[0,r+1,0,0],u&&(u=!1,m={type:"tableBody",start:Object.assign({},_.start),end:Object.assign({},_.end)},x.add(r,0,[["enter",m,n]])),i=_.type==="tableDelimiterRow"?2:m?3:1):i&&(_.type==="data"||_.type==="tableDelimiterMarker"||_.type==="tableDelimiterFiller")?(s=!1,l[2]===0&&(a[1]!==0&&(l[0]=l[1],y=Xl(x,n,a,i,void 0,y),a=[0,0,0,0]),l[2]=r)):_.type==="tableCellDivider"&&(s?s=!1:(a[1]!==0&&(l[0]=l[1],y=Xl(x,n,a,i,void 0,y)),a=l,l=[a[1],r,0,0])):_.type==="tableHead"?(u=!0,h=r):_.type==="tableRow"||_.type==="tableDelimiterRow"?(h=r,a[1]!==0?(l[0]=l[1],y=Xl(x,n,a,i,r,y)):l[1]!==0&&(y=Xl(x,n,l,i,r,y)),i=0):i&&(_.type==="data"||_.type==="tableDelimiterMarker"||_.type==="tableDelimiterFiller")&&(l[3]=r)}for(h!==0&&rw(x,n,h,p,m),x.consume(n.events),r=-1;++r<n.events.length;){const w=n.events[r];w[0]==="enter"&&w[1].type==="table"&&(w[1]._align=rz(n.events,r))}return e}function Xl(e,n,r,s,i,a){const l=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",u="tableContent";r[0]!==0&&(a.end=Object.assign({},Si(n.events,r[0])),e.add(r[0],0,[["exit",a,n]]));const h=Si(n.events,r[1]);if(a={type:l,start:Object.assign({},h),end:Object.assign({},h)},e.add(r[1],0,[["enter",a,n]]),r[2]!==0){const p=Si(n.events,r[2]),m=Si(n.events,r[3]),y={type:u,start:Object.assign({},p),end:Object.assign({},m)};if(e.add(r[2],0,[["enter",y,n]]),s!==2){const x=n.events[r[2]],w=n.events[r[3]];if(x[1].end=Object.assign({},w[1].end),x[1].type="chunkText",x[1].contentType="text",r[3]>r[2]+1){const _=r[2]+1,k=r[3]-r[2]-1;e.add(_,k,[])}}e.add(r[3]+1,0,[["exit",y,n]])}return i!==void 0&&(a.end=Object.assign({},Si(n.events,i)),e.add(i,0,[["exit",a,n]]),a=void 0),a}function rw(e,n,r,s,i){const a=[],l=Si(n.events,r);i&&(i.end=Object.assign({},l),a.push(["exit",i,n])),s.end=Object.assign({},l),a.push(["exit",s,n]),e.add(r+1,0,a)}function Si(e,n){const r=e[n],s=r[0]==="enter"?"start":"end";return r[1][s]}const az={name:"tasklistCheck",tokenize:cz};function lz(){return{text:{91:az}}}function cz(e,n,r){const s=this;return i;function i(h){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?r(h):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(h),e.exit("taskListCheckMarker"),a)}function a(h){return it(h)?(e.enter("taskListCheckValueUnchecked"),e.consume(h),e.exit("taskListCheckValueUnchecked"),l):h===88||h===120?(e.enter("taskListCheckValueChecked"),e.consume(h),e.exit("taskListCheckValueChecked"),l):r(h)}function l(h){return h===93?(e.enter("taskListCheckMarker"),e.consume(h),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),u):r(h)}function u(h){return Pe(h)?n(h):Ge(h)?e.check({tokenize:uz},n,r)(h):r(h)}}function uz(e,n,r){return Je(e,s,"whitespace");function s(i){return i===null?r(i):n(i)}}function dz(e){return ak([D3(),K3(),ez(e),sz(),lz()])}const hz={};function fz(e){const n=this,r=e||hz,s=n.data(),i=s.micromarkExtensions||(s.micromarkExtensions=[]),a=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),l=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);i.push(dz(r)),a.push(P3()),l.push(O3(r))}function pz({message:e}){const{t:n}=rt(),r=e.role==="user",s={p:({node:i,...a})=>f.jsx("p",{className:"mb-2 last:mb-0",...a}),a:({node:i,...a})=>f.jsx("a",{className:"text-primary hover:underline",...a}),ul:({node:i,...a})=>f.jsx("ul",{className:"list-disc ml-4 mb-2",...a}),ol:({node:i,...a})=>f.jsx("ol",{className:"list-decimal ml-4 mb-2",...a}),blockquote:({node:i,...a})=>f.jsx("blockquote",{className:"border-l-2 border-border/50 pl-3 text-fg/70 italic mb-2",...a}),table:({node:i,...a})=>f.jsx("table",{className:"w-full text-xs border-collapse my-2",...a}),th:({node:i,...a})=>f.jsx("th",{className:"border border-border/20 bg-surface/50 px-2 py-1 text-left font-semibold",...a}),td:({node:i,...a})=>f.jsx("td",{className:"border border-border/20 px-2 py-1 align-top",...a}),code:({node:i,inline:a,className:l,...u})=>f.jsx("code",{className:a?"bg-black/20 rounded px-1 py-0.5 font-mono text-xs":"block bg-black/30 rounded-lg p-3 font-mono text-xs leading-relaxed overflow-x-auto",...u}),pre:({node:i,...a})=>f.jsx("pre",{className:"my-2",...a})};return f.jsx("div",{className:`flex w-full ${r?"justify-end":"justify-start"}`,children:f.jsxs("div",{className:`flex gap-3 max-w-[85%] ${r?"flex-row-reverse":"flex-row"}`,children:[f.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${r?"bg-primary text-white":"bg-gradient-to-br from-indigo-500 to-purple-600 text-white shadow-lg glow-primary"}`,children:r?f.jsx(Ac,{size:16}):f.jsx(cj,{size:16})}),f.jsxs("div",{className:`flex flex-col ${r?"items-end":"items-start"}`,children:[f.jsx("div",{className:`px-5 py-3.5 rounded-2xl text-sm leading-relaxed shadow-sm ${r?"bg-primary/15 text-fg rounded-tr-none":"bg-surface/70 backdrop-blur-md text-fg rounded-tl-none"}`,children:f.jsx("div",{className:"markdown-body",children:f.jsx(Wp,{remarkPlugins:[fz],components:s,children:e.content})})}),f.jsx("span",{className:"text-[10px] text-fg/30 mt-1 px-1",children:new Date(e.created_at).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})})]})]})})}function mz({sessionId:e,onContextUpdate:n,onNewSession:r,onSessionCreated:s}){const{t:i}=rt(),[a,l]=O.useState([]),[u,h]=O.useState(""),[p,m]=O.useState(!1),[y,x]=O.useState(!1),w=O.useRef(null),_=O.useRef(null),k=O.useRef(!0),S=O.useRef(null);O.useEffect(()=>{e?T(e):(l([]),n([]))},[e,n]),O.useEffect(()=>{k.current&&w.current&&w.current.scrollIntoView({behavior:"smooth"})},[a,y]);const E=()=>{const A=_.current;if(!A)return;const R=A.scrollHeight-A.scrollTop-A.clientHeight;k.current=R<64},T=async A=>{try{const{data:{session:R}}=await ae.auth.getSession();if(!R)return;const U=await Ze.get(`/api/chat/sessions/${A}/messages`,{headers:{"x-user-id":R.user.id}});if(U.data.success){l(U.data.messages);const V=U.data.messages[U.data.messages.length-1];V&&V.role==="assistant"&&V.context_sources&&n(V.context_sources)}}catch(R){console.error("Failed to fetch messages",R)}},j=async A=>{if(A?.preventDefault(),!u.trim()||p)return;const R=u.trim();h(""),S.current&&(S.current.style.height="auto");const{data:{session:U}}=await ae.auth.getSession();if(!U)return;const V=U.user.id;m(!0),x(!0);try{let H=e;if(!H){const Y=await Ze.post("/api/chat/sessions",{},{headers:{"x-user-id":V}});if(Y.data.success)H=Y.data.session.id,s(H);else throw new Error("Failed to create session")}const D={id:"temp-"+Date.now(),role:"user",content:R,created_at:new Date().toISOString()};l(Y=>[...Y,D]);const Q=await Ze.post("/api/chat/message",{sessionId:H,content:R},{headers:{"x-user-id":V}});if(Q.data.success){const Y=Q.data.message;l(he=>[...he,Y]),Y.context_sources&&n(Y.context_sources)}}catch(H){console.error("Message failed",H),l(D=>[...D,{id:"err-"+Date.now(),role:"assistant",content:i("chat.error_message"),created_at:new Date().toISOString()}])}finally{m(!1),x(!1)}},P=A=>{A.key==="Enter"&&!A.shiftKey&&(A.preventDefault(),j())};return f.jsxs(f.Fragment,{children:[f.jsxs("div",{ref:_,onScroll:E,className:"flex-1 overflow-y-auto p-5 space-y-6 scrollbar-on-hover",children:[a.length===0?f.jsxs("div",{className:"h-full flex flex-col items-center justify-center p-8 text-center opacity-70",children:[f.jsx("div",{className:"w-16 h-16 bg-primary/10 rounded-2xl flex items-center justify-center mb-4 text-primary animate-pulse",children:f.jsx(Mj,{size:32})}),f.jsx("h3",{className:"text-xl font-bold mb-2",children:i("chat.title")}),f.jsx("p",{className:"text-sm max-w-md mx-auto mb-8",children:i("chat.desc")}),f.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 max-w-lg w-full",children:[i("chat.suggestions.react"),i("chat.suggestions.ai"),i("chat.suggestions.finance"),i("chat.suggestions.performance")].map((A,R)=>f.jsx("button",{onClick:()=>h(A),className:"text-left p-3 text-xs bg-surface/30 hover:bg-surface/50 border border-border/20 rounded-xl transition-all hover:scale-[1.02]",children:A},R))})]}):f.jsxs(f.Fragment,{children:[a.map((A,R)=>f.jsx(pz,{message:A},A.id||R)),y&&f.jsx($e.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"flex justify-start w-full",children:f.jsxs("div",{className:"bg-surface/30 border border-border/10 rounded-2xl px-4 py-3 flex items-center gap-3",children:[f.jsxs("div",{className:"flex gap-1",children:[f.jsx("span",{className:"w-1.5 h-1.5 bg-primary/60 rounded-full animate-bounce",style:{animationDelay:"0s"}}),f.jsx("span",{className:"w-1.5 h-1.5 bg-primary/60 rounded-full animate-bounce",style:{animationDelay:"0.1s"}}),f.jsx("span",{className:"w-1.5 h-1.5 bg-primary/60 rounded-full animate-bounce",style:{animationDelay:"0.2s"}})]}),f.jsx("span",{className:"text-xs text-fg/50 font-mono",children:i("chat.thinking")})]})})]}),f.jsx("div",{ref:w})]}),f.jsx("div",{className:"p-4 bg-surface/20 border-t border-border/10 backdrop-blur-md",children:f.jsx("form",{onSubmit:j,className:"relative max-w-4xl mx-auto",children:f.jsxs("div",{className:"relative flex items-end gap-2 bg-surface/55 border border-border/10 rounded-2xl px-2 py-2 shadow-sm focus-within:ring-2 focus-within:ring-primary/30 focus-within:border-primary/30 transition-all",children:[f.jsx("textarea",{ref:S,value:u,onChange:A=>{h(A.target.value),A.target.style.height="auto",A.target.style.height=A.target.scrollHeight+"px"},onKeyDown:P,placeholder:i("chat.placeholder"),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:p}),f.jsx("button",{type:"submit",disabled:!u.trim()||p,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:p?f.jsx(Nc,{size:18,className:"animate-spin"}):f.jsx(Ij,{size:18})})]})})})]})}function gz({sources:e,onClose:n}){const{t:r}=rt();return!e||e.length===0?null:f.jsxs($e.div,{initial:{opacity:0,x:20,width:0},animate:{opacity:1,x:0,width:300},exit:{opacity:0,x:20,width:0},className:"bg-surface/25 backdrop-blur-xl rounded-2xl border border-border/10 overflow-hidden flex flex-col shadow-[0_8px_24px_rgba(0,0,0,0.16)]",children:[f.jsxs("div",{className:"p-4 border-b border-border/10 flex items-center justify-between bg-surface/15",children:[f.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-fg/80",children:[f.jsx(uw,{size:16,className:"text-secondary"}),f.jsx("span",{children:r("chat.relevant_context")})]}),f.jsx("button",{onClick:n,className:"p-1 hover:bg-surface rounded-md text-fg/40 hover:text-fg transition-colors",children:f.jsx(Tn,{size:14})})]}),f.jsx("div",{className:"flex-1 overflow-y-auto p-3 space-y-3",children:e.map((s,i)=>f.jsxs("div",{className:"p-3 bg-surface/20 hover:bg-surface/35 border border-border/5 rounded-xl transition-all group",children:[f.jsxs("div",{className:"flex justify-between items-start mb-2",children:[f.jsxs("div",{className:"flex items-center gap-1.5",children:[f.jsx("span",{className:"flex items-center justify-center w-4 h-4 bg-primary/10 text-primary text-[10px] font-bold rounded",children:i+1}),f.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded border ${s.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:r("chat.match_score",{score:s.score})})]}),f.jsx("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"opacity-0 group-hover:opacity-100 focus-visible:opacity-100 text-fg/40 hover:text-primary transition-opacity focus-visible:ring-2 focus-visible:ring-primary/40 rounded",children:f.jsx(Ui,{size:12})})]}),f.jsx("a",{href:s.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:s.title}),f.jsx("p",{className:"text-[10px] text-fg/50 line-clamp-3 leading-relaxed",children:s.summary})]},i))}),f.jsx("div",{className:"p-3 border-t border-border/10 bg-surface/20 text-[10px] text-center text-fg/30",children:r("chat.rag_attribution",{count:e.length})})]})}function yz(){const[e,n]=O.useState(null),[r,s]=O.useState([]),[i,a]=O.useState(!0);return f.jsxs("div",{className:"flex h-full gap-4 overflow-hidden",children:[f.jsx(qL,{activeSessionId:e,onSelectSession:n}),f.jsx("div",{className:"flex-1 flex flex-col min-w-0 bg-surface/60 rounded-2xl overflow-hidden border border-border/15 shadow-[0_12px_30px_rgba(0,0,0,0.22)] relative",children:f.jsx(mz,{sessionId:e,onContextUpdate:l=>{s(l),l.length>0&&a(!0)},onNewSession:()=>n(null),onSessionCreated:l=>n(l)})}),i&&f.jsx(gz,{sources:r,onClose:()=>a(!1)})]})}function xz({isOpen:e,onClose:n}){const{t:r}=rt(),[s,i]=O.useState(""),[a,l]=O.useState(!0);O.useEffect(()=>{e&&u()},[e]);const u=async()=>{l(!0);try{const p=await(await fetch("/CHANGELOG.md")).text();i(p)}catch(h){console.error("Failed to load changelog:",h),i(`# ${r("common.error")}
|
|
133
133
|
|
|
134
|
-
${r("shell.changelog_error")}`)}finally{l(!1)}};return f.jsx(Ot,{children:e&&f.jsxs(f.Fragment,{children:[f.jsx($e.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:n,className:"fixed inset-0 bg-black/60 backdrop-blur-sm z-50"}),f.jsx($e.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:f.jsxs("div",{className:"glass w-full max-w-3xl max-h-[80vh] overflow-hidden pointer-events-auto shadow-2xl",children:[f.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx(uw,{size:24,className:"text-primary"}),f.jsx("h2",{className:"text-xl font-bold",children:r("shell.release_notes")})]}),f.jsx("button",{onClick:n,className:"p-2 hover:bg-surface rounded-lg transition-colors",children:f.jsx(Tn,{size:20,className:"text-fg/60"})})]}),f.jsx("div",{className:"p-6 overflow-y-auto custom-scrollbar max-h-[calc(80vh-88px)]",children:a?f.jsx("div",{className:"flex items-center justify-center py-12",children:f.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-primary border-t-transparent"})}):f.jsx(Wp,{components:{h1:({children:h})=>f.jsx("h1",{className:"text-2xl font-bold text-fg mb-6 mt-0",children:h}),h2:({children:h})=>f.jsx("h2",{className:"text-xl font-bold text-fg mt-8 mb-3 pb-2 border-b border-border first:mt-0",children:h}),h3:({children:h})=>f.jsx("h3",{className:"text-lg font-bold text-primary mt-6 mb-2",children:h}),p:({children:h})=>f.jsx("p",{className:"text-sm text-fg/70 mb-3 leading-relaxed",children:h}),ul:({children:h})=>f.jsx("ul",{className:"list-none space-y-1 mb-4 ml-0",children:h}),li:({children:h})=>f.jsx("li",{className:"text-sm text-fg/80 ml-4 mb-1 before:content-['•'] before:mr-2 before:text-primary",children:h}),a:({href:h,children:p})=>f.jsx("a",{href:h,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:text-primary/80 underline transition-colors",children:p}),code:({children:h})=>f.jsx("code",{className:"bg-surface/50 text-accent px-1.5 py-0.5 rounded text-xs font-mono border border-border",children:h}),strong:({children:h})=>f.jsx("strong",{className:"font-bold text-fg",children:h})},children:s})})]})})]})})}function vz({asset:e,onClose:n}){const{t:r}=rt(),s=()=>{e.content&&navigator.clipboard.writeText(e.content)},i=()=>{if(!e.content)return;const a=new Blob([e.content],{type:"text/markdown"}),l=URL.createObjectURL(a),u=document.createElement("a");u.href=l,u.download=`${e.title.replace(/[^a-z0-9]/gi,"_").toLowerCase()}.md`,document.body.appendChild(u),u.click(),document.body.removeChild(u),URL.revokeObjectURL(l)};return f.jsx(Ot,{children:e&&f.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:f.jsxs($e.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:[f.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:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.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"?f.jsx(Uh,{className:"w-5 h-5"}):f.jsx(Li,{className:"w-5 h-5"})}),f.jsxs("div",{children:[f.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e.title}),f.jsxs("p",{className:"text-xs text-gray-500",children:[new Date(e.created_at).toLocaleString()," • ",r("discovery.sources_count",{count:e.metadata?.source_signal_count||0})]})]})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{onClick:s,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:f.jsx(Df,{className:"w-4 h-4"})}),f.jsx("button",{onClick:i,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:f.jsx(Fh,{className:"w-4 h-4"})}),f.jsx("div",{className:"w-px h-6 bg-gray-200 dark:bg-gray-700 mx-1"}),f.jsx("button",{onClick:n,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:f.jsx(Tn,{className:"w-5 h-5"})})]})]}),f.jsx("div",{className:"flex-1 overflow-y-auto p-6 bg-white dark:bg-gray-950",children:e.status&&e.status!=="completed"?f.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-4",children:[f.jsx(Pt,{className:"w-12 h-12 animate-spin text-purple-500"}),f.jsxs("div",{className:"text-center",children:[f.jsx("h4",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:e.status==="processing"?r("transmute.generating_asset"):r("transmute.queued_desktop")}),f.jsx("p",{className:"text-sm text-gray-500 max-w-xs mt-1",children:r("transmute.desktop_processing")})]})]}):e.type==="markdown"?f.jsx("div",{className:"prose dark:prose-invert max-w-none",children:f.jsx(Wp,{children:e.content||""})}):e.type==="audio"?f.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-4",children:[f.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:f.jsx(Uh,{className:"w-8 h-8 text-purple-600 dark:text-purple-400"})}),f.jsx("p",{className:"text-gray-500",children:r("transmute.unsupported_type")}),f.jsxs("audio",{controls:!0,className:"w-full max-w-md mt-4",children:[f.jsx("source",{src:e.content||"",type:"audio/mpeg"}),"Your browser does not support the audio element."]})]}):f.jsx("div",{className:"text-gray-500 text-center py-10",children:"Unsupported asset type"})})]})})})}function sw({engine:e,onClose:n,onSave:r,onDelete:s}){const{t:i}=rt(),{showToast:a}=Wc(),[l,u]=O.useState({title:"",type:"newsletter",status:"active",config:{schedule:"",min_score:70,categories:[],custom_prompt:"",max_signals:10,execution_mode:"local"}}),[h,p]=O.useState(!1);O.useEffect(()=>{e&&u({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 m=async()=>{try{const w={title:l.title,type:l.type,status:l.status,config:{schedule:l.config.schedule,filters:{min_score:l.config.min_score,category:l.config.category},custom_prompt:l.config.custom_prompt,max_signals:l.config.max_signals,execution_mode:l.config.execution_mode}};if(e){const{data:_,error:k}=await ae.from("engines").update(w).eq("id",e.id).select().single();if(k)throw k;r(_),a("Engine updated successfully","success")}else{const{data:{user:_}}=await ae.auth.getUser();if(!_)throw new Error("Not authenticated");const{data:k,error:S}=await ae.from("engines").insert({...w,user_id:_.id}).select().single();if(S)throw S;r(k),a("Engine created successfully","success")}n()}catch(w){console.error("Save error:",w),a(w.message||"Failed to save engine","error")}},y=async()=>{if(!(!e||!s))try{const{error:w}=await ae.from("engines").delete().eq("id",e.id);if(w)throw w;s(e.id),a("Engine deleted","success"),n()}catch(w){a(w.message||"Failed to delete engine","error")}},x=()=>{p(!1),n()};return!e&&!n?null:f.jsx(Ot,{children:f.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:f.jsxs($e.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:[f.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800",children:[f.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:i(e?"transmute.edit_engine":"transmute.create_engine")}),f.jsx("button",{onClick:x,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:f.jsx(Tn,{className:"w-5 h-5"})})]}),f.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6",children:[f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:i("transmute.engine_name")}),f.jsx("input",{type:"text",value:l.title,onChange:w=>u({...l,title:w.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"})]}),f.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:i("transmute.type")}),f.jsxs("select",{value:l.type,onChange:w=>u({...l,type:w.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:[f.jsx("option",{value:"newsletter",children:i("transmute.newsletter")}),f.jsx("option",{value:"thread",children:i("transmute.thread")}),f.jsx("option",{value:"audio",children:"Audio Brief"}),f.jsx("option",{value:"report",children:"Report"})]})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:i("transmute.status")}),f.jsxs("select",{value:l.status,onChange:w=>u({...l,status:w.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:[f.jsx("option",{value:"active",children:i("common.status_active")}),f.jsx("option",{value:"paused",children:i("common.status_paused")}),f.jsx("option",{value:"draft",children:"Draft"})]})]})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:i("transmute.execution_env")}),f.jsxs("select",{value:l.config.execution_mode,onChange:w=>u({...l,config:{...l.config,execution_mode:w.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:[f.jsx("option",{value:"local",children:i("transmute.local_llm")}),f.jsx("option",{value:"desktop",children:i("transmute.desktop_swarm")})]}),f.jsx("p",{className:"text-[10px] text-gray-500 mt-1",children:l.config.execution_mode==="desktop"?i("transmute.env_desc_desktop"):i("transmute.env_desc_local")})]})]}),f.jsxs("div",{className:"space-y-4",children:[f.jsx("h4",{className:"font-medium text-gray-900 dark:text-gray-100",children:"Signal Filters"}),f.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:i("transmute.min_score")}),f.jsx("input",{type:"number",min:"0",max:"100",value:l.config.min_score,onChange:w=>u({...l,config:{...l.config,min_score:parseInt(w.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"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:i("transmute.max_signals")}),f.jsx("input",{type:"number",min:"1",max:"50",value:l.config.max_signals,onChange:w=>u({...l,config:{...l.config,max_signals:parseInt(w.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"})]})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:i("transmute.category_filter")}),f.jsxs("select",{multiple:!0,value:l.config.categories,onChange:w=>{const _=Array.from(w.target.selectedOptions,k=>k.value);u({...l,config:{...l.config,categories:_}})},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:[f.jsx("option",{value:"AI & ML",children:"AI & ML"}),f.jsx("option",{value:"Technology",children:"Technology"}),f.jsx("option",{value:"Business",children:"Business"}),f.jsx("option",{value:"Finance",children:"Finance"}),f.jsx("option",{value:"Science",children:"Science"}),f.jsx("option",{value:"Politics",children:"Politics"})]}),f.jsx("p",{className:"text-xs text-gray-500 mt-1",children:i("transmute.multi_select_hint")})]})]}),f.jsxs("div",{children:[f.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:[i("transmute.schedule")," (",i("common.optional"),")"]}),f.jsx("input",{type:"text",value:l.config.schedule,onChange:w=>u({...l,config:{...l.config,schedule:w.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"}),f.jsx("p",{className:"text-xs text-gray-500 mt-1",children:i("transmute.schedule_hint")})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:i("transmute.prompt_override")}),f.jsx("textarea",{value:l.config.custom_prompt,onChange:w=>u({...l,config:{...l.config,custom_prompt:w.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:i("transmute.prompt_placeholder")})]})]}),f.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&&s?h?f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("span",{className:"text-sm text-red-600 font-medium",children:i("transmute.delete_confirm")}),f.jsx("button",{onClick:y,className:"px-3 py-1.5 bg-red-600 text-white text-xs rounded-lg hover:bg-red-700 transition-colors",children:i("transmute.confirm")}),f.jsx("button",{onClick:()=>p(!1),className:"px-3 py-1.5 text-gray-500 hover:text-gray-700 text-xs rounded-lg",children:i("common.cancel")})]}):f.jsxs("button",{onClick:()=>p(!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:[f.jsx(Ff,{className:"w-4 h-4"}),i("common.delete")]}):f.jsx("div",{}),f.jsxs("div",{className:"flex gap-2",children:[f.jsx("button",{onClick:x,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"}),f.jsxs("button",{onClick:m,className:"flex items-center gap-2 px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors",children:[f.jsx(br,{className:"w-4 h-4"}),"Save"]})]})]})]})})})}const wz=({engine:e,onRun:n,onEdit:r,onToggle:s,onViewBrief:i,isLoading:a})=>{const{t:l}=rt(),u=!!e.config.tag,h={newsletter:u?f.jsx(Mf,{className:"w-5 h-5 text-blue-500"}):f.jsx(Li,{className:"w-5 h-5 text-emerald-500"}),thread:f.jsx(rn,{className:"w-5 h-5 text-blue-500"}),audio:f.jsx(Uh,{className:"w-5 h-5 text-purple-500"}),report:f.jsx(oc,{className:"w-5 h-5 text-orange-500"})};return f.jsxs($e.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:[f.jsxs("div",{className:"flex justify-between items-start mb-4",children:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("div",{className:"p-2 rounded-xl bg-gray-100 dark:bg-gray-800",children:h[e.type]||f.jsx(Li,{className:"w-5 h-5"})}),f.jsxs("div",{children:[f.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e.title}),f.jsxs("p",{className:"text-xs text-gray-500 capitalize",children:[u?l("transmute.topic"):l(`transmute.${e.type}`,e.type)," ",l("transmute.pipeline")]})]})]}),f.jsxs("div",{className:"flex gap-1",children:[f.jsx("button",{onClick:()=>s(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"?f.jsx(Pj,{className:"w-4 h-4"}):f.jsx(Wy,{className:"w-4 h-4"})}),f.jsx("button",{onClick:()=>i(e.id),title:l("transmute.view_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:f.jsx(fw,{className:"w-4 h-4"})}),f.jsx("button",{onClick:()=>r(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:f.jsx(oc,{className:"w-4 h-4"})})]})]}),f.jsxs("div",{className:"space-y-2 mb-4",children:[f.jsxs("div",{className:"text-xs text-gray-500 flex justify-between",children:[f.jsx("span",{children:l("transmute.last_run")}),f.jsx("span",{children:e.last_run_at?new Date(e.last_run_at).toLocaleDateString(l("common.locale_code")):l("transmute.never")})]}),f.jsxs("div",{className:"text-xs text-gray-500 flex justify-between",children:[f.jsx("span",{children:l("transmute.schedule")}),f.jsx("span",{children:e.config.schedule||l("transmute.manual")})]})]}),f.jsxs("button",{onClick:()=>n(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?f.jsx(Pt,{className:"w-4 h-4 animate-spin"}):f.jsx(Wy,{className:"w-4 h-4"}),l(a?"transmute.running":"transmute.run_engine")]})]})};function bz(){const{t:e}=rt(),[n,r]=O.useState([]),[s,i]=O.useState(!0),[a,l]=O.useState(new Set),[u,h]=O.useState(null),[p,m]=O.useState(null),[y,x]=O.useState(!1),[w,_]=O.useState(null),[k,S]=O.useState(!1),[E,T]=O.useState(!1),{showToast:j}=Wc();O.useEffect(()=>{(async()=>A())();const G=ae.channel("asset-updates").on("postgres_changes",{event:"UPDATE",schema:"public",table:"assets"},ne=>{const re=ne.new;h(X=>X?.id===re.id?re:X),re.status==="completed"&&ne.old.status!=="completed"&&j(e("transmute.asset_ready",{title:re.title}),"success")}).subscribe();return()=>{ae.removeChannel(G)}},[]);const P=async()=>{if(!E)try{T(!0),j(e("transmute.scanning"),"info");const{data:{session:W}}=await ae.auth.getSession(),G=Ps(),ne={"Content-Type":"application/json","x-user-id":W?.user?.id||""};if(W?.access_token&&(ne.Authorization=`Bearer ${W.access_token}`),G&&(ne["x-supabase-url"]=G.url,ne["x-supabase-key"]=G.anonKey),!(await fetch("/api/engines/ensure-defaults",{method:"POST",headers:ne})).ok)throw new Error("Failed to generate engines");j(e("transmute.discovery_complete"),"success"),await A()}catch(W){console.error("Failed to generate engines:",W),j(e("transmute.discovery_failed"),"error")}finally{T(!1)}},A=async()=>{try{i(!0);const{data:{user:W}}=await ae.auth.getUser();if(!W)return;const{data:G,error:ne}=await ae.from("engines").select("*").eq("user_id",W.id).order("created_at",{ascending:!1});if(ne)throw ne;r(G)}catch(W){console.error("Error fetching engines:",W),j(e("transmute.load_failed"),"error")}finally{i(!1)}},R=async W=>{if(!a.has(W))try{l(M=>new Set(M).add(W)),j(e("transmute.starting_run"),"info");const{data:{session:G}}=await ae.auth.getSession(),ne=G?.access_token,re=Ps(),X={"Content-Type":"application/json","x-user-id":G?.user?.id||""};ne&&(X.Authorization=`Bearer ${ne}`),re&&(X["x-supabase-url"]=re.url,X["x-supabase-key"]=re.anonKey);const ce=await fetch(`/api/engines/${W}/run`,{method:"POST",headers:X});if(!ce.ok){const M=await ce.json();throw new Error(M.error||"Run failed")}const N=await ce.json();N.status==="completed"?j(e("transmute.run_complete",{title:N.title}),"success"):j(e("transmute.run_started_desktop",{id:N.id}),"info"),h(N),r(M=>M.map(J=>J.id===W?{...J,last_run_at:new Date().toISOString()}:J))}catch(G){console.error("Engine run error:",G),j(G.message||e("transmute.run_failed"),"error")}finally{l(G=>{const ne=new Set(G);return ne.delete(W),ne})}},U=async W=>{try{x(!0);const{data:{session:G}}=await ae.auth.getSession(),ne=Ps(),re={"Content-Type":"application/json","x-user-id":G?.user?.id||""};G?.access_token&&(re.Authorization=`Bearer ${G.access_token}`),ne&&(re["x-supabase-url"]=ne.url,re["x-supabase-key"]=ne.anonKey);const X=await fetch(`/api/engines/${W}/brief`,{headers:re});if(!X.ok)throw new Error("Failed to fetch brief");const ce=await X.json();m(ce)}catch{j(e("transmute.brief_failed"),"error")}finally{x(!1)}},V=async(W,G)=>{const ne=G==="active"?"paused":"active";r(re=>re.map(X=>X.id===W?{...X,status:ne}:X));try{const{error:re}=await ae.from("engines").update({status:ne}).eq("id",W);if(re)throw re;j(e("transmute.status_updated",{status:ne}),"success")}catch{r(X=>X.map(ce=>ce.id===W?{...ce,status:G}:ce)),j(e("common.error"),"error")}},H=()=>{S(!0)},D=W=>{const G=n.find(ne=>ne.id===W);G&&_(G)},Q=W=>{r(G=>G.find(re=>re.id===W.id)?G.map(re=>re.id===W.id?W:re):[W,...G])},Y=W=>{r(G=>G.filter(ne=>ne.id!==W))},he=()=>{_(null),S(!1)};return f.jsxs("div",{className:"h-full flex flex-col bg-gray-50/50 dark:bg-[#0A0A0A]",children:[f.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:f.jsxs("div",{className:"flex justify-between items-center max-w-7xl mx-auto w-full",children:[f.jsxs("div",{children:[f.jsx("h2",{className:"text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-purple-500 to-blue-500",children:e("transmute.title")}),f.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:e("transmute.desc")})]}),f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsxs("button",{onClick:P,disabled:E,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:[E?f.jsx(Pt,{className:"w-4 h-4 animate-spin"}):f.jsx(rn,{className:"w-4 h-4"}),e("transmute.generate_engines")]}),f.jsxs("button",{onClick:H,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:[f.jsx(zf,{className:"w-4 h-4"}),e("transmute.new_engine")]})]})]})}),f.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:f.jsx("div",{className:"max-w-7xl mx-auto w-full",children:s?f.jsx("div",{className:"flex items-center justify-center h-64",children:f.jsx(Pt,{className:"w-8 h-8 animate-spin text-purple-500"})}):n.length===0?f.jsxs("div",{className:"flex flex-col items-center justify-center h-96 text-center",children:[f.jsx("div",{className:"w-16 h-16 rounded-2xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-4",children:f.jsx(rn,{className:"w-8 h-8 text-gray-400"})}),f.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:e("transmute.no_engines")}),f.jsx("p",{className:"text-gray-500 max-w-sm mt-2 mb-6",children:e("transmute.no_engines_desc")}),f.jsx("button",{onClick:H,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:e("transmute.create_engine")})]}):f.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:f.jsx(Ot,{children:n.map(W=>f.jsx(wz,{engine:W,onRun:R,onEdit:D,onToggle:V,onViewBrief:U,isLoading:a.has(W.id)},W.id))})})})}),f.jsx(Ot,{children:p&&f.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/60 backdrop-blur-md",children:f.jsxs($e.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:[f.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:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("div",{className:"p-2 rounded-lg bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400",children:f.jsx(fw,{className:"w-5 h-5"})}),f.jsxs("div",{children:[f.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e("transmute.view_json")}),f.jsx("p",{className:"text-xs text-gray-500",children:e("transmute.json_contract")})]})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{onClick:()=>{navigator.clipboard.writeText(JSON.stringify(p,null,2)),j(e("transmute.copied_json"),"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:f.jsx(Df,{className:"w-4 h-4"})}),f.jsx("button",{onClick:()=>m(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:f.jsx(Tn,{className:"w-5 h-5"})})]})]}),f.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-[#0D1117] font-mono text-sm",children:f.jsx("pre",{className:"text-blue-300",children:JSON.stringify(p,null,2)})}),f.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:e("transmute.json_footer")})]})})}),y&&f.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/20 backdrop-blur-sm",children:f.jsx(Pt,{className:"w-10 h-10 animate-spin text-white"})}),f.jsx(vz,{asset:u,onClose:()=>h(null)}),w&&f.jsx(sw,{engine:w,onClose:he,onSave:Q,onDelete:Y}),k&&f.jsx(sw,{engine:null,onClose:he,onSave:Q})]})}const zh=[{code:"en",label:"English",flag:"🇺🇸"},{code:"fr",label:"Français",flag:"🇫🇷"},{code:"es",label:"Español",flag:"🇪🇸"},{code:"ko",label:"한국어",flag:"🇰🇷"},{code:"ja",label:"日本語",flag:"🇯🇵"},{code:"vi",label:"Tiếng Việt",flag:"🇻🇳"}];function _z({collapsed:e=!1}){const{i18n:n}=rt(),[r,s]=O.useState(!1),i=O.useRef(null),a=zh.find(u=>u.code===n.language)||zh[0];O.useEffect(()=>{const u=h=>{i.current&&!i.current.contains(h.target)&&s(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[]);const l=u=>{n.changeLanguage(u),s(!1)};return f.jsxs("div",{className:"relative",ref:i,children:[f.jsxs("button",{onClick:()=>s(!r),className:`flex items-center gap-2 px-3 py-1.5 rounded-lg bg-white/5 border border-white/10 hover:bg-white/10 transition-all text-xs font-medium text-fg/70 ${e?"justify-center px-1.5":""}`,title:e?a.label:void 0,children:[!e&&f.jsx(jj,{size:14,className:"text-primary"}),f.jsx("span",{children:a.flag}),!e&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"hidden sm:inline",children:a.label}),f.jsx(Os,{size:12,className:`transition-transform duration-300 ${r?"rotate-180":""}`})]})]}),f.jsx(Ot,{children:r&&f.jsx($e.div,{initial:{opacity:0,y:10,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:10,scale:.95},className:`absolute ${e?"left-0":"right-0"} bottom-full mb-2 w-48 bg-[#1a1a1a] border border-white/10 rounded-xl shadow-2xl z-[9999] overflow-y-auto max-h-[280px] scrollbar-thin scrollbar-thumb-white/10`,children:f.jsx("div",{className:"py-1",children:zh.map(u=>f.jsxs("button",{onClick:()=>l(u.code),className:"flex items-center justify-between w-full px-4 py-2.5 text-xs text-left hover:bg-white/5 transition-colors",children:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("span",{children:u.flag}),f.jsx("span",{className:u.code===n.language?"text-primary font-bold":"text-fg/70",children:u.label})]}),u.code===n.language&&f.jsx(Ns,{size:14,className:"text-primary"})]},u.code))})})})]})}class kz{audioContext=null;enabled=!0;constructor(){}getAudioContext(){return this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),this.audioContext}setEnabled(n){this.enabled=n}isEnabled(){return this.enabled}playTone(n,r,s=.3){if(this.enabled)try{const i=this.getAudioContext(),a=i.createOscillator(),l=i.createGain();a.connect(l),l.connect(i.destination),a.frequency.value=n,a.type="sine",l.gain.setValueAtTime(s,i.currentTime),l.gain.exponentialRampToValueAtTime(.01,i.currentTime+r),a.start(i.currentTime),a.stop(i.currentTime+r)}catch(i){console.warn("[Sound] Failed to play tone:",i)}}playSequence(n,r=.3){if(!this.enabled)return;let s=0;n.forEach(i=>{setTimeout(()=>{this.playTone(i.freq,i.duration,r)},s),s+=i.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 Fo=new kz;function Sz(){const{t:e}=rt(),[n,r]=O.useState([]),[s,i]=O.useState([]),[a,l]=O.useState("discovery"),[u,h]=O.useState(!1),[p,m]=O.useState(null),[y,x]=O.useState(!0),[w,_]=O.useState(!pv),[k,S]=O.useState(!0),[E,T]=O.useState(!1),[j,P]=O.useState(!1),[A,R]=O.useState(null),[U,V]=O.useState(!1),[H,D]=O.useState(!1),[Q,Y]=O.useState(!1),[he,W]=O.useState(!0),[G,ne]=O.useState(()=>localStorage.getItem("theme")||"dark"),[re,X]=O.useState(null),ce=O.useRef(null);O.useMemo(()=>{const me=s.length;let ye=0,Ne=0,pe=null;for(const bt of s){ye+=bt.score,bt.score>Ne&&(Ne=bt.score);const Qn=new Date(bt.date);(!pe||Qn>new Date(pe.date))&&(pe=bt)}const Ue=me?Math.round(ye/me):0,st=pe?new Date(pe.date):null;return{total:me,average:Ue,top:Ne,latestTimestamp:st,latestTitle:pe?.title??pe?.category??null}},[s]),O.useEffect(()=>{(async()=>{if(!pv){_(!0),x(!1);return}try{const{data:Ne,error:pe}=await ae.from("init_state").select("is_initialized").single();pe?(console.warn("[App] Init check error (might be fresh DB):",pe),pe.code==="42P01"&&S(!1)):S(Ne.is_initialized>0);const{data:{session:Ue}}=await ae.auth.getSession();m(Ue?.user??null)}catch(Ne){console.error("[App] Status check failed:",Ne)}finally{x(!1)}})();const{data:{subscription:ye}}=ae.auth.onAuthStateChange((Ne,pe)=>{m(pe?.user??null)});return()=>ye.unsubscribe()},[]),O.useEffect(()=>{document.documentElement.setAttribute("data-theme",G),localStorage.setItem("theme",G)},[G]);const[N,M]=O.useState({});O.useEffect(()=>{(async()=>{if(!p)return;const{data:ye}=await ae.from("alchemy_settings").select("sync_start_date, last_sync_checkpoint").eq("user_id",p.id).maybeSingle();ye&&M(ye)})()},[p,U]),O.useEffect(()=>{if(!p)return;(async()=>{const{data:Ne}=await ae.from("alchemy_settings").select("sound_enabled").eq("user_id",p.id).maybeSingle();if(Ne){const pe=Ne.sound_enabled??!0;W(pe),Fo.setEnabled(pe)}})();const ye=ae.channel("processing_events").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events",filter:`user_id=eq.${p.id}`},Ne=>{const pe=Ne.new;pe.agent_state==="Mining"&&!H&&(D(!0),Y(!0),he&&Fo.syncStart()),pe.agent_state==="Signal"&&he&&Fo.signalFound(),pe.agent_state==="Completed"&&(D(!1),he&&(pe.metadata?.errors>0?Fo.error():Fo.syncComplete()),setTimeout(()=>{Y(!1)},5e3),J())}).subscribe();return()=>{ae.removeChannel(ye)}},[p,H,he]),O.useEffect(()=>{const me=new EventSource("/events");return me.onmessage=ye=>{const Ne=JSON.parse(ye.data);Ne.type==="history"?r(pe=>[...Ne.data,...pe].slice(0,100)):r(pe=>[Ne,...pe].slice(0,100))},J(),()=>me.close()},[p]),O.useEffect(()=>{ce.current&&ce.current.scrollIntoView({behavior:"smooth"})},[n]);const J=async()=>{try{if(p){const{data:ye,error:Ne}=await ae.from("signals").select("*").order("created_at",{ascending:!1});if(!Ne&&ye){i(ye.map(pe=>({id:pe.id,title:pe.title,score:pe.score,summary:pe.summary,date:pe.created_at,category:pe.category,entities:pe.entities})));return}}const me=await Ze.get("/api/signals");i(me.data)}catch(me){console.error("Failed to fetch signals",me)}},L=async()=>{h(!0);try{await Ze.post("/api/mine"),J()}catch(me){console.error("Mining failed:",me)}finally{h(!1)}},we=(me,ye)=>{me==="logs"?(X(ye),l("logs")):l(me)};return y?f.jsx("div",{className:"flex items-center justify-center h-screen bg-bg",children:f.jsx("div",{className:"w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"})}):w?f.jsx($_,{onComplete:()=>_(!1)}):p?f.jsx(mL,{children:f.jsx(vL,{children:f.jsxs("div",{className:"flex h-screen w-screen overflow-hidden bg-bg text-fg",children:[f.jsxs($e.aside,{animate:{width:E?72:240},className:"glass m-4 mr-0 flex flex-col relative",children:[f.jsxs("div",{className:`px-4 py-3 pb-4 flex items-center gap-3 ${E?"justify-center":""}`,children:[f.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:f.jsx(rn,{className:"text-white fill-current",size:24})}),!E&&f.jsx($e.h1,{initial:{opacity:0},animate:{opacity:1},className:"text-xl font-bold tracking-tight",children:"Alchemist"})]}),f.jsxs("nav",{className:"flex-1 flex flex-col gap-1 px-3",children:[f.jsx(xi,{active:a==="discovery",onClick:()=>l("discovery"),icon:f.jsx(Ej,{size:20}),label:e("tabs.discovery"),collapsed:E}),f.jsx(xi,{active:a==="chat",onClick:()=>l("chat"),icon:f.jsx($h,{size:20}),label:e("tabs.chat"),collapsed:E}),f.jsx(xi,{active:a==="transmute",onClick:()=>l("transmute"),icon:f.jsx(rn,{size:20}),label:e("tabs.transmute"),collapsed:E}),f.jsx(xi,{active:a==="engine",onClick:()=>l("engine"),icon:f.jsx(oc,{size:20}),label:e("common.settings"),collapsed:E}),f.jsx(xi,{active:a==="logs",onClick:()=>l("logs"),icon:f.jsx(ac,{size:20}),label:e("tabs.logs"),collapsed:E}),f.jsx(xi,{active:a==="account",onClick:()=>l("account"),icon:f.jsx(Ac,{size:20}),label:e("common.account"),collapsed:E})]}),f.jsx("div",{className:"px-3 pb-2 border-t border-white/5 pt-4 mt-2 relative z-[100]",children:f.jsx("div",{className:E?"flex justify-center":"px-1",children:f.jsx(_z,{collapsed:E})})}),f.jsx("div",{className:"px-3 pb-2",children:f.jsxs("button",{onClick:()=>ne(G==="dark"?"light":"dark"),className:`w-full flex items-center ${E?"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:E?e(G==="dark"?"shell.switch_light":"shell.switch_dark"):"",children:[f.jsx("div",{className:"min-w-[20px] flex justify-center",children:G==="dark"?f.jsx(Fj,{size:18}):f.jsx(Rj,{size:18})}),!E&&f.jsx($e.span,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"whitespace-nowrap",children:e(G==="dark"?"common.light_mode":"common.dark_mode")})]})}),f.jsxs("div",{className:"px-3 pb-3",children:[f.jsx("button",{onClick:()=>T(!E),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 ${E?"justify-center":"gap-3"}`,children:E?f.jsx(gj,{size:20}):f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"min-w-[20px] flex justify-center",children:f.jsx(mj,{size:20})}),f.jsx("span",{children:e("common.collapse")})]})}),f.jsxs("button",{onClick:()=>P(!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:e("shell.view_changelog"),children:[!E&&f.jsxs(f.Fragment,{children:[f.jsx(Bh,{size:12,className:"group-hover:text-primary transition-colors"}),f.jsxs("span",{children:["v","1.0.56"]})]}),E&&f.jsx(Bh,{size:14,className:"group-hover:text-primary transition-colors"})]})]})]}),f.jsxs("main",{className:"flex-1 flex flex-col p-4 gap-4 overflow-hidden relative",children:[a==="discovery"&&f.jsxs(f.Fragment,{children:[f.jsxs("header",{className:"flex justify-between items-center px-4 py-2",children:[f.jsxs("div",{children:[f.jsx("h2",{className:"text-2xl font-bold",children:e("tabs.discovery")}),f.jsx("p",{className:"text-sm text-fg/50",children:e("setup.welcome_desc")})]}),f.jsxs("div",{className:"flex gap-2",children:[f.jsxs("button",{onClick:()=>V(!0),className:"px-6 py-3 glass hover:bg-surface transition-colors flex items-center gap-2 text-sm font-medium",children:[f.jsx(oc,{size:16}),f.jsxs("div",{className:"flex flex-col items-start",children:[f.jsx("span",{children:e("discovery.sync_settings")}),f.jsx("span",{className:"text-[10px] text-fg/40 font-mono",children:N.sync_start_date?`${e("discovery.from")}: ${new Date(N.sync_start_date).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:N.last_sync_checkpoint?`${e("discovery.checkpoint")}: ${new Date(N.last_sync_checkpoint).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:e("discovery.all_time")})]})]}),f.jsxs("button",{onClick:L,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-105 active:scale-95 transition-all flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100",children:[f.jsx(Nc,{size:18,className:H?"animate-spin":""}),e(H?"discovery.syncing":"discovery.sync_history")]})]})]}),f.jsx(VL,{onOpenUrl:me=>window.open(me,"_blank","noopener,noreferrer"),onCopyText:me=>{navigator.clipboard.writeText(me)}})]}),a==="chat"&&f.jsx(yz,{}),a==="transmute"&&f.jsx(bz,{}),a==="engine"&&f.jsx(xL,{}),a==="account"&&f.jsx(jL,{}),a==="logs"&&f.jsx(IL,{initialState:re}),f.jsx(bL,{isExpanded:Q,onToggle:()=>Y(!Q),onNavigate:we,liftUp:a==="chat"})]}),f.jsx(NL,{signal:A,onClose:()=>R(null)}),f.jsx(AL,{isOpen:U,onClose:()=>V(!1)}),f.jsx(xz,{isOpen:j,onClose:()=>P(!1)})]})})}):f.jsx(dL,{onAuthSuccess:()=>J(),isInitialized:k})}function xi({active:e,icon:n,label:r,onClick:s,collapsed:i}){return f.jsx("button",{onClick:s,title:i?r:"",className:`w-full flex items-center ${i?"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:i?ta.cloneElement(n,{className:e?"text-primary":""}):f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"min-w-[20px] flex justify-center",children:ta.cloneElement(n,{className:e?"text-primary":""})}),f.jsx($e.span,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"font-semibold text-sm whitespace-nowrap",children:r})]})})}function jz(){Ze.interceptors.request.use(async e=>{try{const{data:{session:n}}=await ae.auth.getSession();n?.access_token&&(e.headers.Authorization=`Bearer ${n.access_token}`);const r=Ps();r&&(e.headers["x-supabase-url"]=r.url,e.headers["x-supabase-key"]=r.anonKey)}catch(n){console.error("[Axios] Error injecting headers:",n)}return e})}const{slice:Ez,forEach:Cz}=[];function Tz(e){return Cz.call(Ez.call(arguments,1),n=>{if(n)for(const r in n)e[r]===void 0&&(e[r]=n[r])}),e}function Nz(e){return typeof e!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(r=>r.test(e))}const iw=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Az=function(e,n){const s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},i=encodeURIComponent(n);let a=`${e}=${i}`;if(s.maxAge>0){const l=s.maxAge-0;if(Number.isNaN(l))throw new Error("maxAge should be a Number");a+=`; Max-Age=${Math.floor(l)}`}if(s.domain){if(!iw.test(s.domain))throw new TypeError("option domain is invalid");a+=`; Domain=${s.domain}`}if(s.path){if(!iw.test(s.path))throw new TypeError("option path is invalid");a+=`; Path=${s.path}`}if(s.expires){if(typeof s.expires.toUTCString!="function")throw new TypeError("option expires is invalid");a+=`; Expires=${s.expires.toUTCString()}`}if(s.httpOnly&&(a+="; HttpOnly"),s.secure&&(a+="; Secure"),s.sameSite)switch(typeof s.sameSite=="string"?s.sameSite.toLowerCase():s.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return s.partitioned&&(a+="; Partitioned"),a},ow={create(e,n,r,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};r&&(i.expires=new Date,i.expires.setTime(i.expires.getTime()+r*60*1e3)),s&&(i.domain=s),document.cookie=Az(e,n,i)},read(e){const n=`${e}=`,r=document.cookie.split(";");for(let s=0;s<r.length;s++){let i=r[s];for(;i.charAt(0)===" ";)i=i.substring(1,i.length);if(i.indexOf(n)===0)return i.substring(n.length,i.length)}return null},remove(e,n){this.create(e,"",-1,n)}};var Rz={name:"cookie",lookup(e){let{lookupCookie:n}=e;if(n&&typeof document<"u")return ow.read(n)||void 0},cacheUserLanguage(e,n){let{lookupCookie:r,cookieMinutes:s,cookieDomain:i,cookieOptions:a}=n;r&&typeof document<"u"&&ow.create(r,e,s,i,a)}},Pz={name:"querystring",lookup(e){let{lookupQuerystring:n}=e,r;if(typeof window<"u"){let{search:s}=window.location;!window.location.search&&window.location.hash?.indexOf("?")>-1&&(s=window.location.hash.substring(window.location.hash.indexOf("?")));const a=s.substring(1).split("&");for(let l=0;l<a.length;l++){const u=a[l].indexOf("=");u>0&&a[l].substring(0,u)===n&&(r=a[l].substring(u+1))}}return r}},Oz={name:"hash",lookup(e){let{lookupHash:n,lookupFromHashIndex:r}=e,s;if(typeof window<"u"){const{hash:i}=window.location;if(i&&i.length>2){const a=i.substring(1);if(n){const l=a.split("&");for(let u=0;u<l.length;u++){const h=l[u].indexOf("=");h>0&&l[u].substring(0,h)===n&&(s=l[u].substring(h+1))}}if(s)return s;if(!s&&r>-1){const l=i.match(/\/([a-zA-Z-]*)/g);return Array.isArray(l)?l[typeof r=="number"?r:0]?.replace("/",""):void 0}}}return s}};let vi=null;const aw=()=>{if(vi!==null)return vi;try{if(vi=typeof window<"u"&&window.localStorage!==null,!vi)return!1;const e="i18next.translate.boo";window.localStorage.setItem(e,"foo"),window.localStorage.removeItem(e)}catch{vi=!1}return vi};var Lz={name:"localStorage",lookup(e){let{lookupLocalStorage:n}=e;if(n&&aw())return window.localStorage.getItem(n)||void 0},cacheUserLanguage(e,n){let{lookupLocalStorage:r}=n;r&&aw()&&window.localStorage.setItem(r,e)}};let wi=null;const lw=()=>{if(wi!==null)return wi;try{if(wi=typeof window<"u"&&window.sessionStorage!==null,!wi)return!1;const e="i18next.translate.boo";window.sessionStorage.setItem(e,"foo"),window.sessionStorage.removeItem(e)}catch{wi=!1}return wi};var Iz={name:"sessionStorage",lookup(e){let{lookupSessionStorage:n}=e;if(n&&lw())return window.sessionStorage.getItem(n)||void 0},cacheUserLanguage(e,n){let{lookupSessionStorage:r}=n;r&&lw()&&window.sessionStorage.setItem(r,e)}},Dz={name:"navigator",lookup(e){const n=[];if(typeof navigator<"u"){const{languages:r,userLanguage:s,language:i}=navigator;if(r)for(let a=0;a<r.length;a++)n.push(r[a]);s&&n.push(s),i&&n.push(i)}return n.length>0?n:void 0}},Mz={name:"htmlTag",lookup(e){let{htmlTag:n}=e,r;const s=n||(typeof document<"u"?document.documentElement:null);return s&&typeof s.getAttribute=="function"&&(r=s.getAttribute("lang")),r}},zz={name:"path",lookup(e){let{lookupFromPathIndex:n}=e;if(typeof window>"u")return;const r=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(r)?r[typeof n=="number"?n:0]?.replace("/",""):void 0}},Fz={name:"subdomain",lookup(e){let{lookupFromSubdomainIndex:n}=e;const r=typeof n=="number"?n+1:1,s=typeof window<"u"&&window.location?.hostname?.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);if(s)return s[r]}};let Yk=!1;try{document.cookie,Yk=!0}catch{}const Qk=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];Yk||Qk.splice(1,1);const $z=()=>({order:Qk,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:e=>e});class Zk{constructor(n){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(n,r)}init(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=n,this.options=Tz(r,this.options||{},$z()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=i=>i.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=s,this.addDetector(Rz),this.addDetector(Pz),this.addDetector(Lz),this.addDetector(Iz),this.addDetector(Dz),this.addDetector(Mz),this.addDetector(zz),this.addDetector(Fz),this.addDetector(Oz)}addDetector(n){return this.detectors[n.name]=n,this}detect(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,r=[];return n.forEach(s=>{if(this.detectors[s]){let i=this.detectors[s].lookup(this.options);i&&typeof i=="string"&&(i=[i]),i&&(r=r.concat(i))}}),r=r.filter(s=>s!=null&&!Nz(s)).map(s=>this.options.convertDetectedLanguage(s)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?r:r.length>0?r[0]:null}cacheUserLanguage(n){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;r&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(n)>-1||r.forEach(s=>{this.detectors[s]&&this.detectors[s].cacheUserLanguage(n,this.options)}))}}Zk.type="languageDetector";const Uz={save:"Save",cancel:"Cancel",loading:"Loading...",error:"Error",success:"Success",settings:"Settings",search:"Search",back:"Back",all:"All",delete:"Delete",update:"Update",edit:"Edit",close:"Close",complete:"Complete",skip:"Skip",begin:"Begin",connection:"Connection",setup:"Setup",project:"Project",account:"Account",logout:"Logout",welcome:"Welcome",dark_mode:"Dark Mode",light_mode:"Light Mode",collapse:"Collapse",just_now:"Just now",enabled:"Enabled",disabled:"Disabled",quick:"Quick (5)",balanced:"Balanced (50)",thorough:"Thorough (200)",resetting:"Resetting...",saving:"Saving...",locale_code:"en-US",categories:{ai_ml:"AI & ML",business:"Business",politics:"Politics",technology:"Technology",finance:"Finance",crypto:"Crypto",science:"Science",other:"Other"}},Bz={discovery:"Discovery",chat:"Chat",transmute:"Transmute",logs:"System Logs",history:"History"},Vz={welcome_title:"Assemble Your Engine",welcome_desc:"Alchemy requires a Supabase essence to store signal fragments and intelligence patterns.",requirements:"Requirements:",project_url:"Supabase Project URL",anon_key:"Anon Public API Key",db_password:"Database Password",begin_init:"BEGIN INITIALIZATION",connect_essence:"CONNECT ESSENCE",validating:"Validating Link",resonance:"Synchronizing Resonance...",init_schema:"Initialize Schema",schema_desc:"Run database migrations to set up required tables and functions.",project_id:"Project ID",access_token:"Access Token",run_migrations:"RUN MIGRATIONS",running_migrations:"Running Migrations",take_minute:"This may take a minute...",engine_aligned:"Engine Aligned",restarting:"Restarting Alchemist Subsystems..."},qz={filters:"Filters",category:"Category",intelligence_score:"Intelligence Score",no_signals_in_category:"No signals in {{category}} yet.",no_categories:"No categories yet.",discovery_hint:"Signals will be organized here once discovered.",loading_signals:"Loading signals...",dismiss_hint:"Dismiss (Not Interested)",signal_count_one:"{{count}} signal",signal_count_other:"{{count}} signals",time_min_ago:"{{count}}m ago",time_hour_ago:"{{count}}h ago",time_day_ago:"{{count}}d ago",add_note_title:"Add Note",target:"Target",note_placeholder:"Enter your thoughts, ideas, or action items regarding this signal...",save_note:"Save Note",view_all_sources:"View all sources",source_count_one:"{{count}} source",source_count_other:"{{count}} sources",source_found_in:"Found in {{count}} different sources",high_confidence:"High confidence - found in {{count}} sources",new_signals:"New Signals",smart_summary:"Smart Summary",entities:"Entities",sources:"Sources",last_sync:"Last Sync",syncnow:"Sync Now",all_time:"All time",checkpoint:"Checkpoint",from:"From",score_high:"HIGH",score_medium:"MEDIUM",score_low:"LOW",sources_count:"{{count}} sources",open_source:"Open",add_note:"Note",boost_topic:"Boost Topic",boosted:"Boosted",dismissed:"Dismissed",remove_favourite:"Remove from favourites",add_favourite:"Add to favourites",sync_history:"Sync History",syncing:"Syncing...",sync_settings:"Sync Settings",discovered:"Discovered",original_source:"Original Source",ai_summary:"AI Summary",full_content:"Full Content",copied:"Copied!",open_link:"Open",detail_title:"Signal Details",sync_from:"Sync From (Optional)",urls_per_sync:"URLs per Sync",sync_from_hint:"Leave empty to sync only new URLs since last sync (incremental). Set a date to process URLs from that point forward.",reset_checkpoint:"Reset Checkpoint",reset_checkpoint_hint:'Clear the sync checkpoint to force a full re-sync from your "Sync From" date',sync_info:'The Alchemist tracks your progress automatically. Use "Sync From" to backfill history or "Reset Checkpoint" to start fresh.',save_settings:"Save Settings",sync_saved:"Sync settings saved successfully",checkpoint_reset:"Checkpoint reset successfully",login_to_save:"Please log in to save settings",login_to_reset:"Please log in to reset checkpoint",status_updated:"Engine status updated to {{status}}",asset_ready:'Asset "{{title}}" is ready!',scanning:"Scanning for new categories and topics...",discovery_complete:"Engine discovery complete!",discovery_failed:"Discovery failed. Check settings.",load_failed:"Failed to load engines",starting_run:"Starting engine run...",run_complete:"Engine run complete! Created: {{title}}",run_started_desktop:"Engine run started on Desktop. Tracking as: {{id}}",run_failed:"Failed to run engine",brief_failed:"Failed to generate production brief",copied_json:"JSON copied to clipboard",json_footer:"This JSON contains the full context (Signals + User Persona) required for the Desktop Studio.",topic:"Topic",pipeline:"Pipeline"},Hz={history:"History",ask_anything:"Ask anything about your browsing history...",sources:"Sources",processing:"Processing your query...",new_chat:"New Chat",no_messages:"No messages yet. Start a conversation!",no_history:"No chat history yet.",title:"Ask Alchemist",desc:"I can help you recall information, summarize topics, and find insights from your browsing history.",thinking:"Exploring memory...",placeholder:"Ask about your history...",error_message:"Sorry, I encountered an error processing your request.",relevant_context:"Relevant Context",match_score:"{{score}}% Match",rag_attribution:"Alchemist used these {{count}} signals to answer",suggestions:{react:"What have I read about React recently?",ai:"Summarize the latest AI news I visited.",finance:"Do I have any notes on Finance?",performance:"Find articles about 'Performance'"}},Kz={engines:"Alchemist Engines",assets:"Generated Assets",newsletter:"Newsletter",thread:"Thread",audio:"Audio",report:"Report",title:"Transmute Engine",desc:"Active Generation Pipelines & Assets",generate:"Generate",processing_desktop:"Processing on Desktop...",ensure_defaults:"Ensure Default Engines",create_engine:"Create Engine",no_assets:"No assets generated yet.",generate_engines:"Generate Engines",new_engine:"New Engine",no_engines:"No Engines Configured",no_engines_desc:"Create your first pipeline to automatically turn signals into newsletters, threads, or audio briefs.",run_engine:"Run Engine",running:"Running...",last_run:"Last Run",never:"Never",schedule:"Schedule",manual:"Manual",topic:"Topic",pipeline:"Pipeline",pause:"Pause",resume:"Resume",view_json:"View Production Brief JSON",json_contract:"Stateless & Self-Contained Contract",json_desc:"This JSON contains the full context (Signals + User Persona) required for the Desktop Studio.",generating_asset:"Generating Asset...",queued_desktop:"Queued for Desktop...",desktop_processing:"The RealTimeX Desktop app is processing this request. This modal will update automatically once finished.",unsupported_type:"Unsupported asset type",edit_engine:"Edit Engine",engine_name:"Engine Name",type:"Type",status:"Status",execution_env:"Execution Environment",local_llm:"Local (Alchemy LLM)",desktop_swarm:"RealTimeX Desktop (Agent Swarm)",env_desc_desktop:"Delegates heavy tasks like Audio/Video to the desktop app.",env_desc_local:"Runs simple Markdown tasks directly in Alchemy.",min_score:"Min Score",max_signals:"Max Signals",category_filter:"Category Filter (multi-select)",multi_select_hint:"Hold Cmd/Ctrl to select multiple categories",schedule_hint:"Note: Scheduling is not yet automated",prompt_override:"Custom Prompt Override (optional)",prompt_placeholder:"Override the default prompt for this engine type...",delete_confirm:"Really delete?",confirm:"Confirm"},Wz={title:"Account Configuration",desc:"Manage your Alchemist profile and essence links.",profile:"Profile",security:"Security",supabase:"Supabase",first_name:"First Name",last_name:"Last Name",email_locked:"Email Address (Locked)",sound_effects:"Sound Effects",sound_desc:"Enable audio feedback for sync events and signal discoveries.",sign_out:"Sign Out",logout_desc:"End your current session and return to the login screen.",preserve_profile:"Preserve Profile",security_title:"Update Entropy Key",new_password:"New Password",confirm_password:"Confirm Password",password_mismatch:"Complexity keys do not match.",password_too_short:"Entropy too low. Minimum 8 characters.",password_rotate_success:"Key rotation successful.",rotate_key:"Rotate Key",essence_resonance:"Essence Resonance",byok_desc:"Bring Your Own Keys (BYOK) for intelligence persistence.",established_link:"Established Link",env_notice:"Active from environment variables. UI override enabled.",realign_link:"Realign Link",sever_link:"Sever Link",sever_confirm:"Sever connection to this essence? This will reset local resonance.",anon_secret_fragment:"Anon Secret Fragment",no_resonance:"No Essence Resonance",no_resonance_desc:"The Alchemist requires a cloud core to store intelligence fragments.",initiate_link:"Initiate Link",test_connection:"Test Connection"},Gz={title:"System Logs",desc:"Detailed history of sync runs, sources, and URL processing",blacklist_suggestion:"Potential Blacklist",blacklist_desc:"Candidates for blocking",recent_errors:"Recent Errors",errors_desc:"Failed URL processes",total_signals:"Total Signals",signals_desc:"Successfully mined",blacklist_modal_title:"Blacklist Suggestions",blacklist_modal_desc:"Review domains suggested for blacklisting based on low scores.",no_suggestions:"No suggestions right now",quality_good:"Your signal quality looks good!",signals_count:"{{count}} signals",avg_score:"Avg Score: {{score}}",low_quality:"Consistently Low Quality",repetitive:"Repetitive Pattern",blacklist_domain:"Blacklist Domain",errors_modal_title:"Recent Errors",errors_modal_desc:"Log of recent failures and issues.",no_recent_errors:"No recent errors found.",signals_modal_title:"Found Signals",signals_modal_desc:"Browse and manage your mined signals history.",search_placeholder:"Search signals...",any_score:"Any Score",high_score:"High (80%+)",medium_score:"Medium (50-79%)",low_score:"Low (<50%)",all_categories:"All Categories",page_x:"Page {{page}}"},Jz={title:"Alchemist Engine",live:"LIVE",clear:"Clear",idle:"Idle. Awaiting signal mining events...",run_completed:"Mining Run Completed",signals:"Signals",urls:"URLs",skipped:"Skipped",failed_to_process:"{{count}} URLs failed to process",view_logs:"View Logs",hide_details:"Hide Details",view_details:"View Details",engine_log:"Live Engine Log",state_reading:"Reading",state_thinking:"Thinking",state_signal:"Signal",state_skipped:"Skipped",state_error:"Error",state_completed:"Completed",msg_reading:"Reading content from: {{url}}",msg_thinking:"Analyzing relevance of: {{title}}",msg_found_signal:"Found signal: {{summary}} ({{score}}%)",msg_low_signal:"Low signal stored for review ({{score}}%): {{title}}",msg_failed:"Analysis failed for {{title}}: {{error}}",msg_sync_completed:"Sync completed: {{signals}} signals found, {{skipped}} skipped, {{errors}} errors"},Xz={switch_light:"Switch to Light Mode",switch_dark:"Switch to Dark Mode",view_changelog:"View Changelog",release_notes:"Release Notes",changelog_error:"Failed to load changelog."},Yz={title:"Signal Pulse",mining:"Mining",standing_by:"Standing by",idle:"Idle",tracked:"Signals tracked",avg_score:"Average score",top_signal:"Top signal",latest:"Latest",awaiting:"Awaiting mining",no_signals:"No signals yet"},Qz={title:"Intelligence Engine",subtitle:"Fine-tune the Alchemist's cognitive parameters and provider links.",configuration:"AI Configuration",test_connection:"Test Connection",save_config:"Save Configuration",llm_provider:"LLM Provider",embedding_provider:"Embedding Provider",sdk_connected:"SDK Connected",sdk_not_available:"SDK Not Available",provider:"Provider",intelligence_model:"Intelligence Model",embedding_model:"Embedding Model",loading_providers:"Loading providers...",sdk_info_success:"✓ Using RealTimeX configured provider",sdk_info_fail:"⚠️ RealTimeX SDK not detected. Configure in RealTimeX Desktop.",embedding_info_success:"✓ Embeddings are generated using your RealTimeX configured provider",embedding_info_fail:"⚠️ RealTimeX SDK not detected. Configure providers in RealTimeX Desktop.",persona_title:"Persona Memory",save_memory:"Save Memory",interests_title:"Active Interests",interests_priority:"High Priority",interests_desc:"The Alchemist prioritizes content matching these topics. Updated automatically based on Favorites & Boosts.",interests_placeholder:"e.g. User focuses on React performance, Rust backend systems, and AI Agent architecture...",antipatterns_title:"Anti-Patterns",antipatterns_priority:"Avoid",antipatterns_desc:"The Alchemist filters out or scores down content matching these patterns. Updated via Dismissals.",antipatterns_placeholder:"e.g. Dislikes marketing fluff, generic listicles, and crypto hype...",browser_sources:"Browser History Sources",save_browser:"Save Browser Sources",blacklist_title:"Blacklist Domains",blacklist_desc:"URLs containing these patterns will be skipped during mining. Enter one pattern per line.",blacklist_label:"Domain Patterns (one per line)",blacklist_placeholder:`google.com/search
|
|
134
|
+
${r("shell.changelog_error")}`)}finally{l(!1)}};return f.jsx(Ot,{children:e&&f.jsxs(f.Fragment,{children:[f.jsx($e.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:n,className:"fixed inset-0 bg-black/60 backdrop-blur-sm z-50"}),f.jsx($e.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:f.jsxs("div",{className:"glass w-full max-w-3xl max-h-[80vh] overflow-hidden pointer-events-auto shadow-2xl",children:[f.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx(uw,{size:24,className:"text-primary"}),f.jsx("h2",{className:"text-xl font-bold",children:r("shell.release_notes")})]}),f.jsx("button",{onClick:n,className:"p-2 hover:bg-surface rounded-lg transition-colors",children:f.jsx(Tn,{size:20,className:"text-fg/60"})})]}),f.jsx("div",{className:"p-6 overflow-y-auto custom-scrollbar max-h-[calc(80vh-88px)]",children:a?f.jsx("div",{className:"flex items-center justify-center py-12",children:f.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-primary border-t-transparent"})}):f.jsx(Wp,{components:{h1:({children:h})=>f.jsx("h1",{className:"text-2xl font-bold text-fg mb-6 mt-0",children:h}),h2:({children:h})=>f.jsx("h2",{className:"text-xl font-bold text-fg mt-8 mb-3 pb-2 border-b border-border first:mt-0",children:h}),h3:({children:h})=>f.jsx("h3",{className:"text-lg font-bold text-primary mt-6 mb-2",children:h}),p:({children:h})=>f.jsx("p",{className:"text-sm text-fg/70 mb-3 leading-relaxed",children:h}),ul:({children:h})=>f.jsx("ul",{className:"list-none space-y-1 mb-4 ml-0",children:h}),li:({children:h})=>f.jsx("li",{className:"text-sm text-fg/80 ml-4 mb-1 before:content-['•'] before:mr-2 before:text-primary",children:h}),a:({href:h,children:p})=>f.jsx("a",{href:h,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:text-primary/80 underline transition-colors",children:p}),code:({children:h})=>f.jsx("code",{className:"bg-surface/50 text-accent px-1.5 py-0.5 rounded text-xs font-mono border border-border",children:h}),strong:({children:h})=>f.jsx("strong",{className:"font-bold text-fg",children:h})},children:s})})]})})]})})}function vz({asset:e,onClose:n}){const{t:r}=rt(),s=()=>{e.content&&navigator.clipboard.writeText(e.content)},i=()=>{if(!e.content)return;const a=new Blob([e.content],{type:"text/markdown"}),l=URL.createObjectURL(a),u=document.createElement("a");u.href=l,u.download=`${e.title.replace(/[^a-z0-9]/gi,"_").toLowerCase()}.md`,document.body.appendChild(u),u.click(),document.body.removeChild(u),URL.revokeObjectURL(l)};return f.jsx(Ot,{children:e&&f.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:f.jsxs($e.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:[f.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:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.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"?f.jsx(Uh,{className:"w-5 h-5"}):f.jsx(Li,{className:"w-5 h-5"})}),f.jsxs("div",{children:[f.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e.title}),f.jsxs("p",{className:"text-xs text-gray-500",children:[new Date(e.created_at).toLocaleString()," • ",r("discovery.sources_count",{count:e.metadata?.source_signal_count||0})]})]})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{onClick:s,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:f.jsx(Df,{className:"w-4 h-4"})}),f.jsx("button",{onClick:i,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:f.jsx(Fh,{className:"w-4 h-4"})}),f.jsx("div",{className:"w-px h-6 bg-gray-200 dark:bg-gray-700 mx-1"}),f.jsx("button",{onClick:n,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:f.jsx(Tn,{className:"w-5 h-5"})})]})]}),f.jsx("div",{className:"flex-1 overflow-y-auto p-6 bg-white dark:bg-gray-950",children:e.status&&e.status!=="completed"?f.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-4",children:[f.jsx(Pt,{className:"w-12 h-12 animate-spin text-purple-500"}),f.jsxs("div",{className:"text-center",children:[f.jsx("h4",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:e.status==="processing"?r("transmute.generating_asset"):r("transmute.queued_desktop")}),f.jsx("p",{className:"text-sm text-gray-500 max-w-xs mt-1",children:r("transmute.desktop_processing")})]})]}):e.type==="markdown"?f.jsx("div",{className:"prose dark:prose-invert max-w-none",children:f.jsx(Wp,{children:e.content||""})}):e.type==="audio"?f.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-4",children:[f.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:f.jsx(Uh,{className:"w-8 h-8 text-purple-600 dark:text-purple-400"})}),f.jsx("p",{className:"text-gray-500",children:r("transmute.unsupported_type")}),f.jsxs("audio",{controls:!0,className:"w-full max-w-md mt-4",children:[f.jsx("source",{src:e.content||"",type:"audio/mpeg"}),"Your browser does not support the audio element."]})]}):f.jsx("div",{className:"text-gray-500 text-center py-10",children:"Unsupported asset type"})})]})})})}function sw({engine:e,onClose:n,onSave:r,onDelete:s}){const{t:i}=rt(),{showToast:a}=Wc(),[l,u]=O.useState({title:"",type:"newsletter",status:"active",config:{schedule:"",min_score:70,categories:[],custom_prompt:"",max_signals:10,execution_mode:"local"}}),[h,p]=O.useState(!1);O.useEffect(()=>{e&&u({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 m=async()=>{try{const w={title:l.title,type:l.type,status:l.status,config:{schedule:l.config.schedule,filters:{min_score:l.config.min_score,category:l.config.category},custom_prompt:l.config.custom_prompt,max_signals:l.config.max_signals,execution_mode:l.config.execution_mode}};if(e){const{data:_,error:k}=await ae.from("engines").update(w).eq("id",e.id).select().single();if(k)throw k;r(_),a("Engine updated successfully","success")}else{const{data:{user:_}}=await ae.auth.getUser();if(!_)throw new Error("Not authenticated");const{data:k,error:S}=await ae.from("engines").insert({...w,user_id:_.id}).select().single();if(S)throw S;r(k),a("Engine created successfully","success")}n()}catch(w){console.error("Save error:",w),a(w.message||"Failed to save engine","error")}},y=async()=>{if(!(!e||!s))try{const{error:w}=await ae.from("engines").delete().eq("id",e.id);if(w)throw w;s(e.id),a("Engine deleted","success"),n()}catch(w){a(w.message||"Failed to delete engine","error")}},x=()=>{p(!1),n()};return!e&&!n?null:f.jsx(Ot,{children:f.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:f.jsxs($e.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:[f.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800",children:[f.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:i(e?"transmute.edit_engine":"transmute.create_engine")}),f.jsx("button",{onClick:x,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:f.jsx(Tn,{className:"w-5 h-5"})})]}),f.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6",children:[f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:i("transmute.engine_name")}),f.jsx("input",{type:"text",value:l.title,onChange:w=>u({...l,title:w.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"})]}),f.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:i("transmute.type")}),f.jsxs("select",{value:l.type,onChange:w=>u({...l,type:w.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:[f.jsx("option",{value:"newsletter",children:i("transmute.newsletter")}),f.jsx("option",{value:"thread",children:i("transmute.thread")}),f.jsx("option",{value:"audio",children:"Audio Brief"}),f.jsx("option",{value:"report",children:"Report"})]})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:i("transmute.status")}),f.jsxs("select",{value:l.status,onChange:w=>u({...l,status:w.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:[f.jsx("option",{value:"active",children:i("common.status_active")}),f.jsx("option",{value:"paused",children:i("common.status_paused")}),f.jsx("option",{value:"draft",children:"Draft"})]})]})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:i("transmute.execution_env")}),f.jsxs("select",{value:l.config.execution_mode,onChange:w=>u({...l,config:{...l.config,execution_mode:w.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:[f.jsx("option",{value:"local",children:i("transmute.local_llm")}),f.jsx("option",{value:"desktop",children:i("transmute.desktop_swarm")})]}),f.jsx("p",{className:"text-[10px] text-gray-500 mt-1",children:l.config.execution_mode==="desktop"?i("transmute.env_desc_desktop"):i("transmute.env_desc_local")})]})]}),f.jsxs("div",{className:"space-y-4",children:[f.jsx("h4",{className:"font-medium text-gray-900 dark:text-gray-100",children:"Signal Filters"}),f.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:i("transmute.min_score")}),f.jsx("input",{type:"number",min:"0",max:"100",value:l.config.min_score,onChange:w=>u({...l,config:{...l.config,min_score:parseInt(w.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"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:i("transmute.max_signals")}),f.jsx("input",{type:"number",min:"1",max:"50",value:l.config.max_signals,onChange:w=>u({...l,config:{...l.config,max_signals:parseInt(w.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"})]})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:i("transmute.category_filter")}),f.jsxs("select",{multiple:!0,value:l.config.categories,onChange:w=>{const _=Array.from(w.target.selectedOptions,k=>k.value);u({...l,config:{...l.config,categories:_}})},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:[f.jsx("option",{value:"AI & ML",children:"AI & ML"}),f.jsx("option",{value:"Technology",children:"Technology"}),f.jsx("option",{value:"Business",children:"Business"}),f.jsx("option",{value:"Finance",children:"Finance"}),f.jsx("option",{value:"Science",children:"Science"}),f.jsx("option",{value:"Politics",children:"Politics"})]}),f.jsx("p",{className:"text-xs text-gray-500 mt-1",children:i("transmute.multi_select_hint")})]})]}),f.jsxs("div",{children:[f.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:[i("transmute.schedule")," (",i("common.optional"),")"]}),f.jsx("input",{type:"text",value:l.config.schedule,onChange:w=>u({...l,config:{...l.config,schedule:w.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"}),f.jsx("p",{className:"text-xs text-gray-500 mt-1",children:i("transmute.schedule_hint")})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:i("transmute.prompt_override")}),f.jsx("textarea",{value:l.config.custom_prompt,onChange:w=>u({...l,config:{...l.config,custom_prompt:w.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:i("transmute.prompt_placeholder")})]})]}),f.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&&s?h?f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("span",{className:"text-sm text-red-600 font-medium",children:i("transmute.delete_confirm")}),f.jsx("button",{onClick:y,className:"px-3 py-1.5 bg-red-600 text-white text-xs rounded-lg hover:bg-red-700 transition-colors",children:i("transmute.confirm")}),f.jsx("button",{onClick:()=>p(!1),className:"px-3 py-1.5 text-gray-500 hover:text-gray-700 text-xs rounded-lg",children:i("common.cancel")})]}):f.jsxs("button",{onClick:()=>p(!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:[f.jsx(Ff,{className:"w-4 h-4"}),i("common.delete")]}):f.jsx("div",{}),f.jsxs("div",{className:"flex gap-2",children:[f.jsx("button",{onClick:x,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"}),f.jsxs("button",{onClick:m,className:"flex items-center gap-2 px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors",children:[f.jsx(br,{className:"w-4 h-4"}),"Save"]})]})]})]})})})}const wz=({engine:e,onRun:n,onEdit:r,onToggle:s,onViewBrief:i,isLoading:a})=>{const{t:l}=rt(),u=!!e.config.tag,h={newsletter:u?f.jsx(Mf,{className:"w-5 h-5 text-blue-500"}):f.jsx(Li,{className:"w-5 h-5 text-emerald-500"}),thread:f.jsx(rn,{className:"w-5 h-5 text-blue-500"}),audio:f.jsx(Uh,{className:"w-5 h-5 text-purple-500"}),report:f.jsx(oc,{className:"w-5 h-5 text-orange-500"})};return f.jsxs($e.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:[f.jsxs("div",{className:"flex justify-between items-start mb-4",children:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("div",{className:"p-2 rounded-xl bg-gray-100 dark:bg-gray-800",children:h[e.type]||f.jsx(Li,{className:"w-5 h-5"})}),f.jsxs("div",{children:[f.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e.title}),f.jsxs("p",{className:"text-xs text-gray-500 capitalize",children:[u?l("transmute.topic"):l(`transmute.${e.type}`,e.type)," ",l("transmute.pipeline")]})]})]}),f.jsxs("div",{className:"flex gap-1",children:[f.jsx("button",{onClick:()=>s(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"?f.jsx(Pj,{className:"w-4 h-4"}):f.jsx(Wy,{className:"w-4 h-4"})}),f.jsx("button",{onClick:()=>i(e.id),title:l("transmute.view_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:f.jsx(fw,{className:"w-4 h-4"})}),f.jsx("button",{onClick:()=>r(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:f.jsx(oc,{className:"w-4 h-4"})})]})]}),f.jsxs("div",{className:"space-y-2 mb-4",children:[f.jsxs("div",{className:"text-xs text-gray-500 flex justify-between",children:[f.jsx("span",{children:l("transmute.last_run")}),f.jsx("span",{children:e.last_run_at?new Date(e.last_run_at).toLocaleDateString(l("common.locale_code")):l("transmute.never")})]}),f.jsxs("div",{className:"text-xs text-gray-500 flex justify-between",children:[f.jsx("span",{children:l("transmute.schedule")}),f.jsx("span",{children:e.config.schedule||l("transmute.manual")})]})]}),f.jsxs("button",{onClick:()=>n(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?f.jsx(Pt,{className:"w-4 h-4 animate-spin"}):f.jsx(Wy,{className:"w-4 h-4"}),l(a?"transmute.running":"transmute.run_engine")]})]})};function bz(){const{t:e}=rt(),[n,r]=O.useState([]),[s,i]=O.useState(!0),[a,l]=O.useState(new Set),[u,h]=O.useState(null),[p,m]=O.useState(null),[y,x]=O.useState(!1),[w,_]=O.useState(null),[k,S]=O.useState(!1),[E,T]=O.useState(!1),{showToast:j}=Wc();O.useEffect(()=>{(async()=>A())();const G=ae.channel("asset-updates").on("postgres_changes",{event:"UPDATE",schema:"public",table:"assets"},ne=>{const re=ne.new;h(X=>X?.id===re.id?re:X),re.status==="completed"&&ne.old.status!=="completed"&&j(e("transmute.asset_ready",{title:re.title}),"success")}).subscribe();return()=>{ae.removeChannel(G)}},[]);const P=async()=>{if(!E)try{T(!0),j(e("transmute.scanning"),"info");const{data:{session:W}}=await ae.auth.getSession(),G=Ps(),ne={"Content-Type":"application/json","x-user-id":W?.user?.id||""};if(W?.access_token&&(ne.Authorization=`Bearer ${W.access_token}`),G&&(ne["x-supabase-url"]=G.url,ne["x-supabase-key"]=G.anonKey),!(await fetch("/api/engines/ensure-defaults",{method:"POST",headers:ne})).ok)throw new Error("Failed to generate engines");j(e("transmute.discovery_complete"),"success"),await A()}catch(W){console.error("Failed to generate engines:",W),j(e("transmute.discovery_failed"),"error")}finally{T(!1)}},A=async()=>{try{i(!0);const{data:{user:W}}=await ae.auth.getUser();if(!W)return;const{data:G,error:ne}=await ae.from("engines").select("*").eq("user_id",W.id).order("created_at",{ascending:!1});if(ne)throw ne;r(G)}catch(W){console.error("Error fetching engines:",W),j(e("transmute.load_failed"),"error")}finally{i(!1)}},R=async W=>{if(!a.has(W))try{l(M=>new Set(M).add(W)),j(e("transmute.starting_run"),"info");const{data:{session:G}}=await ae.auth.getSession(),ne=G?.access_token,re=Ps(),X={"Content-Type":"application/json","x-user-id":G?.user?.id||""};ne&&(X.Authorization=`Bearer ${ne}`),re&&(X["x-supabase-url"]=re.url,X["x-supabase-key"]=re.anonKey);const ce=await fetch(`/api/engines/${W}/run`,{method:"POST",headers:X});if(!ce.ok){const M=await ce.json();throw new Error(M.error||"Run failed")}const N=await ce.json();N.status==="completed"?j(e("transmute.run_complete",{title:N.title}),"success"):j(e("transmute.run_started_desktop",{id:N.id}),"info"),h(N),r(M=>M.map(J=>J.id===W?{...J,last_run_at:new Date().toISOString()}:J))}catch(G){console.error("Engine run error:",G),j(G.message||e("transmute.run_failed"),"error")}finally{l(G=>{const ne=new Set(G);return ne.delete(W),ne})}},U=async W=>{try{x(!0);const{data:{session:G}}=await ae.auth.getSession(),ne=Ps(),re={"Content-Type":"application/json","x-user-id":G?.user?.id||""};G?.access_token&&(re.Authorization=`Bearer ${G.access_token}`),ne&&(re["x-supabase-url"]=ne.url,re["x-supabase-key"]=ne.anonKey);const X=await fetch(`/api/engines/${W}/brief`,{headers:re});if(!X.ok)throw new Error("Failed to fetch brief");const ce=await X.json();m(ce)}catch{j(e("transmute.brief_failed"),"error")}finally{x(!1)}},V=async(W,G)=>{const ne=G==="active"?"paused":"active";r(re=>re.map(X=>X.id===W?{...X,status:ne}:X));try{const{error:re}=await ae.from("engines").update({status:ne}).eq("id",W);if(re)throw re;j(e("transmute.status_updated",{status:ne}),"success")}catch{r(X=>X.map(ce=>ce.id===W?{...ce,status:G}:ce)),j(e("common.error"),"error")}},H=()=>{S(!0)},D=W=>{const G=n.find(ne=>ne.id===W);G&&_(G)},Q=W=>{r(G=>G.find(re=>re.id===W.id)?G.map(re=>re.id===W.id?W:re):[W,...G])},Y=W=>{r(G=>G.filter(ne=>ne.id!==W))},he=()=>{_(null),S(!1)};return f.jsxs("div",{className:"h-full flex flex-col bg-gray-50/50 dark:bg-[#0A0A0A]",children:[f.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:f.jsxs("div",{className:"flex justify-between items-center max-w-7xl mx-auto w-full",children:[f.jsxs("div",{children:[f.jsx("h2",{className:"text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-purple-500 to-blue-500",children:e("transmute.title")}),f.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:e("transmute.desc")})]}),f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsxs("button",{onClick:P,disabled:E,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:[E?f.jsx(Pt,{className:"w-4 h-4 animate-spin"}):f.jsx(rn,{className:"w-4 h-4"}),e("transmute.generate_engines")]}),f.jsxs("button",{onClick:H,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:[f.jsx(zf,{className:"w-4 h-4"}),e("transmute.new_engine")]})]})]})}),f.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:f.jsx("div",{className:"max-w-7xl mx-auto w-full",children:s?f.jsx("div",{className:"flex items-center justify-center h-64",children:f.jsx(Pt,{className:"w-8 h-8 animate-spin text-purple-500"})}):n.length===0?f.jsxs("div",{className:"flex flex-col items-center justify-center h-96 text-center",children:[f.jsx("div",{className:"w-16 h-16 rounded-2xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-4",children:f.jsx(rn,{className:"w-8 h-8 text-gray-400"})}),f.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:e("transmute.no_engines")}),f.jsx("p",{className:"text-gray-500 max-w-sm mt-2 mb-6",children:e("transmute.no_engines_desc")}),f.jsx("button",{onClick:H,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:e("transmute.create_engine")})]}):f.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:f.jsx(Ot,{children:n.map(W=>f.jsx(wz,{engine:W,onRun:R,onEdit:D,onToggle:V,onViewBrief:U,isLoading:a.has(W.id)},W.id))})})})}),f.jsx(Ot,{children:p&&f.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/60 backdrop-blur-md",children:f.jsxs($e.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:[f.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:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("div",{className:"p-2 rounded-lg bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400",children:f.jsx(fw,{className:"w-5 h-5"})}),f.jsxs("div",{children:[f.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e("transmute.view_json")}),f.jsx("p",{className:"text-xs text-gray-500",children:e("transmute.json_contract")})]})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{onClick:()=>{navigator.clipboard.writeText(JSON.stringify(p,null,2)),j(e("transmute.copied_json"),"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:f.jsx(Df,{className:"w-4 h-4"})}),f.jsx("button",{onClick:()=>m(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:f.jsx(Tn,{className:"w-5 h-5"})})]})]}),f.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-[#0D1117] font-mono text-sm",children:f.jsx("pre",{className:"text-blue-300",children:JSON.stringify(p,null,2)})}),f.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:e("transmute.json_footer")})]})})}),y&&f.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/20 backdrop-blur-sm",children:f.jsx(Pt,{className:"w-10 h-10 animate-spin text-white"})}),f.jsx(vz,{asset:u,onClose:()=>h(null)}),w&&f.jsx(sw,{engine:w,onClose:he,onSave:Q,onDelete:Y}),k&&f.jsx(sw,{engine:null,onClose:he,onSave:Q})]})}const zh=[{code:"en",label:"English",flag:"🇺🇸"},{code:"fr",label:"Français",flag:"🇫🇷"},{code:"es",label:"Español",flag:"🇪🇸"},{code:"ko",label:"한국어",flag:"🇰🇷"},{code:"ja",label:"日本語",flag:"🇯🇵"},{code:"vi",label:"Tiếng Việt",flag:"🇻🇳"}];function _z({collapsed:e=!1}){const{i18n:n}=rt(),[r,s]=O.useState(!1),i=O.useRef(null),a=zh.find(u=>u.code===n.language)||zh[0];O.useEffect(()=>{const u=h=>{i.current&&!i.current.contains(h.target)&&s(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[]);const l=u=>{n.changeLanguage(u),s(!1)};return f.jsxs("div",{className:"relative",ref:i,children:[f.jsxs("button",{onClick:()=>s(!r),className:`flex items-center gap-2 px-3 py-1.5 rounded-lg bg-white/5 border border-white/10 hover:bg-white/10 transition-all text-xs font-medium text-fg/70 ${e?"justify-center px-1.5":""}`,title:e?a.label:void 0,children:[!e&&f.jsx(jj,{size:14,className:"text-primary"}),f.jsx("span",{children:a.flag}),!e&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"hidden sm:inline",children:a.label}),f.jsx(Os,{size:12,className:`transition-transform duration-300 ${r?"rotate-180":""}`})]})]}),f.jsx(Ot,{children:r&&f.jsx($e.div,{initial:{opacity:0,y:10,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:10,scale:.95},className:`absolute ${e?"left-0":"right-0"} bottom-full mb-2 w-48 bg-[#1a1a1a] border border-white/10 rounded-xl shadow-2xl z-[9999] overflow-y-auto max-h-[280px] scrollbar-thin scrollbar-thumb-white/10`,children:f.jsx("div",{className:"py-1",children:zh.map(u=>f.jsxs("button",{onClick:()=>l(u.code),className:"flex items-center justify-between w-full px-4 py-2.5 text-xs text-left hover:bg-white/5 transition-colors",children:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("span",{children:u.flag}),f.jsx("span",{className:u.code===n.language?"text-primary font-bold":"text-fg/70",children:u.label})]}),u.code===n.language&&f.jsx(Ns,{size:14,className:"text-primary"})]},u.code))})})})]})}class kz{audioContext=null;enabled=!0;constructor(){}getAudioContext(){return this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),this.audioContext}setEnabled(n){this.enabled=n}isEnabled(){return this.enabled}playTone(n,r,s=.3){if(this.enabled)try{const i=this.getAudioContext(),a=i.createOscillator(),l=i.createGain();a.connect(l),l.connect(i.destination),a.frequency.value=n,a.type="sine",l.gain.setValueAtTime(s,i.currentTime),l.gain.exponentialRampToValueAtTime(.01,i.currentTime+r),a.start(i.currentTime),a.stop(i.currentTime+r)}catch(i){console.warn("[Sound] Failed to play tone:",i)}}playSequence(n,r=.3){if(!this.enabled)return;let s=0;n.forEach(i=>{setTimeout(()=>{this.playTone(i.freq,i.duration,r)},s),s+=i.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 Fo=new kz;function Sz(){const{t:e}=rt(),[n,r]=O.useState([]),[s,i]=O.useState([]),[a,l]=O.useState("discovery"),[u,h]=O.useState(!1),[p,m]=O.useState(null),[y,x]=O.useState(!0),[w,_]=O.useState(!pv),[k,S]=O.useState(!0),[E,T]=O.useState(!1),[j,P]=O.useState(!1),[A,R]=O.useState(null),[U,V]=O.useState(!1),[H,D]=O.useState(!1),[Q,Y]=O.useState(!1),[he,W]=O.useState(!0),[G,ne]=O.useState(()=>localStorage.getItem("theme")||"dark"),[re,X]=O.useState(null),ce=O.useRef(null);O.useMemo(()=>{const me=s.length;let ye=0,Ne=0,pe=null;for(const bt of s){ye+=bt.score,bt.score>Ne&&(Ne=bt.score);const Qn=new Date(bt.date);(!pe||Qn>new Date(pe.date))&&(pe=bt)}const Ue=me?Math.round(ye/me):0,st=pe?new Date(pe.date):null;return{total:me,average:Ue,top:Ne,latestTimestamp:st,latestTitle:pe?.title??pe?.category??null}},[s]),O.useEffect(()=>{(async()=>{if(!pv){_(!0),x(!1);return}try{const{data:Ne,error:pe}=await ae.from("init_state").select("is_initialized").single();pe?(console.warn("[App] Init check error (might be fresh DB):",pe),pe.code==="42P01"&&S(!1)):S(Ne.is_initialized>0);const{data:{session:Ue}}=await ae.auth.getSession();m(Ue?.user??null)}catch(Ne){console.error("[App] Status check failed:",Ne)}finally{x(!1)}})();const{data:{subscription:ye}}=ae.auth.onAuthStateChange((Ne,pe)=>{m(pe?.user??null)});return()=>ye.unsubscribe()},[]),O.useEffect(()=>{document.documentElement.setAttribute("data-theme",G),localStorage.setItem("theme",G)},[G]);const[N,M]=O.useState({});O.useEffect(()=>{(async()=>{if(!p)return;const{data:ye}=await ae.from("alchemy_settings").select("sync_start_date, last_sync_checkpoint").eq("user_id",p.id).maybeSingle();ye&&M(ye)})()},[p,U]),O.useEffect(()=>{if(!p)return;(async()=>{const{data:Ne}=await ae.from("alchemy_settings").select("sound_enabled").eq("user_id",p.id).maybeSingle();if(Ne){const pe=Ne.sound_enabled??!0;W(pe),Fo.setEnabled(pe)}})();const ye=ae.channel("processing_events").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events",filter:`user_id=eq.${p.id}`},Ne=>{const pe=Ne.new;pe.agent_state==="Mining"&&!H&&(D(!0),Y(!0),he&&Fo.syncStart()),pe.agent_state==="Signal"&&he&&Fo.signalFound(),pe.agent_state==="Completed"&&(D(!1),he&&(pe.metadata?.errors>0?Fo.error():Fo.syncComplete()),setTimeout(()=>{Y(!1)},5e3),J())}).subscribe();return()=>{ae.removeChannel(ye)}},[p,H,he]),O.useEffect(()=>{const me=new EventSource("/events");return me.onmessage=ye=>{const Ne=JSON.parse(ye.data);Ne.type==="history"?r(pe=>[...Ne.data,...pe].slice(0,100)):r(pe=>[Ne,...pe].slice(0,100))},J(),()=>me.close()},[p]),O.useEffect(()=>{ce.current&&ce.current.scrollIntoView({behavior:"smooth"})},[n]);const J=async()=>{try{if(p){const{data:ye,error:Ne}=await ae.from("signals").select("*").order("created_at",{ascending:!1});if(!Ne&&ye){i(ye.map(pe=>({id:pe.id,title:pe.title,score:pe.score,summary:pe.summary,date:pe.created_at,category:pe.category,entities:pe.entities})));return}}const me=await Ze.get("/api/signals");i(me.data)}catch(me){console.error("Failed to fetch signals",me)}},L=async()=>{h(!0);try{await Ze.post("/api/mine"),J()}catch(me){console.error("Mining failed:",me)}finally{h(!1)}},we=(me,ye)=>{me==="logs"?(X(ye),l("logs")):l(me)};return y?f.jsx("div",{className:"flex items-center justify-center h-screen bg-bg",children:f.jsx("div",{className:"w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"})}):w?f.jsx($_,{onComplete:()=>_(!1)}):p?f.jsx(mL,{children:f.jsx(vL,{children:f.jsxs("div",{className:"flex h-screen w-screen overflow-hidden bg-bg text-fg",children:[f.jsxs($e.aside,{animate:{width:E?72:240},className:"glass m-4 mr-0 flex flex-col relative",children:[f.jsxs("div",{className:`px-4 py-3 pb-4 flex items-center gap-3 ${E?"justify-center":""}`,children:[f.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:f.jsx(rn,{className:"text-white fill-current",size:24})}),!E&&f.jsx($e.h1,{initial:{opacity:0},animate:{opacity:1},className:"text-xl font-bold tracking-tight",children:"Alchemist"})]}),f.jsxs("nav",{className:"flex-1 flex flex-col gap-1 px-3",children:[f.jsx(xi,{active:a==="discovery",onClick:()=>l("discovery"),icon:f.jsx(Ej,{size:20}),label:e("tabs.discovery"),collapsed:E}),f.jsx(xi,{active:a==="chat",onClick:()=>l("chat"),icon:f.jsx($h,{size:20}),label:e("tabs.chat"),collapsed:E}),f.jsx(xi,{active:a==="transmute",onClick:()=>l("transmute"),icon:f.jsx(rn,{size:20}),label:e("tabs.transmute"),collapsed:E}),f.jsx(xi,{active:a==="engine",onClick:()=>l("engine"),icon:f.jsx(oc,{size:20}),label:e("common.settings"),collapsed:E}),f.jsx(xi,{active:a==="logs",onClick:()=>l("logs"),icon:f.jsx(ac,{size:20}),label:e("tabs.logs"),collapsed:E}),f.jsx(xi,{active:a==="account",onClick:()=>l("account"),icon:f.jsx(Ac,{size:20}),label:e("common.account"),collapsed:E})]}),f.jsx("div",{className:"px-3 pb-2 border-t border-white/5 pt-4 mt-2 relative z-[100]",children:f.jsx("div",{className:E?"flex justify-center":"px-1",children:f.jsx(_z,{collapsed:E})})}),f.jsx("div",{className:"px-3 pb-2",children:f.jsxs("button",{onClick:()=>ne(G==="dark"?"light":"dark"),className:`w-full flex items-center ${E?"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:E?e(G==="dark"?"shell.switch_light":"shell.switch_dark"):"",children:[f.jsx("div",{className:"min-w-[20px] flex justify-center",children:G==="dark"?f.jsx(Fj,{size:18}):f.jsx(Rj,{size:18})}),!E&&f.jsx($e.span,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"whitespace-nowrap",children:e(G==="dark"?"common.light_mode":"common.dark_mode")})]})}),f.jsxs("div",{className:"px-3 pb-3",children:[f.jsx("button",{onClick:()=>T(!E),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 ${E?"justify-center":"gap-3"}`,children:E?f.jsx(gj,{size:20}):f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"min-w-[20px] flex justify-center",children:f.jsx(mj,{size:20})}),f.jsx("span",{children:e("common.collapse")})]})}),f.jsxs("button",{onClick:()=>P(!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:e("shell.view_changelog"),children:[!E&&f.jsxs(f.Fragment,{children:[f.jsx(Bh,{size:12,className:"group-hover:text-primary transition-colors"}),f.jsxs("span",{children:["v","1.0.57"]})]}),E&&f.jsx(Bh,{size:14,className:"group-hover:text-primary transition-colors"})]})]})]}),f.jsxs("main",{className:"flex-1 flex flex-col p-4 gap-4 overflow-hidden relative",children:[a==="discovery"&&f.jsxs(f.Fragment,{children:[f.jsxs("header",{className:"flex justify-between items-center px-4 py-2",children:[f.jsxs("div",{children:[f.jsx("h2",{className:"text-2xl font-bold",children:e("tabs.discovery")}),f.jsx("p",{className:"text-sm text-fg/50",children:e("setup.welcome_desc")})]}),f.jsxs("div",{className:"flex gap-2",children:[f.jsxs("button",{onClick:()=>V(!0),className:"px-6 py-3 glass hover:bg-surface transition-colors flex items-center gap-2 text-sm font-medium",children:[f.jsx(oc,{size:16}),f.jsxs("div",{className:"flex flex-col items-start",children:[f.jsx("span",{children:e("discovery.sync_settings")}),f.jsx("span",{className:"text-[10px] text-fg/40 font-mono",children:N.sync_start_date?`${e("discovery.from")}: ${new Date(N.sync_start_date).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:N.last_sync_checkpoint?`${e("discovery.checkpoint")}: ${new Date(N.last_sync_checkpoint).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:e("discovery.all_time")})]})]}),f.jsxs("button",{onClick:L,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-105 active:scale-95 transition-all flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100",children:[f.jsx(Nc,{size:18,className:H?"animate-spin":""}),e(H?"discovery.syncing":"discovery.sync_history")]})]})]}),f.jsx(VL,{onOpenUrl:me=>window.open(me,"_blank","noopener,noreferrer"),onCopyText:me=>{navigator.clipboard.writeText(me)}})]}),a==="chat"&&f.jsx(yz,{}),a==="transmute"&&f.jsx(bz,{}),a==="engine"&&f.jsx(xL,{}),a==="account"&&f.jsx(jL,{}),a==="logs"&&f.jsx(IL,{initialState:re}),f.jsx(bL,{isExpanded:Q,onToggle:()=>Y(!Q),onNavigate:we,liftUp:a==="chat"})]}),f.jsx(NL,{signal:A,onClose:()=>R(null)}),f.jsx(AL,{isOpen:U,onClose:()=>V(!1)}),f.jsx(xz,{isOpen:j,onClose:()=>P(!1)})]})})}):f.jsx(dL,{onAuthSuccess:()=>J(),isInitialized:k})}function xi({active:e,icon:n,label:r,onClick:s,collapsed:i}){return f.jsx("button",{onClick:s,title:i?r:"",className:`w-full flex items-center ${i?"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:i?ta.cloneElement(n,{className:e?"text-primary":""}):f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"min-w-[20px] flex justify-center",children:ta.cloneElement(n,{className:e?"text-primary":""})}),f.jsx($e.span,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"font-semibold text-sm whitespace-nowrap",children:r})]})})}function jz(){Ze.interceptors.request.use(async e=>{try{const{data:{session:n}}=await ae.auth.getSession();n?.access_token&&(e.headers.Authorization=`Bearer ${n.access_token}`);const r=Ps();r&&(e.headers["x-supabase-url"]=r.url,e.headers["x-supabase-key"]=r.anonKey)}catch(n){console.error("[Axios] Error injecting headers:",n)}return e})}const{slice:Ez,forEach:Cz}=[];function Tz(e){return Cz.call(Ez.call(arguments,1),n=>{if(n)for(const r in n)e[r]===void 0&&(e[r]=n[r])}),e}function Nz(e){return typeof e!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(r=>r.test(e))}const iw=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Az=function(e,n){const s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},i=encodeURIComponent(n);let a=`${e}=${i}`;if(s.maxAge>0){const l=s.maxAge-0;if(Number.isNaN(l))throw new Error("maxAge should be a Number");a+=`; Max-Age=${Math.floor(l)}`}if(s.domain){if(!iw.test(s.domain))throw new TypeError("option domain is invalid");a+=`; Domain=${s.domain}`}if(s.path){if(!iw.test(s.path))throw new TypeError("option path is invalid");a+=`; Path=${s.path}`}if(s.expires){if(typeof s.expires.toUTCString!="function")throw new TypeError("option expires is invalid");a+=`; Expires=${s.expires.toUTCString()}`}if(s.httpOnly&&(a+="; HttpOnly"),s.secure&&(a+="; Secure"),s.sameSite)switch(typeof s.sameSite=="string"?s.sameSite.toLowerCase():s.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return s.partitioned&&(a+="; Partitioned"),a},ow={create(e,n,r,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};r&&(i.expires=new Date,i.expires.setTime(i.expires.getTime()+r*60*1e3)),s&&(i.domain=s),document.cookie=Az(e,n,i)},read(e){const n=`${e}=`,r=document.cookie.split(";");for(let s=0;s<r.length;s++){let i=r[s];for(;i.charAt(0)===" ";)i=i.substring(1,i.length);if(i.indexOf(n)===0)return i.substring(n.length,i.length)}return null},remove(e,n){this.create(e,"",-1,n)}};var Rz={name:"cookie",lookup(e){let{lookupCookie:n}=e;if(n&&typeof document<"u")return ow.read(n)||void 0},cacheUserLanguage(e,n){let{lookupCookie:r,cookieMinutes:s,cookieDomain:i,cookieOptions:a}=n;r&&typeof document<"u"&&ow.create(r,e,s,i,a)}},Pz={name:"querystring",lookup(e){let{lookupQuerystring:n}=e,r;if(typeof window<"u"){let{search:s}=window.location;!window.location.search&&window.location.hash?.indexOf("?")>-1&&(s=window.location.hash.substring(window.location.hash.indexOf("?")));const a=s.substring(1).split("&");for(let l=0;l<a.length;l++){const u=a[l].indexOf("=");u>0&&a[l].substring(0,u)===n&&(r=a[l].substring(u+1))}}return r}},Oz={name:"hash",lookup(e){let{lookupHash:n,lookupFromHashIndex:r}=e,s;if(typeof window<"u"){const{hash:i}=window.location;if(i&&i.length>2){const a=i.substring(1);if(n){const l=a.split("&");for(let u=0;u<l.length;u++){const h=l[u].indexOf("=");h>0&&l[u].substring(0,h)===n&&(s=l[u].substring(h+1))}}if(s)return s;if(!s&&r>-1){const l=i.match(/\/([a-zA-Z-]*)/g);return Array.isArray(l)?l[typeof r=="number"?r:0]?.replace("/",""):void 0}}}return s}};let vi=null;const aw=()=>{if(vi!==null)return vi;try{if(vi=typeof window<"u"&&window.localStorage!==null,!vi)return!1;const e="i18next.translate.boo";window.localStorage.setItem(e,"foo"),window.localStorage.removeItem(e)}catch{vi=!1}return vi};var Lz={name:"localStorage",lookup(e){let{lookupLocalStorage:n}=e;if(n&&aw())return window.localStorage.getItem(n)||void 0},cacheUserLanguage(e,n){let{lookupLocalStorage:r}=n;r&&aw()&&window.localStorage.setItem(r,e)}};let wi=null;const lw=()=>{if(wi!==null)return wi;try{if(wi=typeof window<"u"&&window.sessionStorage!==null,!wi)return!1;const e="i18next.translate.boo";window.sessionStorage.setItem(e,"foo"),window.sessionStorage.removeItem(e)}catch{wi=!1}return wi};var Iz={name:"sessionStorage",lookup(e){let{lookupSessionStorage:n}=e;if(n&&lw())return window.sessionStorage.getItem(n)||void 0},cacheUserLanguage(e,n){let{lookupSessionStorage:r}=n;r&&lw()&&window.sessionStorage.setItem(r,e)}},Dz={name:"navigator",lookup(e){const n=[];if(typeof navigator<"u"){const{languages:r,userLanguage:s,language:i}=navigator;if(r)for(let a=0;a<r.length;a++)n.push(r[a]);s&&n.push(s),i&&n.push(i)}return n.length>0?n:void 0}},Mz={name:"htmlTag",lookup(e){let{htmlTag:n}=e,r;const s=n||(typeof document<"u"?document.documentElement:null);return s&&typeof s.getAttribute=="function"&&(r=s.getAttribute("lang")),r}},zz={name:"path",lookup(e){let{lookupFromPathIndex:n}=e;if(typeof window>"u")return;const r=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(r)?r[typeof n=="number"?n:0]?.replace("/",""):void 0}},Fz={name:"subdomain",lookup(e){let{lookupFromSubdomainIndex:n}=e;const r=typeof n=="number"?n+1:1,s=typeof window<"u"&&window.location?.hostname?.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);if(s)return s[r]}};let Yk=!1;try{document.cookie,Yk=!0}catch{}const Qk=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];Yk||Qk.splice(1,1);const $z=()=>({order:Qk,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:e=>e});class Zk{constructor(n){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(n,r)}init(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=n,this.options=Tz(r,this.options||{},$z()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=i=>i.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=s,this.addDetector(Rz),this.addDetector(Pz),this.addDetector(Lz),this.addDetector(Iz),this.addDetector(Dz),this.addDetector(Mz),this.addDetector(zz),this.addDetector(Fz),this.addDetector(Oz)}addDetector(n){return this.detectors[n.name]=n,this}detect(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,r=[];return n.forEach(s=>{if(this.detectors[s]){let i=this.detectors[s].lookup(this.options);i&&typeof i=="string"&&(i=[i]),i&&(r=r.concat(i))}}),r=r.filter(s=>s!=null&&!Nz(s)).map(s=>this.options.convertDetectedLanguage(s)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?r:r.length>0?r[0]:null}cacheUserLanguage(n){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;r&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(n)>-1||r.forEach(s=>{this.detectors[s]&&this.detectors[s].cacheUserLanguage(n,this.options)}))}}Zk.type="languageDetector";const Uz={save:"Save",cancel:"Cancel",loading:"Loading...",error:"Error",success:"Success",settings:"Settings",search:"Search",back:"Back",all:"All",delete:"Delete",update:"Update",edit:"Edit",close:"Close",complete:"Complete",skip:"Skip",begin:"Begin",connection:"Connection",setup:"Setup",project:"Project",account:"Account",logout:"Logout",welcome:"Welcome",dark_mode:"Dark Mode",light_mode:"Light Mode",collapse:"Collapse",just_now:"Just now",enabled:"Enabled",disabled:"Disabled",quick:"Quick (5)",balanced:"Balanced (50)",thorough:"Thorough (200)",resetting:"Resetting...",saving:"Saving...",locale_code:"en-US",categories:{ai_ml:"AI & ML",business:"Business",politics:"Politics",technology:"Technology",finance:"Finance",crypto:"Crypto",science:"Science",other:"Other"}},Bz={discovery:"Discovery",chat:"Chat",transmute:"Transmute",logs:"System Logs",history:"History"},Vz={welcome_title:"Assemble Your Engine",welcome_desc:"Alchemy requires a Supabase essence to store signal fragments and intelligence patterns.",requirements:"Requirements:",project_url:"Supabase Project URL",anon_key:"Anon Public API Key",db_password:"Database Password",begin_init:"BEGIN INITIALIZATION",connect_essence:"CONNECT ESSENCE",validating:"Validating Link",resonance:"Synchronizing Resonance...",init_schema:"Initialize Schema",schema_desc:"Run database migrations to set up required tables and functions.",project_id:"Project ID",access_token:"Access Token",run_migrations:"RUN MIGRATIONS",running_migrations:"Running Migrations",take_minute:"This may take a minute...",engine_aligned:"Engine Aligned",restarting:"Restarting Alchemist Subsystems..."},qz={filters:"Filters",category:"Category",intelligence_score:"Intelligence Score",no_signals_in_category:"No signals in {{category}} yet.",no_categories:"No categories yet.",discovery_hint:"Signals will be organized here once discovered.",loading_signals:"Loading signals...",dismiss_hint:"Dismiss (Not Interested)",signal_count_one:"{{count}} signal",signal_count_other:"{{count}} signals",time_min_ago:"{{count}}m ago",time_hour_ago:"{{count}}h ago",time_day_ago:"{{count}}d ago",add_note_title:"Add Note",target:"Target",note_placeholder:"Enter your thoughts, ideas, or action items regarding this signal...",save_note:"Save Note",view_all_sources:"View all sources",source_count_one:"{{count}} source",source_count_other:"{{count}} sources",source_found_in:"Found in {{count}} different sources",high_confidence:"High confidence - found in {{count}} sources",new_signals:"New Signals",smart_summary:"Smart Summary",entities:"Entities",sources:"Sources",last_sync:"Last Sync",syncnow:"Sync Now",all_time:"All time",checkpoint:"Checkpoint",from:"From",score_high:"HIGH",score_medium:"MEDIUM",score_low:"LOW",sources_count:"{{count}} sources",open_source:"Open",add_note:"Note",boost_topic:"Boost Topic",boosted:"Boosted",dismissed:"Dismissed",remove_favourite:"Remove from favourites",add_favourite:"Add to favourites",sync_history:"Sync History",syncing:"Syncing...",sync_settings:"Sync Settings",discovered:"Discovered",original_source:"Original Source",ai_summary:"AI Summary",full_content:"Full Content",copied:"Copied!",open_link:"Open",detail_title:"Signal Details",sync_from:"Sync From (Optional)",urls_per_sync:"URLs per Sync",sync_from_hint:"Leave empty to sync only new URLs since last sync (incremental). Set a date to process URLs from that point forward.",reset_checkpoint:"Reset Checkpoint",reset_checkpoint_hint:'Clear the sync checkpoint to force a full re-sync from your "Sync From" date',sync_info:'The Alchemist tracks your progress automatically. Use "Sync From" to backfill history or "Reset Checkpoint" to start fresh.',save_settings:"Save Settings",sync_saved:"Sync settings saved successfully",checkpoint_reset:"Checkpoint reset successfully",login_to_save:"Please log in to save settings",login_to_reset:"Please log in to reset checkpoint",status_updated:"Engine status updated to {{status}}",asset_ready:'Asset "{{title}}" is ready!',scanning:"Scanning for new categories and topics...",discovery_complete:"Engine discovery complete!",discovery_failed:"Discovery failed. Check settings.",load_failed:"Failed to load engines",starting_run:"Starting engine run...",run_complete:"Engine run complete! Created: {{title}}",run_started_desktop:"Engine run started on Desktop. Tracking as: {{id}}",run_failed:"Failed to run engine",brief_failed:"Failed to generate production brief",copied_json:"JSON copied to clipboard",json_footer:"This JSON contains the full context (Signals + User Persona) required for the Desktop Studio.",topic:"Topic",pipeline:"Pipeline"},Hz={history:"History",ask_anything:"Ask anything about your browsing history...",sources:"Sources",processing:"Processing your query...",new_chat:"New Chat",no_messages:"No messages yet. Start a conversation!",no_history:"No chat history yet.",title:"Ask Alchemist",desc:"I can help you recall information, summarize topics, and find insights from your browsing history.",thinking:"Exploring memory...",placeholder:"Ask about your history...",error_message:"Sorry, I encountered an error processing your request.",relevant_context:"Relevant Context",match_score:"{{score}}% Match",rag_attribution:"Alchemist used these {{count}} signals to answer",suggestions:{react:"What have I read about React recently?",ai:"Summarize the latest AI news I visited.",finance:"Do I have any notes on Finance?",performance:"Find articles about 'Performance'"}},Kz={engines:"Alchemist Engines",assets:"Generated Assets",newsletter:"Newsletter",thread:"Thread",audio:"Audio",report:"Report",title:"Transmute Engine",desc:"Active Generation Pipelines & Assets",generate:"Generate",processing_desktop:"Processing on Desktop...",ensure_defaults:"Ensure Default Engines",create_engine:"Create Engine",no_assets:"No assets generated yet.",generate_engines:"Generate Engines",new_engine:"New Engine",no_engines:"No Engines Configured",no_engines_desc:"Create your first pipeline to automatically turn signals into newsletters, threads, or audio briefs.",run_engine:"Run Engine",running:"Running...",last_run:"Last Run",never:"Never",schedule:"Schedule",manual:"Manual",topic:"Topic",pipeline:"Pipeline",pause:"Pause",resume:"Resume",view_json:"View Production Brief JSON",json_contract:"Stateless & Self-Contained Contract",json_desc:"This JSON contains the full context (Signals + User Persona) required for the Desktop Studio.",generating_asset:"Generating Asset...",queued_desktop:"Queued for Desktop...",desktop_processing:"The RealTimeX Desktop app is processing this request. This modal will update automatically once finished.",unsupported_type:"Unsupported asset type",edit_engine:"Edit Engine",engine_name:"Engine Name",type:"Type",status:"Status",execution_env:"Execution Environment",local_llm:"Local (Alchemy LLM)",desktop_swarm:"RealTimeX Desktop (Agent Swarm)",env_desc_desktop:"Delegates heavy tasks like Audio/Video to the desktop app.",env_desc_local:"Runs simple Markdown tasks directly in Alchemy.",min_score:"Min Score",max_signals:"Max Signals",category_filter:"Category Filter (multi-select)",multi_select_hint:"Hold Cmd/Ctrl to select multiple categories",schedule_hint:"Note: Scheduling is not yet automated",prompt_override:"Custom Prompt Override (optional)",prompt_placeholder:"Override the default prompt for this engine type...",delete_confirm:"Really delete?",confirm:"Confirm"},Wz={title:"Account Configuration",desc:"Manage your Alchemist profile and essence links.",profile:"Profile",security:"Security",supabase:"Supabase",first_name:"First Name",last_name:"Last Name",email_locked:"Email Address (Locked)",sound_effects:"Sound Effects",sound_desc:"Enable audio feedback for sync events and signal discoveries.",sign_out:"Sign Out",logout_desc:"End your current session and return to the login screen.",preserve_profile:"Preserve Profile",security_title:"Update Entropy Key",new_password:"New Password",confirm_password:"Confirm Password",password_mismatch:"Complexity keys do not match.",password_too_short:"Entropy too low. Minimum 8 characters.",password_rotate_success:"Key rotation successful.",rotate_key:"Rotate Key",essence_resonance:"Essence Resonance",byok_desc:"Bring Your Own Keys (BYOK) for intelligence persistence.",established_link:"Established Link",env_notice:"Active from environment variables. UI override enabled.",realign_link:"Realign Link",sever_link:"Sever Link",sever_confirm:"Sever connection to this essence? This will reset local resonance.",anon_secret_fragment:"Anon Secret Fragment",no_resonance:"No Essence Resonance",no_resonance_desc:"The Alchemist requires a cloud core to store intelligence fragments.",initiate_link:"Initiate Link",test_connection:"Test Connection"},Gz={title:"System Logs",desc:"Detailed history of sync runs, sources, and URL processing",blacklist_suggestion:"Potential Blacklist",blacklist_desc:"Candidates for blocking",recent_errors:"Recent Errors",errors_desc:"Failed URL processes",total_signals:"Total Signals",signals_desc:"Successfully mined",blacklist_modal_title:"Blacklist Suggestions",blacklist_modal_desc:"Review domains suggested for blacklisting based on low scores.",no_suggestions:"No suggestions right now",quality_good:"Your signal quality looks good!",signals_count:"{{count}} signals",avg_score:"Avg Score: {{score}}",low_quality:"Consistently Low Quality",repetitive:"Repetitive Pattern",blacklist_domain:"Blacklist Domain",errors_modal_title:"Recent Errors",errors_modal_desc:"Log of recent failures and issues.",no_recent_errors:"No recent errors found.",signals_modal_title:"Found Signals",signals_modal_desc:"Browse and manage your mined signals history.",search_placeholder:"Search signals...",any_score:"Any Score",high_score:"High (80%+)",medium_score:"Medium (50-79%)",low_score:"Low (<50%)",all_categories:"All Categories",page_x:"Page {{page}}"},Jz={title:"Alchemist Engine",live:"LIVE",clear:"Clear",idle:"Idle. Awaiting signal mining events...",run_completed:"Mining Run Completed",signals:"Signals",urls:"URLs",skipped:"Skipped",failed_to_process:"{{count}} URLs failed to process",view_logs:"View Logs",hide_details:"Hide Details",view_details:"View Details",engine_log:"Live Engine Log",state_reading:"Reading",state_thinking:"Thinking",state_signal:"Signal",state_skipped:"Skipped",state_error:"Error",state_completed:"Completed",msg_reading:"Reading content from: {{url}}",msg_thinking:"Analyzing relevance of: {{title}}",msg_found_signal:"Found signal: {{summary}} ({{score}}%)",msg_low_signal:"Low signal stored for review ({{score}}%): {{title}}",msg_failed:"Analysis failed for {{title}}: {{error}}",msg_sync_completed:"Sync completed: {{signals}} signals found, {{skipped}} skipped, {{errors}} errors"},Xz={switch_light:"Switch to Light Mode",switch_dark:"Switch to Dark Mode",view_changelog:"View Changelog",release_notes:"Release Notes",changelog_error:"Failed to load changelog."},Yz={title:"Signal Pulse",mining:"Mining",standing_by:"Standing by",idle:"Idle",tracked:"Signals tracked",avg_score:"Average score",top_signal:"Top signal",latest:"Latest",awaiting:"Awaiting mining",no_signals:"No signals yet"},Qz={title:"Intelligence Engine",subtitle:"Fine-tune the Alchemist's cognitive parameters and provider links.",configuration:"AI Configuration",test_connection:"Test Connection",save_config:"Save Configuration",llm_provider:"LLM Provider",embedding_provider:"Embedding Provider",sdk_connected:"SDK Connected",sdk_not_available:"SDK Not Available",provider:"Provider",intelligence_model:"Intelligence Model",embedding_model:"Embedding Model",loading_providers:"Loading providers...",sdk_info_success:"✓ Using RealTimeX configured provider",sdk_info_fail:"⚠️ RealTimeX SDK not detected. Configure in RealTimeX Desktop.",embedding_info_success:"✓ Embeddings are generated using your RealTimeX configured provider",embedding_info_fail:"⚠️ RealTimeX SDK not detected. Configure providers in RealTimeX Desktop.",persona_title:"Persona Memory",save_memory:"Save Memory",interests_title:"Active Interests",interests_priority:"High Priority",interests_desc:"The Alchemist prioritizes content matching these topics. Updated automatically based on Favorites & Boosts.",interests_placeholder:"e.g. User focuses on React performance, Rust backend systems, and AI Agent architecture...",antipatterns_title:"Anti-Patterns",antipatterns_priority:"Avoid",antipatterns_desc:"The Alchemist filters out or scores down content matching these patterns. Updated via Dismissals.",antipatterns_placeholder:"e.g. Dislikes marketing fluff, generic listicles, and crypto hype...",browser_sources:"Browser History Sources",save_browser:"Save Browser Sources",blacklist_title:"Blacklist Domains",blacklist_desc:"URLs containing these patterns will be skipped during mining. Enter one pattern per line.",blacklist_label:"Domain Patterns (one per line)",blacklist_placeholder:`google.com/search
|
|
135
135
|
localhost:
|
|
136
136
|
127.0.0.1
|
|
137
137
|
facebook.com
|
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-BD6Vefvz.js"></script>
|
|
13
13
|
<link rel="stylesheet" crossorigin href="/assets/index-B6joRGWV.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.57",
|
|
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",
|
|
@@ -21,14 +21,14 @@
|
|
|
21
21
|
"scripts": {
|
|
22
22
|
"dev": "vite",
|
|
23
23
|
"dev:api": "tsx watch api/index.ts",
|
|
24
|
-
"prebuild:ui": "
|
|
25
|
-
"version": "
|
|
24
|
+
"prebuild:ui": "node scripts/copy-changelog.mjs",
|
|
25
|
+
"version": "node scripts/copy-changelog.mjs && git add public/CHANGELOG.md",
|
|
26
26
|
"build": "npm run build:ui && npm run build:api",
|
|
27
27
|
"build:ui": "vite build",
|
|
28
28
|
"build:api": "tsc -p tsconfig.api.json",
|
|
29
29
|
"start": "node dist/api/index.js",
|
|
30
30
|
"preview": "vite preview",
|
|
31
|
-
"migrate": "
|
|
31
|
+
"migrate": "tsx scripts/migrate.ts",
|
|
32
32
|
"timestamp": "node scripts/get-latest-migration-timestamp.mjs"
|
|
33
33
|
},
|
|
34
34
|
"keywords": [
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { copyFileSync, existsSync } from 'fs';
|
|
2
|
+
import { join, dirname } from 'path';
|
|
3
|
+
import { fileURLToPath } from 'url';
|
|
4
|
+
|
|
5
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = dirname(__filename);
|
|
7
|
+
const ROOT_DIR = join(__dirname, '..');
|
|
8
|
+
|
|
9
|
+
const src = join(ROOT_DIR, 'CHANGELOG.md');
|
|
10
|
+
const dest = join(ROOT_DIR, 'public', 'CHANGELOG.md');
|
|
11
|
+
|
|
12
|
+
try {
|
|
13
|
+
if (existsSync(src)) {
|
|
14
|
+
copyFileSync(src, dest);
|
|
15
|
+
console.log('✅ CHANGELOG.md copied to public/');
|
|
16
|
+
} else {
|
|
17
|
+
console.error('❌ CHANGELOG.md not found');
|
|
18
|
+
process.exit(1);
|
|
19
|
+
}
|
|
20
|
+
} catch (error) {
|
|
21
|
+
console.error('❌ Failed to copy CHANGELOG.md:', error.message);
|
|
22
|
+
process.exit(1);
|
|
23
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { spawn } from 'child_process';
|
|
2
|
+
import { fileURLToPath } from 'url';
|
|
3
|
+
import { dirname, join } from 'path';
|
|
4
|
+
import { readdirSync, existsSync, statSync } from 'fs';
|
|
5
|
+
import { createInterface } from 'readline';
|
|
6
|
+
import crypto from 'crypto';
|
|
7
|
+
|
|
8
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
9
|
+
const __dirname = dirname(__filename);
|
|
10
|
+
const ROOT_DIR = join(__dirname, '..');
|
|
11
|
+
|
|
12
|
+
const rl = createInterface({
|
|
13
|
+
input: process.stdin,
|
|
14
|
+
output: process.stdout
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
const question = (query: string): Promise<string> => {
|
|
18
|
+
return new Promise((resolve) => rl.question(query, resolve));
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
async function runCommand(command: string, args: string[], env = {}): Promise<void> {
|
|
22
|
+
return new Promise((resolve, reject) => {
|
|
23
|
+
console.log(`\n🏃 Running: ${command} ${args.join(' ')}`);
|
|
24
|
+
const child = spawn(command, args, {
|
|
25
|
+
stdio: 'inherit',
|
|
26
|
+
shell: true,
|
|
27
|
+
env: { ...process.env, ...env }
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
child.on('close', (code) => {
|
|
31
|
+
if (code === 0) resolve();
|
|
32
|
+
else reject(new Error(`Command failed with code ${code}`));
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
child.on('error', (err) => {
|
|
36
|
+
reject(err);
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function findSupabaseBin(): Promise<{ cmd: string; baseArgs: string[] }> {
|
|
42
|
+
const isWindows = process.platform === 'win32';
|
|
43
|
+
const binName = isWindows ? 'supabase.cmd' : 'supabase';
|
|
44
|
+
const candidate = join(ROOT_DIR, 'node_modules', '.bin', binName);
|
|
45
|
+
|
|
46
|
+
if (existsSync(candidate)) {
|
|
47
|
+
return { cmd: candidate, baseArgs: [] };
|
|
48
|
+
}
|
|
49
|
+
// Fallback to npx
|
|
50
|
+
return { cmd: 'npx', baseArgs: ['--no-install', 'supabase'] };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function main() {
|
|
54
|
+
console.log("🚀 Starting RealTimeX Alchemy Migration Tool...");
|
|
55
|
+
|
|
56
|
+
const { cmd: SUPABASE_CMD, baseArgs: SUPABASE_ARGS } = await findSupabaseBin();
|
|
57
|
+
console.log(` Using: ${SUPABASE_CMD} ${SUPABASE_ARGS.join(' ')}`);
|
|
58
|
+
|
|
59
|
+
if (!existsSync(join(ROOT_DIR, 'supabase'))) {
|
|
60
|
+
console.error("❌ Error: supabase folder not found");
|
|
61
|
+
process.exit(1);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
let projectId = process.env.SUPABASE_PROJECT_ID;
|
|
65
|
+
if (!projectId) {
|
|
66
|
+
console.log("---------------------------------------------------------");
|
|
67
|
+
console.log("👉 Enter your Supabase Project Reference ID:");
|
|
68
|
+
console.log(" (Found in Supabase Dashboard > Project Settings > General)");
|
|
69
|
+
projectId = await question(" Project ID: ");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (!projectId) {
|
|
73
|
+
console.error("❌ Error: Project ID is required to proceed.");
|
|
74
|
+
process.exit(1);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
let accessToken = process.env.SUPABASE_ACCESS_TOKEN;
|
|
78
|
+
if (!accessToken) {
|
|
79
|
+
console.error("❌ Error: SUPABASE_ACCESS_TOKEN is required.");
|
|
80
|
+
console.log(" Generate one at: https://supabase.com/dashboard/account/tokens");
|
|
81
|
+
process.exit(1);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
process.chdir(ROOT_DIR);
|
|
86
|
+
|
|
87
|
+
console.log("---------------------------------------------------------");
|
|
88
|
+
console.log(`🔗 Linking to Supabase Project: ${projectId}`);
|
|
89
|
+
await runCommand(SUPABASE_CMD, [...SUPABASE_ARGS, 'link', '--project-ref', projectId]);
|
|
90
|
+
|
|
91
|
+
console.log("---------------------------------------------------------");
|
|
92
|
+
console.log("📂 Pushing Database Schema Changes...");
|
|
93
|
+
await runCommand(SUPABASE_CMD, [...SUPABASE_ARGS, 'db', 'push']);
|
|
94
|
+
|
|
95
|
+
console.log("---------------------------------------------------------");
|
|
96
|
+
console.log("⚙️ Pushing Project Configuration...");
|
|
97
|
+
await runCommand(SUPABASE_CMD, [...SUPABASE_ARGS, 'config', 'push']);
|
|
98
|
+
|
|
99
|
+
console.log("---------------------------------------------------------");
|
|
100
|
+
console.log("🔐 Setting up Edge Function secrets...");
|
|
101
|
+
|
|
102
|
+
// Use shell: true in runCommand to handle pipes or just run simple command
|
|
103
|
+
// For simplicity and cross-platform, we can try to list secrets
|
|
104
|
+
try {
|
|
105
|
+
// Note: This might be tricky across platforms if it relies on grep.
|
|
106
|
+
// We'll just try to set it, Supabase CLI usually handles existing ones if possible
|
|
107
|
+
// or we just skip if we can detect it.
|
|
108
|
+
|
|
109
|
+
console.log(" Checking TOKEN_ENCRYPTION_KEY...");
|
|
110
|
+
const encryptionKey = crypto.randomBytes(24).toString('base64');
|
|
111
|
+
await runCommand(SUPABASE_CMD, [...SUPABASE_ARGS, 'secrets', 'set', `TOKEN_ENCRYPTION_KEY=${encryptionKey}`]);
|
|
112
|
+
console.log(" ✅ TOKEN_ENCRYPTION_KEY has been set/updated");
|
|
113
|
+
} catch (e) {
|
|
114
|
+
console.log(" ⚠️ Note: Secret setting might have failed or already exists.");
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
console.log("---------------------------------------------------------");
|
|
118
|
+
console.log("⚡ Deploying Edge Functions...");
|
|
119
|
+
const functionsDir = join(ROOT_DIR, 'supabase', 'functions');
|
|
120
|
+
if (existsSync(functionsDir)) {
|
|
121
|
+
const entries = readdirSync(functionsDir);
|
|
122
|
+
for (const entry of entries) {
|
|
123
|
+
const funcPath = join(functionsDir, entry);
|
|
124
|
+
if (statSync(funcPath).isDirectory() && !entry.startsWith('_') && !entry.startsWith('.')) {
|
|
125
|
+
if (existsSync(join(funcPath, 'index.ts'))) {
|
|
126
|
+
console.log(` Deploying ${entry}...`);
|
|
127
|
+
await runCommand(SUPABASE_CMD, [...SUPABASE_ARGS, 'functions', 'deploy', entry, '--no-verify-jwt']);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
console.log("---------------------------------------------------------");
|
|
134
|
+
console.log("✅ SUCCESS: Backend updated successfully!");
|
|
135
|
+
|
|
136
|
+
} catch (error: any) {
|
|
137
|
+
console.error(`\n❌ Error during migration: ${error.message}`);
|
|
138
|
+
process.exit(1);
|
|
139
|
+
} finally {
|
|
140
|
+
rl.close();
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
main();
|