@origintrail-official/dkg-node-ui 0.0.1-dev.1773506972.23bf9c0

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.
Files changed (84) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +49 -0
  3. package/dist/api.d.ts +30 -0
  4. package/dist/api.d.ts.map +1 -0
  5. package/dist/api.js +805 -0
  6. package/dist/api.js.map +1 -0
  7. package/dist/chat-assistant.d.ts +68 -0
  8. package/dist/chat-assistant.d.ts.map +1 -0
  9. package/dist/chat-assistant.js +663 -0
  10. package/dist/chat-assistant.js.map +1 -0
  11. package/dist/chat-memory.d.ts +171 -0
  12. package/dist/chat-memory.d.ts.map +1 -0
  13. package/dist/chat-memory.js +985 -0
  14. package/dist/chat-memory.js.map +1 -0
  15. package/dist/chat-persistence-queue.d.ts +67 -0
  16. package/dist/chat-persistence-queue.d.ts.map +1 -0
  17. package/dist/chat-persistence-queue.js +245 -0
  18. package/dist/chat-persistence-queue.js.map +1 -0
  19. package/dist/db.d.ts +402 -0
  20. package/dist/db.d.ts.map +1 -0
  21. package/dist/db.js +887 -0
  22. package/dist/db.js.map +1 -0
  23. package/dist/gelf-push-worker.d.ts +67 -0
  24. package/dist/gelf-push-worker.d.ts.map +1 -0
  25. package/dist/gelf-push-worker.js +147 -0
  26. package/dist/gelf-push-worker.js.map +1 -0
  27. package/dist/index.d.ts +20 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +12 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/llm/capability-resolver.d.ts +3 -0
  32. package/dist/llm/capability-resolver.d.ts.map +1 -0
  33. package/dist/llm/capability-resolver.js +21 -0
  34. package/dist/llm/capability-resolver.js.map +1 -0
  35. package/dist/llm/client.d.ts +23 -0
  36. package/dist/llm/client.d.ts.map +1 -0
  37. package/dist/llm/client.js +91 -0
  38. package/dist/llm/client.js.map +1 -0
  39. package/dist/llm/provider-adapter.d.ts +16 -0
  40. package/dist/llm/provider-adapter.d.ts.map +1 -0
  41. package/dist/llm/provider-adapter.js +199 -0
  42. package/dist/llm/provider-adapter.js.map +1 -0
  43. package/dist/llm/types.d.ts +64 -0
  44. package/dist/llm/types.d.ts.map +1 -0
  45. package/dist/llm/types.js +2 -0
  46. package/dist/llm/types.js.map +1 -0
  47. package/dist/metrics-collector.d.ts +36 -0
  48. package/dist/metrics-collector.d.ts.map +1 -0
  49. package/dist/metrics-collector.js +155 -0
  50. package/dist/metrics-collector.js.map +1 -0
  51. package/dist/operation-tracker.d.ts +43 -0
  52. package/dist/operation-tracker.d.ts.map +1 -0
  53. package/dist/operation-tracker.js +195 -0
  54. package/dist/operation-tracker.js.map +1 -0
  55. package/dist/structured-logger.d.ts +16 -0
  56. package/dist/structured-logger.d.ts.map +1 -0
  57. package/dist/structured-logger.js +41 -0
  58. package/dist/structured-logger.js.map +1 -0
  59. package/dist/telemetry.d.ts +35 -0
  60. package/dist/telemetry.d.ts.map +1 -0
  61. package/dist/telemetry.js +45 -0
  62. package/dist/telemetry.js.map +1 -0
  63. package/dist-ui/assets/3d-force-graph-nMUNmvtB.js +964 -0
  64. package/dist-ui/assets/AgentHub-XKCM9uYQ.js +65 -0
  65. package/dist-ui/assets/AppHost-DoLIi89g.js +1 -0
  66. package/dist-ui/assets/Apps-Cc8HfqfD.js +1 -0
  67. package/dist-ui/assets/Dashboard-D5q6MK78.js +2 -0
  68. package/dist-ui/assets/Explorer-B80RVksc.js +64 -0
  69. package/dist-ui/assets/N3Parser-Q_-1ZY5E.js +7 -0
  70. package/dist-ui/assets/Settings-CG7-7GM-.js +71 -0
  71. package/dist-ui/assets/hooks-BLTFNmyP.js +1 -0
  72. package/dist-ui/assets/index-8_35CUX2.js +192 -0
  73. package/dist-ui/assets/index-CKZq_ZB-.css +1 -0
  74. package/dist-ui/assets/index-DH-l6lM0.js +76 -0
  75. package/dist-ui/assets/jsonld-32FQRO67-DhbO8O6B.js +2 -0
  76. package/dist-ui/assets/jsonld-BFI4wECl.js +62 -0
  77. package/dist-ui/assets/ntriples-ZWBY2WET-nIpilpjf.js +1 -0
  78. package/dist-ui/assets/ordinal-DIohFSkg.js +1 -0
  79. package/dist-ui/assets/renderer-3d-2EVDZII7-DsxBsJvs.js +2 -0
  80. package/dist-ui/assets/three.module-uCjFke6H.js +4019 -0
  81. package/dist-ui/assets/turtle-JJPK7LJ5-zezDJZEp.js +1 -0
  82. package/dist-ui/favicon.png +0 -0
  83. package/dist-ui/index.html +14 -0
  84. package/package.json +58 -0
@@ -0,0 +1,65 @@
1
+ import{r as s,a as as,t as ls,v as Gt,q as _t,w as ds,x as cs,y as us,z as Ht,j as e,A as ps,B as hs,c as gs,C as fs,D as xs,E as Et,F as ms,G as ys}from"./index-DH-l6lM0.js";import{R as Ft,u as bs}from"./index-8_35CUX2.js";import"./ordinal-DIohFSkg.js";function ze(n){if(!n)return n;const o=n.match(/^"([\s\S]*)"(?:\^\^<[^>]+>)?(?:@[a-z-]+)?$/);return o?o[1]:n}function zt(n){return n.replace(/\s+/g," ").trim()}function vs(n){if(n&&(n==="pending"||n==="in_progress"||n==="stored"||n==="enshrined"||n==="failed"||n==="skipped"))return n}const Ut="http://schema.org/dateCreated",Ss="http://schema.org/text",ws="http://schema.org/name",qe="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",js="http://dkg.io/ontology/ChatTurn",ks="http://dkg.io/ontology/turnId",Kt="http://dkg.io/ontology/GraphCluster",Cs="http://dkg.io/ontology/clusterLinksTo",Is="http://dkg.io/ontology/literalCount";function We(n){return n.startsWith("urn:")||n.startsWith("http://")||n.startsWith("https://")||n.startsWith("did:")||n.startsWith("_:")}function ct(n){return`${n.subject}\0${n.predicate}\0${n.object}`}function Ye(n){const o=new Set;for(const i of n)o.add(i.subject),We(i.object)&&o.add(i.object);return o}function Lt(n){const o=new Set;for(const i of n)We(i.object)&&o.add(ct(i));return o}function Ns(n,o){const i=Ye(n),a=[...Ye(o)].filter(d=>!i.has(d)),c=Lt(n),C=[...Lt(o)].filter(d=>!c.has(d));return{addedNodeCount:a.length,addedEdgeCount:C.length,sampleNodes:a.slice(0,4),sampleEdges:C.slice(0,3)}}function dt(n){let o=!1;const i=n.map(g=>g.role!=="assistant"||g.persistStatus!=="stored"?g:(o=!0,{...g,persistStatus:"enshrined"}));return o?i:n}function Ms(n,o){if(o.length===0)return n;const i=new Set(n.map(ct)),g=[...n];for(const a of o){const c=ct(a);i.has(c)||(i.add(c),g.push(a))}return g}function Ts(n){if(n.length===0)return null;const o=new Set,i=new Map,g=new Map;for(const c of n){if(c.predicate===qe&&c.object===js){o.add(c.subject);continue}if(c.predicate===ks){i.set(c.subject,ze(c.object));continue}if(c.predicate===Ut){const v=Date.parse(ze(c.object));Number.isNaN(v)||g.set(c.subject,v)}}const a=[...o].map(c=>({subject:c,turnId:i.get(c),ts:g.get(c)??0})).filter(c=>!!c.turnId).sort((c,v)=>c.ts-v.ts||String(c.turnId).localeCompare(String(v.turnId)));return a.length===0?null:a[a.length-1].turnId??null}function Dt(n,o){if(n.length===0)return null;const i=[...n].sort((a,c)=>a-c),g=Math.max(0,Math.min(i.length-1,Math.ceil(i.length*o)-1));return i[g]??null}function Rs(n,o){return o!=null&&o.includes("Conversation")?"Conversation":o!=null&&o.includes("Message")?"Message":o!=null&&o.includes("ToolInvocation")?"ToolInvocation":o!=null&&o.includes("ChatTurn")?"ChatTurn":n.includes(":session:")?"Conversation":n.includes(":msg:")?"Message":n.includes(":tool:")?"ToolInvocation":n.includes(":turn:")?"ChatTurn":n.startsWith("urn:dkg:entity:")?"Entity":n.startsWith("did:dkg:")?"Paranet":n.startsWith("http://schema.org/")?"SchemaNode":n.startsWith("urn:")?"URN":n.startsWith("http://")||n.startsWith("https://")?"IRI":"Other"}function Es(n){if(n.length===0)return[];const o=new Map;for(const d of n)d.predicate===qe&&We(d.object)&&o.set(d.subject,d.object);const i=new Map,g=new Map,a=new Map,c=new Map,v=d=>{const E=i.get(d);if(E)return E;const m=Rs(d,o.get(d));return i.set(d,m),g.has(m)||g.set(m,new Set),g.get(m).add(d),m};for(const d of n){const E=v(d.subject);if(We(d.object)){const m=v(d.object),W=`${E}\0${m}`;c.set(W,(c.get(W)??0)+1)}else a.set(E,(a.get(E)??0)+1)}const C=[];for(const[d,E]of g){const m=`urn:dkg:cluster:${d.toLowerCase()}`;C.push({subject:m,predicate:qe,object:Kt},{subject:m,predicate:ws,object:JSON.stringify(`${d} (${E.size})`)});const W=a.get(d)??0;W>0&&C.push({subject:m,predicate:Is,object:JSON.stringify(String(W))})}for(const[d,E]of c){const[m,W]=d.split("\0"),B=`urn:dkg:cluster:${m.toLowerCase()}`,ue=`urn:dkg:cluster:${W.toLowerCase()}`;C.push({subject:B,predicate:Cs,object:ue}),C.push({subject:B,predicate:`http://dkg.io/ontology/clusterEdgeCount:${W}`,object:JSON.stringify(String(E))})}return C}function Pt(n){if(!n)return n;const o=n.replace(/[<>]/g,"");return o.length<=42?o:`${o.slice(0,24)}...${o.slice(-14)}`}function zs({nodeIds:n,focusRequest:o}){const{viz:i}=bs(),g=s.useMemo(()=>[...n].sort().join("\0"),[n]);return s.useEffect(()=>{if(i)return n.length>0?i.highlightNodes(n):i.clearHighlight(),()=>{i.clearHighlight()}},[i,g,n]),s.useEffect(()=>{!i||!(o!=null&&o.nodeId)||i.centerOnNode(o.nodeId,{durationMs:300,zoomLevel:o.zoomLevel??2.1})},[i,o==null?void 0:o.requestId,o==null?void 0:o.nodeId,o==null?void 0:o.zoomLevel]),null}function Ls(n){const o=new Map;for(const g of n)if(g.predicate===Ut){const a=new Date(g.object);isNaN(a.getTime())||o.set(g.subject,a.getTime())}const i=[...new Set(o.values())].sort((g,a)=>g-a);return{subjectDates:o,timestamps:i}}function Ds(n,o,i){const g=new Set;for(const[a,c]of o)c<=i&&g.add(a);return n.filter(a=>!!(g.has(a.subject)||!o.has(a.subject)))}let Ve=10;function $t(n,o){if(!n||typeof n!="string")return"";const i=n.replace(/\^\^<[^>]+>$/,"").trim().replace(/^"|"$/g,""),g=new Date(i);return Number.isNaN(g.getTime())?i||"":g.toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function At(){return{id:Ve++,role:"assistant",content:"Agent online. Connected to DKG v9 testnet with access to your Knowledge Assets. How can I help?",ts:new Date().toLocaleTimeString()}}function Ps(n){var i;const o=new Map;for(const g of n){if(!(g!=null&&g.session))continue;const a=g.messages.find(B=>B.author==="user"),c=((i=a==null?void 0:a.text)==null?void 0:i.slice(0,60))||"New conversation",v=g.messages[g.messages.length-1],C={id:g.session,preview:c,messageCount:g.messages.length,lastTs:(v==null?void 0:v.ts)??""},d=o.get(C.id);if(!d){o.set(C.id,C);continue}const E=Date.parse(d.lastTs),m=Date.parse(C.lastTs);(Number.isFinite(m)&&Number.isFinite(E)?m>=E:C.lastTs>=d.lastTs)&&o.set(C.id,C)}return[...o.values()].sort((g,a)=>{const c=Date.parse(g.lastTs),v=Date.parse(a.lastTs);return Number.isFinite(c)&&Number.isFinite(v)?v-c:a.lastTs.localeCompare(g.lastTs)})}function Wt(){return{sampleCount:0,deltaApplied:0,fallbackCount:0,medianMs:null,p95Ms:null,lastMode:null,lastReason:null}}function $s(){const[n,o]=s.useState([]),[i,g]=s.useState(null),[a,c]=s.useState([]),[v,C]=s.useState(""),[d,E]=s.useState(!1),[m,W]=s.useState(!0),[B,ue]=s.useState(""),me=s.useRef(null),ie=s.useRef(null);s.useEffect(()=>{var u;(u=me.current)==null||u.scrollIntoView({behavior:"smooth"})},[a]);const I=s.useCallback(async()=>{try{const M=((await gs()).agents??[]).filter(b=>b.connectionStatus!=="self").map(b=>{var O;return{name:b.name??((O=b.peerId)==null?void 0:O.slice(0,12)),peerId:b.peerId,connectionStatus:b.connectionStatus,latencyMs:b.latencyMs,lastSeen:b.lastSeen}});M.sort((b,O)=>b.connectionStatus==="connected"&&O.connectionStatus!=="connected"?-1:O.connectionStatus==="connected"&&b.connectionStatus!=="connected"?1:b.name.localeCompare(O.name)),o(M)}catch{}W(!1)},[]);s.useEffect(()=>{I()},[I]);const oe=s.useCallback(async u=>{try{const M=await fs({peer:u,limit:100});c(M.messages??[])}catch{}},[]),S=s.useCallback(u=>{g(u),c([]),oe(u.peerId)},[oe]);s.useEffect(()=>{if(i)return ie.current=setInterval(()=>oe(i.peerId),4e3),()=>{ie.current&&clearInterval(ie.current)}},[i,oe]);const pe=s.useCallback(async()=>{if(!i||!v.trim()||d)return;const u=v.trim();C(""),E(!0),c(M=>[...M,{ts:Date.now(),direction:"out",peer:i.peerId,text:u}]);try{await xs(i.peerId,u)}catch(M){c(b=>[...b,{ts:Date.now(),direction:"in",peer:"system",text:`Failed to deliver: ${M.message}`}])}finally{E(!1)}},[i,v,d]),w=n.filter(u=>u.connectionStatus==="connected").length,se=300*1e3,D=B.trim().toLowerCase(),J=D?n.reduce((u,M)=>u+(M.name.toLowerCase().includes(D)||M.peerId.toLowerCase().includes(D)?1:0),0):n.length;return e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"260px 1fr",height:"100%",overflow:"hidden"},children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",borderRight:"1px solid var(--border)",background:"var(--bg)",overflow:"hidden"},children:[e.jsxs("div",{style:{padding:"16px 14px 12px",borderBottom:"1px solid var(--border)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between",marginBottom:4},children:[e.jsx("div",{style:{fontSize:12,fontWeight:700},children:"Network Peers"}),D&&e.jsxs("div",{style:{fontSize:10,color:"var(--green)"},children:[J," found"]})]}),e.jsxs("div",{style:{fontSize:10,color:"var(--text-dim)",marginBottom:10},children:[w," connected · ",n.length," discovered"]}),e.jsx("input",{type:"text",value:B,onChange:u=>ue(u.target.value),placeholder:"Search peers…",style:{width:"100%",padding:"7px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-elevated)",color:"var(--text)",fontSize:11,outline:"none",boxSizing:"border-box"},onFocus:u=>{u.target.style.borderColor="var(--green)"},onBlur:u=>{u.target.style.borderColor="var(--border)"}})]}),e.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"8px 10px"},children:[m&&e.jsx("div",{style:{fontSize:11,color:"var(--text-dim)",padding:"12px 6px"},children:"Loading peers…"}),!m&&n.length===0&&e.jsxs("div",{className:"empty-state empty-state--sidebar",children:[e.jsx("div",{className:"empty-state-icon",children:e.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),e.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}),e.jsx("div",{className:"empty-state-title",children:"No peers discovered"}),e.jsx("div",{className:"empty-state-desc",children:"Peers will appear here as your node discovers other agents on the network."})]}),!m&&n.length>0&&J===0&&e.jsxs("div",{style:{fontSize:11,color:"var(--text-dim)",padding:"12px 6px"},children:['No peers match "',B,'"']}),n.map(u=>{const M=!D||u.name.toLowerCase().includes(D)||u.peerId.toLowerCase().includes(D),b=(i==null?void 0:i.peerId)===u.peerId,O=u.connectionStatus==="connected"||u.lastSeen!=null&&Date.now()-u.lastSeen<se;return e.jsxs("div",{onClick:()=>S(u),style:{padding:"10px 12px",borderRadius:8,marginBottom:4,cursor:"pointer",background:b?"var(--surface)":"transparent",border:b?"1px solid var(--border)":"1px solid transparent",transition:"all .15s ease",display:M?void 0:"none"},onMouseEnter:_=>{b||(_.currentTarget.style.background="var(--surface)")},onMouseLeave:_=>{b||(_.currentTarget.style.background="transparent")},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:O?"#10b981":"#6b7280",boxShadow:O?"0 0 6px rgba(16,185,129,.5)":"none"}}),e.jsx("span",{style:{fontSize:12,fontWeight:b?700:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:b?"var(--text)":"var(--text-muted)"},children:u.name})]}),u.latencyMs!=null&&e.jsxs("div",{className:"mono",style:{fontSize:9,color:"var(--text-dim)",marginTop:2,marginLeft:15},children:[u.latencyMs,"ms"]})]},u.peerId)})]}),e.jsx("div",{style:{padding:"10px 14px",borderTop:"1px solid var(--border)",fontSize:10,color:"var(--text-dim)"},children:e.jsx("button",{onClick:I,style:{fontSize:10,color:"var(--text-dim)",background:"none",border:"none",cursor:"pointer",padding:0,textDecoration:"underline",textUnderlineOffset:2},children:"Refresh peers"})})]}),e.jsx("div",{style:{display:"flex",flexDirection:"column",overflow:"hidden"},children:i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{padding:"16px 24px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",gap:12},children:[e.jsx("div",{style:{width:34,height:34,borderRadius:"50%",background:i.connectionStatus==="connected"?"rgba(16,185,129,.12)":"var(--surface)",border:`1px solid ${i.connectionStatus==="connected"?"rgba(16,185,129,.3)":"var(--border)"}`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:14},children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:i.connectionStatus==="connected"?"#10b981":"#6b7280",strokeWidth:"2",children:[e.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:14,fontWeight:700},children:i.name}),e.jsxs("div",{style:{fontSize:11,color:i.connectionStatus==="connected"?"var(--green)":"var(--text-dim)",display:"flex",alignItems:"center",gap:5},children:[e.jsx("span",{style:{width:6,height:6,borderRadius:"50%",display:"inline-block",background:i.connectionStatus==="connected"?"var(--green)":"#6b7280"}}),i.connectionStatus==="connected"?"Connected":"Disconnected",i.latencyMs!=null&&e.jsxs("span",{className:"mono",style:{fontSize:10,color:"var(--text-dim)"},children:["· ",i.latencyMs,"ms"]})]})]}),e.jsxs("div",{className:"mono",style:{marginLeft:"auto",fontSize:9,color:"var(--text-dim)",maxWidth:120,overflow:"hidden",textOverflow:"ellipsis"},children:[i.peerId.slice(0,16),"…"]})]}),e.jsxs("div",{className:"chat-area",style:{flex:1,overflowY:"auto",padding:"20px 24px"},children:[a.length===0&&e.jsxs("div",{className:"empty-state",style:{marginTop:24},children:[e.jsx("div",{className:"empty-state-icon",children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"}),e.jsx("polyline",{points:"22,6 12,13 2,6"})]})}),e.jsx("div",{className:"empty-state-title",children:"No messages yet"}),e.jsx("div",{className:"empty-state-desc",children:"Send a message to start a peer-to-peer conversation."})]}),a.map((u,M)=>e.jsxs("div",{className:`chat-msg ${u.direction==="out"?"user":"assistant"}`,children:[e.jsx("div",{className:`chat-bubble ${u.direction==="out"?"user":"assistant"}`,children:u.text}),e.jsx("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:4,fontFamily:"JetBrains Mono, monospace"},children:new Date(u.ts).toLocaleTimeString()})]},M)),d&&e.jsx("div",{className:"chat-msg user",children:e.jsx("div",{className:"chat-bubble user",style:{display:"flex",gap:4,alignItems:"center",padding:"12px 16px",opacity:.5},children:"Sending…"})}),e.jsx("div",{ref:me})]}),e.jsxs("div",{className:"chat-input-row",children:[e.jsx("input",{className:"chat-input",value:v,onChange:u=>C(u.target.value),onKeyDown:u=>u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),pe()),placeholder:`Message ${i.name}…`}),e.jsx("button",{className:"chat-send",onClick:pe,disabled:d||!v.trim(),children:"Send"})]})]}):e.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:12,color:"var(--text-dim)"},children:[e.jsx("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",opacity:.4,children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),e.jsx("div",{style:{fontSize:13},children:"Select a peer to start chatting"}),e.jsx("div",{style:{fontSize:11},children:"Messages are sent directly over the DKG P2P network"})]})})]})}let Ke=1e3;const Ne="urn:dkg:chat:session:openclaw:dkg-ui",Ot="openclaw:dkg-ui";function Bt(n,o){const i=new Set,g=[];for(const a of[...o,...n]){const c=String(a.id),C=c&&!c.startsWith("oc-")&&!/^\d+$/.test(c)?c:`${a.role}\0${a.ts}\0${a.content}`;i.has(C)||(i.add(C),g.push(a))}return g}function As(){const[n,o]=s.useState([]),[i,g]=s.useState(""),[a,c]=s.useState(!1),[v,C]=s.useState(null),[d,E]=s.useState(0),[m,W]=s.useState(null),[B,ue]=s.useState(null),[me,ie]=s.useState(!1),[I,oe]=s.useState(!1),[S,pe]=s.useState(null),[w,se]=s.useState(!1),[D,J]=s.useState(!1),[u,M]=s.useState(null),[b,O]=s.useState(null),_=s.useRef(null),re=s.useRef(null),G=s.useRef(null),ae=s.useRef(null),ye=s.useRef(null),we=s.useRef(null),K=p=>{p.current&&(clearTimeout(p.current),p.current=null)};s.useEffect(()=>{var p;(p=_.current)==null||p.scrollIntoView({behavior:"smooth"})},[n]),s.useEffect(()=>{if(v==null){E(0);return}E(Math.floor((Date.now()-v)/1e3));const p=setInterval(()=>{E(Math.floor((Date.now()-v)/1e3))},1e3);return()=>clearInterval(p)},[v]),s.useEffect(()=>()=>{var p;(p=re.current)==null||p.abort(),K(ae),K(ye),K(we)},[]),s.useEffect(()=>{let p=!1;const z=async()=>{try{const j=await ys();if(p)return;const V=j.ok;V&&G.current===!1&&(ue(Date.now()),K(ae),ae.current=setTimeout(()=>{ae.current=null,ue(F=>F&&Date.now()-F>=2900?null:F)},3e3),Et(100).then(F=>{if(p)return;const T=F.map($=>({id:$.uri||`oc-history:${Ke++}`,role:$.author.includes("agent")?"assistant":"user",content:$.text,ts:$.ts?new Date($.ts).toLocaleTimeString():""}));T.length>0&&o($=>Bt($,T))}).catch(()=>{})),G.current=V,W(V)}catch{p||(G.current=!1,W(!1))}};z();const P=setInterval(z,15e3);return()=>{p=!0,clearInterval(P)}},[]),s.useEffect(()=>{let p=!1;return(async()=>{try{const z=await Et(100);if(p)return;const P=z.map(j=>({id:j.uri||`oc-history:${Ke++}`,role:j.author.includes("agent")?"assistant":"user",content:j.text,ts:j.ts?new Date(j.ts).toLocaleTimeString():""}));P.length>0&&o(j=>Bt(j,P))}catch{}p||ie(!0)})(),()=>{p=!0}},[]);const le=s.useCallback(async()=>{var p;se(!0);try{const z=`CONSTRUCT { ?s ?p ?o } WHERE {
2
+ {
3
+ SELECT ?s ?p ?o WHERE {
4
+ { <${Ne}> ?p ?o . BIND(<${Ne}> AS ?s) }
5
+ UNION
6
+ { ?s <http://schema.org/isPartOf> <${Ne}> . ?s ?p ?o }
7
+ UNION
8
+ { ?msg <http://schema.org/isPartOf> <${Ne}> .
9
+ ?msg <http://dkg.io/ontology/usedTool> ?tool .
10
+ ?tool ?p ?o . BIND(?tool AS ?s) }
11
+ UNION
12
+ { ?msg <http://schema.org/isPartOf> <${Ne}> .
13
+ ?entity <http://dkg.io/ontology/mentionedIn> ?msg .
14
+ ?entity ?p ?o . BIND(?entity AS ?s) }
15
+ UNION
16
+ { ?msg <http://schema.org/isPartOf> <${Ne}> .
17
+ ?srcEntity <http://dkg.io/ontology/mentionedIn> ?msg .
18
+ ?srcEntity ?rel ?targetEntity .
19
+ FILTER(STRSTARTS(STR(?targetEntity), "urn:dkg:entity:"))
20
+ ?targetEntity ?p ?o . BIND(?targetEntity AS ?s) }
21
+ UNION
22
+ { ?memory <http://dkg.io/ontology/extractedFrom> <${Ne}> .
23
+ ?memory ?p ?o . BIND(?memory AS ?s) }
24
+ UNION
25
+ { ?memory a <http://dkg.io/ontology/ImportedMemory> .
26
+ ?memory ?p ?o . BIND(?memory AS ?s) }
27
+ UNION
28
+ { ?batch a <http://dkg.io/ontology/MemoryImport> .
29
+ ?batch ?p ?o . BIND(?batch AS ?s) }
30
+ UNION
31
+ { ?sessionEntity <http://dkg.io/ontology/extractedFrom> ?batch .
32
+ ?batch a <http://dkg.io/ontology/MemoryImport> .
33
+ ?sessionEntity ?p ?o . BIND(?sessionEntity AS ?s) }
34
+ }
35
+ ORDER BY ?s ?p ?o
36
+ LIMIT 5000
37
+ }
38
+ }`,P=await _t(z,"agent-memory",!0),j=Array.isArray((p=P==null?void 0:P.result)==null?void 0:p.quads)?P.result.quads:[];pe(j.map(V=>({subject:V.subject,predicate:V.predicate,object:ze(V.object)})))}catch{pe(null)}se(!1)},[]);s.useEffect(()=>{I&&le()},[I,le]);const be=s.useCallback(()=>{Gt(Ot).then(p=>{O(p.scope)}).catch(()=>{O(p=>p??"empty")})},[]);s.useEffect(()=>{I&&be()},[I,be]);const ve=s.useCallback(async()=>{if(!D){J(!0),M(null);try{const p=await Promise.race([Ht(Ot,{clearAfter:!1}),new Promise((z,P)=>{setTimeout(()=>P(new Error("Publishing timed out. Please retry.")),45e3)})]);O(p.publication.scope),M(`Published ${p.rootEntityCount} root entities (${p.status})`),await le()}catch(p){M(`Publish failed: ${(p==null?void 0:p.message)??"Unknown error"}`)}finally{J(!1)}}},[D,le]),ne=s.useCallback(async()=>{var V,F;if(!i.trim()||a)return;const p=i.trim();g(""),o(T=>[...T,{id:Ke++,role:"user",content:p,ts:new Date().toLocaleTimeString()}]),c(!0),C(Date.now());const z=new AbortController;re.current=z;const P=setTimeout(()=>z.abort(),9e4),j=Ke++;o(T=>[...T,{id:j,role:"assistant",content:"",ts:new Date().toLocaleTimeString()}]);try{await ms(p,{signal:z.signal,onEvent:T=>{T.type==="text_delta"?o($=>$.map(U=>U.id===j?{...U,content:U.content+T.delta}:U)):T.type==="final"&&o($=>$.map(U=>U.id===j?{...U,content:T.text}:U))}}),I&&(K(ye),K(we),ye.current=setTimeout(()=>{ye.current=null,le()},1500),we.current=setTimeout(()=>{we.current=null,be()},2e3))}catch(T){let $;T.name==="AbortError"?$="Request timed out after 90 seconds. The agent may be overloaded — try again later.":m===!1?$="Agent is offline. Check that the OpenClaw gateway is running.":(V=T.message)!=null&&V.includes("Failed to fetch")||(F=T.message)!=null&&F.includes("NetworkError")?$="Network error — unable to reach the agent. Check your connection.":$=`Error: ${T.message}`,o(U=>U.map(X=>X.id===j?{...X,role:"system",content:$}:X))}finally{clearTimeout(P),re.current=null,c(!1),C(null)}},[i,a,m,I,le,be]),he=m===!0?"#4ade80":m===!1?"#ef4444":"#888",Q=m===!0?"Online":m===!1?"Offline":"Checking…";return e.jsxs("div",{style:{display:"grid",gridTemplateColumns:I?"1fr 1fr":"1fr",height:"100%",overflow:"hidden"},children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",overflow:"hidden"},children:[e.jsxs("div",{style:{padding:"14px 20px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[e.jsx("div",{style:{width:10,height:10,borderRadius:"50%",background:he,boxShadow:m===!0?`0 0 6px ${he}66`:"none"}}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:13,fontWeight:700},children:"OpenClaw Agent"}),e.jsxs("div",{style:{fontSize:10,color:"var(--text-dim)"},children:[B?"Reconnected":Q,e.jsx("span",{style:{marginLeft:8,padding:"1px 6px",borderRadius:4,fontSize:9,background:B?"rgba(34,211,238,.12)":"rgba(74,222,128,.12)",color:B?"#22d3ee":"var(--green)"},children:B?"synced":"DKG UI"})]})]})]}),e.jsxs("button",{onClick:()=>oe(p=>!p),title:I?"Hide graph":"Show knowledge graph",style:{padding:"5px 12px",borderRadius:6,border:I?"1px solid rgba(34,211,238,.5)":"1px solid var(--border)",background:I?"rgba(34,211,238,.1)":"var(--surface)",color:I?"#22d3ee":"var(--text-muted)",fontSize:11,cursor:"pointer",fontWeight:600,display:"flex",alignItems:"center",gap:5,transition:"all .15s ease"},children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[e.jsx("circle",{cx:"6",cy:"6",r:"3"}),e.jsx("circle",{cx:"18",cy:"6",r:"3"}),e.jsx("circle",{cx:"12",cy:"18",r:"3"}),e.jsx("line",{x1:"8.5",y1:"7.5",x2:"10.5",y2:"16"}),e.jsx("line",{x1:"15.5",y1:"7.5",x2:"13.5",y2:"16"})]}),I?"Hide Graph":"Show Graph"]})]}),e.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"20px 20px 8px"},children:[!me&&e.jsx("div",{style:{textAlign:"center",color:"var(--text-dim)",fontSize:12,padding:20},children:"Loading history…"}),me&&n.length===0&&e.jsxs("div",{style:{textAlign:"center",color:"var(--text-dim)",padding:"40px 20px"},children:[e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",style:{opacity:.3,marginBottom:12},children:[e.jsx("path",{d:"M12 2L2 7l10 5 10-5-10-5z"}),e.jsx("path",{d:"M2 17l10 5 10-5"}),e.jsx("path",{d:"M2 12l10 5 10-5"})]}),e.jsx("div",{style:{fontSize:13},children:"Send a message to start chatting with your OpenClaw agent."}),e.jsx("div",{style:{fontSize:11,marginTop:8},children:"Messages and imported memories are persisted to the DKG knowledge graph."})]}),n.map(p=>e.jsx("div",{style:{marginBottom:16,display:"flex",justifyContent:p.role==="user"?"flex-end":"flex-start"},children:e.jsxs("div",{style:{maxWidth:"75%",padding:"10px 14px",borderRadius:12,background:p.role==="user"?"rgba(74,222,128,.15)":p.role==="system"?"rgba(255,255,255,.04)":"rgba(255,255,255,.06)",border:p.role==="system"?"1px solid rgba(255,255,255,.08)":"none",fontSize:13,lineHeight:"1.5",whiteSpace:"pre-wrap",color:p.role==="system"?"var(--text-dim)":"var(--text)",fontStyle:p.role==="system"?"italic":"normal"},children:[p.content,e.jsx("div",{style:{fontSize:9,color:"var(--text-dim)",marginTop:4},children:p.ts})]})},p.id)),a&&e.jsx("div",{style:{display:"flex",justifyContent:"flex-start",marginBottom:16},children:e.jsxs("div",{style:{padding:"10px 14px",borderRadius:12,background:"rgba(255,255,255,.06)",fontSize:13,color:"var(--text-dim)"},children:["Thinking",d>0?`… ${d}s`:"…"]})}),e.jsx("div",{ref:_})]}),e.jsxs("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)",display:"flex",gap:8},children:[e.jsx("input",{value:i,onChange:p=>g(p.target.value),onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),ne())},placeholder:"Message your OpenClaw agent…",disabled:a||m===!1,style:{flex:1,padding:"10px 14px",borderRadius:10,border:"1px solid var(--border)",background:"var(--bg-elevated)",color:"var(--text)",fontSize:13,outline:"none"}}),e.jsx("button",{onClick:ne,disabled:a||!i.trim()||m===!1,style:{padding:"10px 20px",borderRadius:10,border:"none",background:a||!i.trim()||m===!1?"rgba(74,222,128,.2)":"var(--green)",color:a||!i.trim()||m===!1?"var(--text-dim)":"#000",fontWeight:700,fontSize:12,cursor:a?"wait":"pointer"},children:"Send"})]})]}),I&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",borderLeft:"1px solid var(--border)",overflow:"hidden"},children:[e.jsxs("div",{style:{padding:"10px 16px",borderBottom:"1px solid var(--border)",display:"grid",gap:8},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{fontSize:12,fontWeight:700},children:"Knowledge Graph"}),S&&e.jsxs("span",{style:{fontSize:10,color:"var(--text-dim)"},children:[S.length," triples"]}),e.jsx("span",{className:"mono",style:{borderRadius:999,border:b==="enshrined"?"1px solid rgba(74,222,128,.3)":b==="enshrined_with_pending"?"1px solid rgba(245,158,11,.35)":"1px solid var(--border)",background:b==="enshrined"?"rgba(74,222,128,.1)":b==="enshrined_with_pending"?"rgba(245,158,11,.12)":"var(--surface)",color:b==="enshrined"?"var(--green)":b==="enshrined_with_pending"?"#f59e0b":"var(--text-dim)",padding:"2px 8px",fontSize:10},children:b==="enshrined"?"enshrined":b==="enshrined_with_pending"?"enshrined + pending":b==="workspace_only"?"workspace only":b?"empty":"checking..."})]}),e.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[e.jsx("button",{onClick:le,disabled:w,style:{padding:"4px 10px",borderRadius:6,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",fontSize:10,cursor:"pointer"},children:w?"Loading…":"Refresh"}),e.jsx("button",{onClick:()=>{ve()},disabled:D,style:{padding:"4px 10px",borderRadius:6,border:"1px solid rgba(74,222,128,.35)",background:"rgba(74,222,128,.1)",color:"var(--green)",fontSize:10,cursor:D?"not-allowed":"pointer",opacity:D?.65:1},children:D?"Publishing…":"Publish session"})]})]}),u&&e.jsx("div",{className:"mono",style:{fontSize:10,color:u.toLowerCase().includes("failed")?"var(--red)":"var(--green)"},children:u}),e.jsx("div",{className:"mono",style:{fontSize:10,color:"var(--text-dim)",lineHeight:1.5},children:"Publish session enshrines the OpenClaw conversation currently in view on the DKG privately. New writes remain in workspace until you publish again."})]}),e.jsxs("div",{style:{flex:1,minHeight:0,position:"relative"},children:[w&&!S&&e.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:"Loading graph…"}),S&&S.length===0&&e.jsxs("div",{className:"empty-state",style:{position:"absolute",inset:0},children:[e.jsx("div",{className:"empty-state-icon",children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"3"}),e.jsx("circle",{cx:"19",cy:"5",r:"2"}),e.jsx("circle",{cx:"5",cy:"19",r:"2"}),e.jsx("line",{x1:"14.5",y1:"9.5",x2:"17.5",y2:"6.5"}),e.jsx("line",{x1:"9.5",y1:"14.5",x2:"6.5",y2:"17.5"})]})}),e.jsx("div",{className:"empty-state-title",children:"No graph data yet"}),e.jsx("div",{className:"empty-state-desc",children:"Send some messages first. The knowledge graph builds as you converse."})]}),S&&S.length>0&&e.jsx(Ft,{data:S,format:"triples",options:{labelMode:"humanized",renderer:"2d",labels:{predicates:["http://schema.org/text","http://schema.org/name","http://www.w3.org/2000/01/rdf-schema#label","http://dkg.io/ontology/sessionId","http://dkg.io/ontology/toolName"]},style:{classColors:{"http://schema.org/Conversation":"#4ade80","http://schema.org/Message":"#22d3ee","http://dkg.io/ontology/ChatTurn":"#38bdf8","http://dkg.io/ontology/ToolInvocation":"#f59e0b","http://dkg.io/ontology/ImportedMemory":"#a78bfa","http://dkg.io/ontology/MemoryImport":"#818cf8","http://schema.org/Person":"#f472b6","http://schema.org/Organization":"#fb923c","http://schema.org/Place":"#34d399","http://schema.org/Product":"#c084fc","http://schema.org/Event":"#facc15","http://schema.org/CreativeWork":"#7dd3fc"},defaultNodeColor:"#94a3b8",defaultEdgeColor:"#5f8598",edgeWidth:.9},hexagon:{baseSize:4,minSize:3,maxSize:6,scaleWithDegree:!0,circleTypes:["http://schema.org/Message"]},focus:{maxNodes:5e3,hops:999}},style:{width:"100%",height:"100%"}})]})]})]})}function Gs(){const[n,o]=s.useState("agent"),[i,g]=s.useState(null);s.useEffect(()=>{let t=!1;return as().then(r=>{t||g(r)}).catch(()=>{}),()=>{t=!0}},[]),s.useEffect(()=>{i!=null&&i.hasOpenClawChannel&&o(t=>t==="agent"?"openclaw":t)},[i]);const[a,c]=s.useState([At()]),[v,C]=s.useState(""),[d,E]=s.useState(!1),[m,W]=s.useState(null),[B,ue]=s.useState([]),[me,ie]=s.useState(!0),[I,oe]=s.useState(null),[S,pe]=s.useState(!1),[w,se]=s.useState(null),[D,J]=s.useState(!1),[u,M]=s.useState(null),[b,O]=s.useState(1500),[_,re]=s.useState(!1),[G,ae]=s.useState("raw"),[ye,we]=s.useState({}),[K,le]=s.useState(null),[be,ve]=s.useState(null),[ne,he]=s.useState(!1),[Q,p]=s.useState(!1),[z,P]=s.useState(null),[j,V]=s.useState("timestamp"),[F,T]=s.useState(!1),[$,U]=s.useState(""),[X,Le]=s.useState(null),[Z,je]=s.useState(null),[Vt,De]=s.useState(null),[Pe,qt]=s.useState(typeof window<"u"?window.innerWidth<1180:!1),[H,Je]=s.useState(null),[,ut]=s.useState(()=>Wt()),Qe=s.useRef(null),Me=s.useRef(!0),Xe=s.useRef(null),Ze=s.useRef(new Map),et=s.useRef(null),ge=s.useRef(0),Oe=s.useRef(0),Be=s.useRef(S),ke=s.useRef(u),Te=s.useRef(I),Re=s.useRef(m),pt=s.useRef(d),ht=s.useRef(_),gt=s.useRef(0),ft=s.useRef(new Map),tt=s.useRef(new Map),fe=s.useRef(new Map),$e=s.useRef(new Map),xt=s.useRef([]),mt=s.useRef(async()=>{});s.useEffect(()=>{Be.current=S},[S]),s.useEffect(()=>{ke.current=u},[u]),s.useEffect(()=>{Te.current=I},[I]),s.useEffect(()=>{Re.current=m},[m]),s.useEffect(()=>{pt.current=d},[d]),s.useEffect(()=>{ht.current=_},[_]),s.useEffect(()=>{et.current=w},[w]),s.useEffect(()=>{const t=()=>qt(window.innerWidth<1180);return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[]),s.useEffect(()=>{const t=Qe.current;t&&Me.current&&(t.scrollTop=t.scrollHeight)},[a,d]);const Yt=s.useCallback(()=>{const t=Qe.current;if(!t)return;const r=t.scrollHeight-t.scrollTop-t.clientHeight;Me.current=r<80},[]);s.useEffect(()=>{const t=new Map;for(const r of a)r.turnId&&t.set(r.turnId,r.id);tt.current=t},[a]),s.useEffect(()=>{const t=I??m;t&&ft.current.set(t,a.map(r=>({...r})))},[a,I,m]);const Se=s.useCallback(()=>{xt.current=[],ut(Wt())},[]),yt=s.useCallback((t,r,l)=>{const h=Math.max(0,Number.isFinite(r)?r:0),x=xt.current;x.push(h),x.length>128&&x.splice(0,x.length-128);const f=Dt(x,.5),k=Dt(x,.95);ut(R=>({sampleCount:x.length,deltaApplied:R.deltaApplied+(t==="delta"?1:0),fallbackCount:R.fallbackCount+(t==="fallback"?1:0),medianMs:f,p95Ms:k,lastMode:t,lastReason:t==="fallback"?l??null:null}))},[]),Ee=s.useCallback(async()=>{ie(!0);try{const r=((await ls(50)).sessions??[]).filter(l=>{var h;return!((h=l.session)!=null&&h.startsWith("openclaw:"))});ue(Ps(r))}catch{ue([])}finally{ie(!1)}},[]);s.useEffect(()=>{Ee()},[Ee]);const Ge=s.useCallback(async t=>{try{const r=await Gt(t);we(h=>({...h,[t]:r})),(Te.current??Re.current)===t&&r.scope==="enshrined"&&c(h=>dt(h))}catch{}},[]),_e=s.useCallback(t=>{const r=tt.current.get(t.turnId),l=Te.current??Re.current;c(h=>{let x=!1;const f=h.map(k=>{var Y,L;if(k.turnId!==t.turnId)return k;x=!0;const R=t.storeMs??((Y=k.timings)==null?void 0:Y.store_ms)??0,Ce=(((L=k.timings)==null?void 0:L.llm_ms)??0)+R;return{...k,persistStatus:k.persistStatus==="enshrined"&&t.status==="stored"?"enshrined":t.status,persistError:t.error,persistAttempts:t.attempts,persistMaxAttempts:t.maxAttempts,timings:k.timings?{...k.timings,store_ms:R,total_ms:Ce}:k.timings}});if(!x){if((pt.current||!!l&&t.sessionId===l)&&(fe.current.set(t.turnId,t),fe.current.size>128)){const R=fe.current.keys().next().value;R&&fe.current.delete(R)}return h}return fe.current.delete(t.turnId),f}),t.status==="stored"&&Be.current&&t.sessionId&&mt.current(t.sessionId,t.turnId,{linkedMessageId:r,linkedTurnId:r==null?t.turnId:void 0})},[]);s.useEffect(()=>{let t=!1,r=null;const l=async()=>{try{const f=await ps();t||Je(f)}catch{t||Je(null)}},h=async()=>{for(;!t;){r=new AbortController;try{await hs({signal:r.signal,onEvent:f=>{if(!t){if(f.type==="persist_health"){Je({pending:f.pending,inProgress:f.inProgress,stored:f.stored,failed:f.failed,overduePending:f.overduePending,oldestPendingAgeMs:f.oldestPendingAgeMs});return}_e(f)}}})}catch{if(t||r.signal.aborted)break}if(t)break;await new Promise(f=>setTimeout(f,1500))}};l(),h();const x=setInterval(()=>{l()},2e4);return()=>{t=!0,r&&r.abort(),clearInterval(x)}},[_e]);const bt=s.useCallback((t,r)=>{c(l=>l.map(h=>h.id===t?{...h,graphDiff:r}:h))},[]),ee=s.useCallback(async(t,r)=>{var h;const l=++ge.current;J(!0),M(t);try{const x=`urn:dkg:chat:session:${t}`,f=Math.max(500,Math.min((r==null?void 0:r.limitOverride)??b,15e3)),k=f+1,R=`CONSTRUCT { ?s ?p ?o } WHERE {
39
+ {
40
+ SELECT ?s ?p ?o WHERE {
41
+ { <${x}> ?p ?o . BIND(<${x}> AS ?s) }
42
+ UNION
43
+ { ?s <http://schema.org/isPartOf> <${x}> . ?s ?p ?o }
44
+ UNION
45
+ { ?msg <http://schema.org/isPartOf> <${x}> .
46
+ ?msg <http://dkg.io/ontology/usedTool> ?tool .
47
+ ?tool ?p ?o . BIND(?tool AS ?s) }
48
+ UNION
49
+ { ?msg <http://schema.org/isPartOf> <${x}> .
50
+ ?entity <http://dkg.io/ontology/mentionedIn> ?msg .
51
+ ?entity ?p ?o . BIND(?entity AS ?s) }
52
+ UNION
53
+ { ?msg <http://schema.org/isPartOf> <${x}> .
54
+ ?srcEntity <http://dkg.io/ontology/mentionedIn> ?msg .
55
+ ?srcEntity ?rel ?targetEntity .
56
+ FILTER(STRSTARTS(STR(?targetEntity), "urn:dkg:entity:"))
57
+ ?targetEntity ?p ?o . BIND(?targetEntity AS ?s) }
58
+ UNION
59
+ { ?memory <http://dkg.io/ontology/extractedFrom> <${x}> .
60
+ ?memory ?p ?o . BIND(?memory AS ?s) }
61
+ }
62
+ ORDER BY ?s ?p ?o
63
+ LIMIT ${k}
64
+ }
65
+ }`,A=await _t(R,"agent-memory",!0),Y=(Array.isArray((h=A==null?void 0:A.result)==null?void 0:h.quads)?A.result.quads:[]).map(ce=>({subject:ce.subject,predicate:ce.predicate,object:ze(ce.object)})),L=Y.length>f,te=L?Y.slice(0,f):Y;if(ge.current!==l)return;O(f),re(L);const Ie=Ye(te);je(ce=>ce&&Ie.has(ce)?ce:null),$e.current.set(t,Ts(te)),se(te)}catch{if(ge.current!==l)return;$e.current.set(t,null),re(!1),se([])}finally{ge.current===l&&J(!1)}},[b]),st=s.useCallback(async(t,r,l)=>{const h=performance.now(),x=(L,te)=>{yt(L,performance.now()-h,te)},f=ke.current,k=Te.current??Re.current;if((f??k)!==t)return;const A=et.current;if(!A||ht.current){await ee(t),x("fallback",A?"partial_graph_snapshot":"missing_graph_snapshot");return}const Ce=ge.current,Y=$e.current.get(t)??null;try{const L=await ds(t,r,{baseTurnId:Y});if(ge.current!==Ce||ke.current&&ke.current!==t)return;if(L.mode!=="delta"){await ee(t),x("fallback",L.reason??"full_refresh_required");return}const te=(L.triples??[]).map(lt=>({subject:lt.subject,predicate:lt.predicate,object:ze(lt.object)})),Ie=et.current??[],ce=Ms(Ie,te);let Ue=l==null?void 0:l.linkedMessageId;Ue==null&&(l!=null&&l.linkedTurnId)&&(Ue=tt.current.get(l.linkedTurnId)),Ue!=null&&bt(Ue,Ns(Ie,ce)),$e.current.set(t,L.watermark.appliedTurnId??L.watermark.latestTurnId??r),M(t),re(!1),se(ce),x("delta")}catch{await ee(t),x("fallback","delta_request_error")}},[bt,ee,yt]);mt.current=st;const rt=s.useCallback(async t=>{pe(!0),he(!1),P(null),T(!1),ae("raw"),O(1500),ve(null),Se(),await Promise.all([ee(t,{limitOverride:1500}),Ge(t)])},[ee,Ge,Se]),vt=s.useCallback(()=>{if(S){ge.current+=1,pe(!1),he(!1),J(!1),T(!1),ve(null),re(!1),De(null);return}const t=I??m;if(!t){Se(),pe(!0),he(!1),se([]),M(null),J(!1),re(!1),De(null);return}rt(t)},[S,I,m,rt,Se]),St=s.useCallback(async()=>{const t=v.trim();if(!t||d)return;C("");const r={id:Ve++,role:"user",content:t,ts:new Date().toLocaleTimeString()},l=Ve++,h=new Date().toLocaleTimeString();c(x=>[...x,r,{id:l,role:"assistant",content:"",ts:h,responseMode:"streaming"}]),E(!0),Me.current=!0;try{const x=await cs(t,{sessionId:m??void 0,onEvent:f=>{if(f.type==="text_delta"){c(k=>k.map(R=>R.id===l?{...R,content:`${R.content}${f.delta}`}:R));return}if(f.type==="final"){if(c(k=>k.map(R=>R.id===l?{...R,content:f.reply||R.content,data:f.data,sparql:f.sparql,turnId:f.turnId,persistStatus:f.persistStatus,persistError:f.persistError,timings:f.timings,responseMode:f.responseMode,llmDiagnostics:f.llmDiagnostics}:R)),f.turnId){const k=fe.current.get(f.turnId);k&&(fe.current.delete(f.turnId),_e(k))}Be.current&&f.sessionId&&f.persistStatus==="stored"&&f.turnId&&st(f.sessionId,f.turnId,{linkedMessageId:l})}}});x.sessionId&&(W(x.sessionId),oe(x.sessionId)),Ee()}catch(x){c(f=>f.map(k=>k.id===l?{...k,content:`Error: ${x.message}`,responseMode:"blocking"}:k))}finally{E(!1)}},[v,d,m,Ee,_e,st]),Jt=s.useCallback(()=>{d||(Oe.current+=1,ge.current+=1,fe.current.clear(),$e.current.clear(),Se(),W(null),oe(null),c([At()]),C(""),se(null),M(null),J(!1),O(1500),re(!1),ae("raw"),he(!1),ve(null),Le(null),je(null),De(null),U(""),P(null),T(!1),he(!1),Me.current=!0)},[d,Se]),Qt=s.useCallback(async t=>{var l;if(d||t===I)return;const r=++Oe.current;fe.current.clear(),Se(),ie(!0),P(null),T(!1),Me.current=!0,Le(null),je(null),De(null),U("");try{const h=await us(t);if(Oe.current!==r||!((l=h==null?void 0:h.messages)!=null&&l.length))return;const x=ft.current.get(t)??[],f=new Map;for(const A of x)A.turnId&&f.set(A.turnId,A);const k=h.messages.map(A=>{var Ie;const Ce=A.author==="user"?"user":"assistant",Y=((Ie=A.turnId)==null?void 0:Ie.trim())||void 0,L=Y?f.get(Y):void 0;let te=vs(A.persistStatus);return(L==null?void 0:L.persistStatus)==="enshrined"&&(te="enshrined"),!te&&Ce==="assistant"&&Y&&(te="stored"),{id:Ve++,role:Ce,content:A.text,ts:A.ts?$t(A.ts)||new Date(A.ts).toLocaleTimeString():"",turnId:Y,persistStatus:te,graphDiff:L==null?void 0:L.graphDiff,llmDiagnostics:L==null?void 0:L.llmDiagnostics}}),R=ye[t];c((R==null?void 0:R.scope)==="enshrined"?dt(k):k),W(t),oe(t),S?(ae("raw"),O(1500),await Promise.all([ee(t,{limitOverride:1500}),Ge(t)])):(ge.current+=1,se(null),M(null),J(!1),re(!1))}catch{}finally{Oe.current===r&&ie(!1)}},[d,I,S,ee,Ge,Se,ye]),y=s.useMemo(()=>!w||w.length===0?null:Ls(w),[w]),wt=s.useMemo(()=>{if(!y||y.timestamps.length===0)return 0;const t=z??y.timestamps[y.timestamps.length-1];let r=0;for(let l=0;l<y.timestamps.length&&y.timestamps[l]<=t;l+=1)r=l;return r},[y,z]),jt=s.useMemo(()=>!w||!y||z===null?w:Ds(w,y.subjectDates,z),[w,y,z]);s.useEffect(()=>{y&&y.timestamps.length>0&&z===null&&P(y.timestamps[y.timestamps.length-1])},[y,z]),s.useEffect(()=>{if(!F||!y||y.timestamps.length<2)return;const t=y.timestamps;return Xe.current=setInterval(()=>{P(r=>{const l=t.findIndex(h=>h>(r??0));return l===-1||l>=t.length?(T(!1),t[t.length-1]):t[l]})},600),()=>{Xe.current&&clearInterval(Xe.current)}},[F,y]);const nt=s.useMemo(()=>{const t=new Map;if(!w||w.length===0)return t;for(const r of w){if(r.predicate!==Ss)continue;const l=zt(ze(r.object));l&&(t.has(l)||t.set(l,new Set),t.get(l).add(r.subject))}return t},[w]),Ae=s.useMemo(()=>{const t=new Map;if(nt.size===0)return t;for(const r of a){const l=zt(r.content);if(!l)continue;const h=nt.get(l);h&&h.size>0&&t.set(r.id,[...h])}return t},[a,nt]),He=s.useMemo(()=>{const t=new Map;for(const[r,l]of Ae)for(const h of l)t.set(h,r);return t},[Ae]),xe=s.useMemo(()=>{const t=jt??w;return t&&(G==="clustered"?Es(t):t)},[jt,w,G]),Xt=s.useMemo(()=>{if(G!=="clustered"||!xe)return 0;const t=new Set;for(const r of xe)r.predicate===qe&&r.object===Kt&&t.add(r.subject);return t.size},[G,xe]),Fe=s.useMemo(()=>{const t=$.trim().toLowerCase(),r=xe;if(!t||!r)return[];const l=new Set;for(const h of r)(h.subject.toLowerCase().includes(t)||h.predicate.toLowerCase().includes(t)||h.object.toLowerCase().includes(t))&&(l.add(h.subject),We(h.object)&&l.add(h.object));return[...l]},[xe,$]),Zt=s.useMemo(()=>{const t=new Set;if(X!=null)for(const r of Ae.get(X)??[])t.add(r);for(const r of Fe)t.add(r);return Z&&t.add(Z),[...t]},[X,Ae,Fe,Z]),kt=s.useMemo(()=>[...a].reverse().find(t=>t.role==="assistant"&&t.graphDiff),[a]),q=s.useMemo(()=>{if(X!=null){const t=a.find(r=>r.id===X&&r.role==="assistant"&&r.graphDiff);if(t!=null&&t.graphDiff)return t}return kt??null},[a,X,kt]),Ct=s.useCallback(t=>{const r=Ze.current.get(t);r&&(Me.current=!1,r.scrollIntoView({behavior:"smooth",block:"center"}))},[]),It=s.useCallback((t,r=2.1)=>{gt.current+=1,De({nodeId:t,requestId:gt.current,zoomLevel:r})},[]),es=s.useCallback(t=>{je(t.id);const r=He.get(t.id);r!=null&&Le(r)},[He]),ts=s.useMemo(()=>({name:"Conversation",palette:"dark",paletteOverrides:{edgeColor:"#5f8598",particleColor:"rgba(34, 211, 238, 0.5)"}}),[]),Nt=s.useMemo(()=>!w||w.length===0?new Set:Ye(w),[w]),de=I??m??u,N=de?ye[de]??null:null,ss=s.useMemo(()=>N?N.scope==="enshrined"?"enshrined":N.scope==="enshrined_with_pending"?"enshrined + pending":N.scope==="workspace_only"?"workspace only":"empty":de?"checking...":"no session",[de,N]),Mt=!!K&&!!de&&K===de,Tt=!!K&&!!de&&K!==de,it=!u||Mt||Tt,ot=be&&de&&be.sessionId===de?be.text:null;s.useEffect(()=>{G==="raw"&&Z&&(Nt.has(Z)||je(null))},[G,Nt,Z]);const rs=s.useCallback(()=>{const t=ke.current;if(!t||D)return;const r=Math.min(b+1500,15e3);ee(t,{limitOverride:r})},[ee,b,D]),ns=s.useCallback(async()=>{const t=ke.current??Te.current??Re.current;if(!(!t||K!=null)){le(t),ve(null);try{const r=await Promise.race([Ht(t,{clearAfter:!1}),new Promise((h,x)=>{setTimeout(()=>x(new Error("Publishing timed out. Please retry.")),45e3)})]);we(h=>({...h,[t]:r.publication})),(Te.current??Re.current)===t&&r.publication.scope==="enshrined"&&c(h=>dt(h)),ve({sessionId:t,text:`Published ${r.rootEntityCount} root entities (${r.status})`}),Be.current&&ke.current===t&&await ee(t),await Ee()}catch(r){ve({sessionId:t,text:`Publish failed: ${(r==null?void 0:r.message)??"Unknown error"}`})}finally{le(r=>r===t?null:r)}}},[ee,K,Ee]),Rt=e.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",minHeight:0,background:"var(--bg)"},children:[e.jsxs("div",{style:{padding:"10px 12px",borderBottom:"1px solid var(--border)",display:"grid",gap:8},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",fontSize:11,color:"var(--text-muted)"},children:[e.jsx("span",{children:G==="clustered"?`${Xt} clusters`:`${(xe==null?void 0:xe.length)??0} triples`}),Fe.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{style:{color:"var(--text-dim)"},children:"."}),e.jsxs("span",{children:[Fe.length," highlighted nodes"]})]}),e.jsx("span",{style:{color:"var(--text-dim)"},children:"."}),e.jsx("span",{className:"mono",style:{borderRadius:999,border:(N==null?void 0:N.scope)==="enshrined"?"1px solid rgba(74,222,128,.3)":(N==null?void 0:N.scope)==="enshrined_with_pending"?"1px solid rgba(245,158,11,.35)":"1px solid var(--border)",background:(N==null?void 0:N.scope)==="enshrined"?"rgba(74,222,128,.1)":(N==null?void 0:N.scope)==="enshrined_with_pending"?"rgba(245,158,11,.12)":"var(--surface)",color:(N==null?void 0:N.scope)==="enshrined"?"var(--green)":(N==null?void 0:N.scope)==="enshrined_with_pending"?"#f59e0b":"var(--text-dim)",padding:"2px 8px",fontSize:10},title:`workspace triples: ${(N==null?void 0:N.workspaceTripleCount)??0}, data triples: ${(N==null?void 0:N.dataTripleCount)??0}`,children:ss}),u&&e.jsxs(e.Fragment,{children:[e.jsx("span",{style:{color:"var(--text-dim)"},children:"."}),e.jsxs("span",{className:"mono",title:u,children:["session ",u.slice(0,10)]})]})]}),e.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[e.jsx("input",{value:$,onChange:t=>U(t.target.value),placeholder:"Search graph nodes, predicates, values",style:{flex:1,minWidth:0,borderRadius:8,border:"1px solid var(--border)",background:"var(--surface)",color:"var(--text)",padding:"7px 10px",fontSize:11}}),$&&e.jsx("button",{onClick:()=>U(""),style:{borderRadius:7,border:"1px solid var(--border)",background:"var(--surface)",color:"var(--text-muted)",padding:"6px 8px",fontSize:10,cursor:"pointer"},children:"Clear"})]}),e.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[e.jsx("button",{onClick:()=>ae("raw"),style:{borderRadius:7,border:G==="raw"?"1px solid rgba(34,211,238,.35)":"1px solid var(--border)",background:G==="raw"?"rgba(34,211,238,.1)":"var(--surface)",color:G==="raw"?"#22d3ee":"var(--text-muted)",padding:"5px 9px",fontSize:10,cursor:"pointer"},children:"Raw"}),e.jsx("button",{onClick:()=>ae("clustered"),style:{borderRadius:7,border:G==="clustered"?"1px solid rgba(34,211,238,.35)":"1px solid var(--border)",background:G==="clustered"?"rgba(34,211,238,.1)":"var(--surface)",color:G==="clustered"?"#22d3ee":"var(--text-muted)",padding:"5px 9px",fontSize:10,cursor:"pointer"},children:"Clustered"}),e.jsx("button",{onClick:rs,disabled:!_||D,style:{borderRadius:7,border:"1px solid var(--border)",background:"var(--surface)",color:_?"var(--text-muted)":"var(--text-dim)",padding:"5px 9px",fontSize:10,cursor:_?"pointer":"not-allowed",opacity:_?1:.65},title:_?`Load more triples (current limit ${b})`:"All currently loaded triples are shown",children:_?"Load more":"Fully loaded"}),e.jsx("button",{onClick:()=>{ns()},disabled:it,title:Tt?"Another session is currently publishing":void 0,style:{marginLeft:"auto",borderRadius:7,border:"1px solid rgba(74,222,128,.35)",background:"rgba(74,222,128,.1)",color:"var(--green)",padding:"5px 9px",fontSize:10,cursor:it?"not-allowed":"pointer",opacity:it?.65:1},children:Mt?"Publishing...":"Publish session"})]}),ot&&e.jsx("div",{className:"mono",style:{fontSize:10,color:ot.toLowerCase().includes("failed")?"var(--red)":"var(--green)"},children:ot}),e.jsx("div",{className:"mono",style:{fontSize:10,color:"var(--text-dim)",lineHeight:1.5},children:"Publish session enshrines the agent conversation currently in view on the DKG privately. New writes remain in workspace until you publish again."})]}),e.jsxs("div",{style:{flex:1,minHeight:0,position:"relative"},children:[D&&e.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)"},children:"Loading graph..."}),!D&&w==null&&e.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12,textAlign:"center",padding:20},children:"Open a conversation graph to see node growth while you chat."}),!D&&w&&w.length===0&&e.jsxs("div",{className:"empty-state",style:{position:"absolute",inset:0},children:[e.jsx("div",{className:"empty-state-icon",children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"3"}),e.jsx("circle",{cx:"19",cy:"5",r:"2"}),e.jsx("circle",{cx:"5",cy:"19",r:"2"}),e.jsx("line",{x1:"14.5",y1:"9.5",x2:"17.5",y2:"6.5"}),e.jsx("line",{x1:"9.5",y1:"14.5",x2:"6.5",y2:"17.5"})]})}),e.jsx("div",{className:"empty-state-title",children:"No triples yet"}),e.jsx("div",{className:"empty-state-desc",children:"Memory graph triples will appear here as data is stored."})]}),!D&&w&&w.length>0&&e.jsx(Ft,{data:xe??w,format:"triples",options:{labelMode:"humanized",renderer:"2d",labels:{predicates:["http://schema.org/text","http://schema.org/name","http://www.w3.org/2000/01/rdf-schema#label","http://dkg.io/ontology/sessionId","http://dkg.io/ontology/toolName"]},style:{classColors:{"http://schema.org/Conversation":"#4ade80","http://schema.org/Message":"#22d3ee","http://dkg.io/ontology/ToolInvocation":"#f59e0b","http://dkg.io/ontology/GraphCluster":"#a78bfa","http://schema.org/Person":"#f472b6","http://schema.org/Organization":"#fb923c","http://schema.org/Place":"#34d399","http://schema.org/Product":"#c084fc","http://schema.org/Event":"#facc15","http://schema.org/CreativeWork":"#7dd3fc"},defaultNodeColor:"#94a3b8",defaultEdgeColor:"#5f8598",edgeWidth:.9},hexagon:{baseSize:4,minSize:3,maxSize:6,scaleWithDegree:!0,circleTypes:["http://schema.org/Message"]},focus:{maxNodes:5e3,hops:999}},viewConfig:ts,style:{width:"100%",height:"100%"},onNodeClick:es,children:e.jsx(zs,{nodeIds:Zt,focusRequest:Vt})})]}),y&&y.timestamps.length>1&&e.jsxs("div",{style:{padding:"10px 12px",borderTop:"1px solid var(--border)",display:"grid",gap:8,background:"var(--bg)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("button",{onClick:()=>{F?T(!1):(z!==null&&z>=y.timestamps[y.timestamps.length-1]&&P(y.timestamps[0]),T(!0))},style:{width:28,height:28,borderRadius:"50%",border:"1px solid rgba(34,211,238,.3)",background:F?"rgba(34,211,238,.15)":"var(--surface)",color:"#22d3ee",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,flexShrink:0},title:F?"Pause timeline":"Play timeline",children:F?"||":">"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("button",{onClick:()=>V("timestamp"),style:{borderRadius:6,border:j==="timestamp"?"1px solid rgba(34,211,238,.35)":"1px solid var(--border)",background:j==="timestamp"?"rgba(34,211,238,.12)":"var(--surface)",color:j==="timestamp"?"#22d3ee":"var(--text-muted)",padding:"5px 8px",fontSize:10,cursor:"pointer"},children:"Timestamp"}),e.jsx("button",{onClick:()=>V("turn"),style:{borderRadius:6,border:j==="turn"?"1px solid rgba(34,211,238,.35)":"1px solid var(--border)",background:j==="turn"?"rgba(34,211,238,.12)":"var(--surface)",color:j==="turn"?"#22d3ee":"var(--text-muted)",padding:"5px 8px",fontSize:10,cursor:"pointer"},children:"Turn"})]}),e.jsx("div",{className:"mono",style:{marginLeft:"auto",fontSize:10,color:"var(--text-dim)"},children:j==="turn"?`Turn ${wt+1}/${y.timestamps.length}`:`At ${new Date(z??y.timestamps[y.timestamps.length-1]).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("div",{className:"mono",style:{fontSize:10,color:"var(--text-dim)",minWidth:56},children:j==="turn"?"Turn 1":new Date(y.timestamps[0]).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}),e.jsx("input",{type:"range",min:j==="turn"?0:y.timestamps[0],max:j==="turn"?y.timestamps.length-1:y.timestamps[y.timestamps.length-1],step:j==="turn"?1:void 0,value:j==="turn"?wt:z??y.timestamps[y.timestamps.length-1],onChange:t=>{const r=Number(t.target.value);if(T(!1),j==="turn"){const l=Math.max(0,Math.min(y.timestamps.length-1,r));P(y.timestamps[l]);return}P(r)},style:{flex:1,accentColor:"#22d3ee",cursor:"pointer"}}),e.jsx("div",{className:"mono",style:{fontSize:10,color:"var(--text-dim)",minWidth:66,textAlign:"right"},children:j==="turn"?`Turn ${y.timestamps.length}`:new Date(y.timestamps[y.timestamps.length-1]).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})})]})]}),(Z||(q==null?void 0:q.graphDiff))&&e.jsxs("div",{style:{padding:"10px 12px",borderTop:"1px solid var(--border)",background:"var(--surface)",display:"grid",gap:8},children:[Z&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[e.jsx("span",{style:{fontSize:10,color:"var(--text-dim)",flexShrink:0},children:"Selected node"}),e.jsx("code",{style:{fontSize:10,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},title:Z,children:Pt(Z)}),He.has(Z)&&e.jsx("button",{onClick:()=>Ct(He.get(Z)),style:{marginLeft:"auto",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",padding:"4px 8px",fontSize:10,cursor:"pointer"},children:"Jump to message"})]}),(q==null?void 0:q.graphDiff)&&e.jsxs("div",{style:{display:"grid",gap:6},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{fontSize:11,fontWeight:700,color:"var(--text)"},children:"What changed"}),e.jsx("span",{style:{fontSize:10,color:"var(--text-dim)"},children:X===q.id?"selected turn":"latest persisted turn"}),e.jsx("button",{onClick:()=>{Le(q.id),Ct(q.id)},style:{marginLeft:"auto",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",padding:"4px 8px",fontSize:10,cursor:"pointer"},children:"Go to turn"})]}),e.jsxs("div",{className:"mono",style:{fontSize:10,color:"var(--cyan)"},children:["+",q.graphDiff.addedNodeCount," nodes . +",q.graphDiff.addedEdgeCount," edges"]}),q.graphDiff.sampleNodes.length>0&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:q.graphDiff.sampleNodes.map(t=>e.jsx("button",{onClick:()=>{je(t),It(t)},title:t,style:{borderRadius:999,border:"1px solid rgba(34,211,238,.25)",background:"rgba(34,211,238,.08)",color:"#22d3ee",padding:"3px 8px",fontSize:10,cursor:"pointer",maxWidth:220,overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},children:Pt(t)},t))})]})]})]}),at=S&&!ne,is=!(S&&ne),os=at?Pe?{gridTemplateColumns:"1fr",gridTemplateRows:"minmax(260px, .95fr) minmax(260px, 1.05fr)"}:{gridTemplateColumns:"minmax(340px, 1fr) minmax(360px, .95fr)",gridTemplateRows:"1fr"}:{gridTemplateColumns:"1fr",gridTemplateRows:"1fr"};return e.jsxs("div",{className:"page-section",style:{display:"flex",flexDirection:"column",height:"100%",padding:0},children:[e.jsx("div",{style:{display:"flex",borderBottom:"1px solid var(--border)",background:"var(--bg)",padding:"0 16px",gap:0,flexShrink:0},children:(i!=null&&i.hasOpenClawChannel?["openclaw","peers"]:["agent","peers"]).map(t=>e.jsxs("button",{onClick:()=>o(t),style:{padding:"12px 20px",fontSize:12,fontWeight:n===t?700:500,background:"none",border:"none",borderBottom:n===t?"2px solid var(--green)":"2px solid transparent",color:n===t?"var(--text)":"var(--text-muted)",cursor:"pointer",display:"flex",alignItems:"center",gap:6,transition:"all .15s ease"},children:[t==="agent"?e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"11",width:"18",height:"10",rx:"2"}),e.jsx("circle",{cx:"12",cy:"5",r:"3"})]}):t==="openclaw"?e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M12 2L2 7l10 5 10-5-10-5z"}),e.jsx("path",{d:"M2 17l10 5 10-5"}),e.jsx("path",{d:"M2 12l10 5 10-5"})]}):e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),t==="agent"?"My Agent":t==="openclaw"?`OpenClaw${i!=null&&i.name?` (${i.name})`:""}`:"Peer Chat"]},t))}),n==="peers"?e.jsx("div",{style:{flex:1,overflow:"hidden"},children:e.jsx($s,{})}):n==="openclaw"?e.jsx("div",{style:{flex:1,overflow:"hidden"},children:e.jsx(As,{})}):e.jsxs("div",{style:{display:"grid",gridTemplateColumns:Q?"44px 1fr":"260px 1fr",flex:1,overflow:"hidden"},children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",borderRight:"1px solid var(--border)",background:"var(--bg)",overflow:"hidden"},children:[e.jsxs("div",{style:{padding:Q?"10px 8px":"16px 14px 12px",borderBottom:"1px solid var(--border)",display:"grid",gap:8},children:[e.jsx("button",{onClick:()=>p(t=>!t),title:Q?"Expand sidebar":"Collapse sidebar",style:{width:"100%",padding:Q?"8px 6px":"8px 10px",borderRadius:8,border:"1px solid var(--border)",background:"var(--surface)",color:"var(--text-muted)",fontSize:11,fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:Q?e.jsx("path",{d:"M9 18l6-6-6-6"}):e.jsx("path",{d:"M15 18l-6-6 6-6"})})}),e.jsxs("button",{onClick:Jt,disabled:d,title:"Start a new chat session",style:{width:"100%",padding:Q?"8px 6px":"10px 14px",borderRadius:10,border:"1px solid rgba(74,222,128,.3)",background:"var(--green-dim)",color:"var(--green)",fontSize:12,fontWeight:700,cursor:d?"not-allowed":"pointer",opacity:d?.6:1,display:"flex",alignItems:"center",justifyContent:"center",gap:Q?0:8},children:[e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),!Q&&"New Chat"]})]}),!Q&&e.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"8px 10px"},children:[me&&B.length===0&&e.jsx("div",{style:{fontSize:11,color:"var(--text-dim)",padding:"12px 6px"},children:"Loading conversations…"}),!me&&B.length===0&&e.jsxs("div",{className:"empty-state empty-state--sidebar",children:[e.jsx("div",{className:"empty-state-icon",children:e.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),e.jsx("div",{className:"empty-state-title",children:"No conversations yet"}),e.jsx("div",{className:"empty-state-desc",children:"Start chatting with your agent. Each conversation is stored in your private knowledge graph."})]}),B.map(t=>{const r=t.id===I,l=$t(t.lastTs);return e.jsxs("div",{onClick:()=>{d||Qt(t.id)},style:{padding:"10px 12px",borderRadius:8,marginBottom:4,cursor:d?"not-allowed":"pointer",opacity:d?.75:1,background:r?"var(--surface)":"transparent",border:r?"1px solid var(--border)":"1px solid transparent",transition:"all .15s ease"},onMouseEnter:h=>{!r&&!d&&(h.currentTarget.style.background="var(--surface)")},onMouseLeave:h=>{!r&&!d&&(h.currentTarget.style.background="transparent")},children:[e.jsxs("div",{style:{fontSize:12,fontWeight:r?700:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:r?"var(--text)":"var(--text-muted)",marginBottom:3},children:[t.preview,t.preview.length>=60?"…":""]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsxs("span",{className:"mono",style:{fontSize:10,color:"var(--text-dim)"},children:[t.messageCount," msg",l?` · ${l}`:""]}),r&&e.jsx("button",{onClick:h=>{h.stopPropagation(),!d&&(S&&u===t.id?vt():rt(t.id))},disabled:d,title:"Visualize conversation graph",style:{marginLeft:"auto",padding:"2px 6px",fontSize:9,fontWeight:600,borderRadius:4,border:"1px solid rgba(34,211,238,.3)",background:"rgba(34,211,238,.08)",color:"#22d3ee",cursor:d?"not-allowed":"pointer",opacity:d?.7:1},children:S&&u===t.id?"Hide":"Graph"})]})]},t.id)})]}),!Q&&e.jsx("div",{style:{padding:"10px 14px",borderTop:"1px solid var(--border)",fontSize:10,color:"var(--text-dim)"},children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z"}),e.jsx("path",{d:"M12 6v6l4 2"})]}),"Conversations stored in your private DKG"]})})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[e.jsxs("div",{style:{padding:"14px 20px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",gap:12},children:[e.jsx("div",{style:{width:34,height:34,borderRadius:"50%",background:"var(--green-dim)",border:"1px solid rgba(74,222,128,.25)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:16},children:"AI"}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:14,fontWeight:700},children:"DKG Agent"}),e.jsxs("div",{style:{fontSize:11,color:"var(--green)",display:"flex",alignItems:"center",gap:5},children:[e.jsx("span",{className:"pulse-dot",style:{width:6,height:6,borderRadius:"50%",background:"var(--green)",display:"inline-block"}}),"Connected"]})]}),S&&e.jsx("span",{style:{marginLeft:8,fontSize:10,color:"#22d3ee",background:"rgba(34,211,238,.1)",border:"1px solid rgba(34,211,238,.28)",borderRadius:999,padding:"3px 8px"},children:ne?"Graph-only view":"Split graph view"}),H&&e.jsxs("span",{className:"mono",title:`Pending: ${H.pending}, In progress: ${H.inProgress}, Failed: ${H.failed}, Overdue: ${H.overduePending}`,style:{marginLeft:8,fontSize:10,color:H.failed>0||H.overduePending>0?"var(--red)":"var(--text-dim)",background:H.failed>0||H.overduePending>0?"rgba(248,113,113,.08)":"var(--surface)",border:H.failed>0||H.overduePending>0?"1px solid rgba(248,113,113,.3)":"1px solid var(--border)",borderRadius:999,padding:"3px 8px"},children:["Queue ",H.pending,H.failed>0?` . fail ${H.failed}`:"",H.overduePending>0?` . overdue ${H.overduePending}`:""]}),S&&e.jsx("button",{onClick:()=>he(t=>!t),style:{marginLeft:8,padding:"5px 10px",fontSize:10,fontWeight:600,borderRadius:6,border:ne?"1px solid rgba(34,211,238,.5)":"1px solid var(--border)",background:ne?"rgba(34,211,238,.1)":"var(--surface)",color:ne?"#22d3ee":"var(--text-muted)",cursor:"pointer"},title:ne?"Exit graph-only mode":"Focus on graph only",children:ne?"Exit graph-only":"Graph only"}),e.jsxs("button",{onClick:vt,style:{marginLeft:"auto",padding:"5px 12px",fontSize:11,fontWeight:600,borderRadius:6,border:S?"1px solid rgba(34,211,238,.5)":"1px solid var(--border)",background:S?"rgba(34,211,238,.1)":"var(--surface)",color:S?"#22d3ee":"var(--text-muted)",cursor:"pointer",display:"flex",alignItems:"center",gap:5,transition:"all .15s ease"},children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("circle",{cx:"6",cy:"6",r:"3"}),e.jsx("circle",{cx:"18",cy:"6",r:"3"}),e.jsx("circle",{cx:"12",cy:"18",r:"3"}),e.jsx("line",{x1:"8.5",y1:"7.5",x2:"10.5",y2:"16"}),e.jsx("line",{x1:"15.5",y1:"7.5",x2:"13.5",y2:"16"})]}),S?"Hide Graph":"Show Graph"]})]}),e.jsxs("div",{style:{flex:1,minHeight:0,display:"grid",...os},children:[is&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,minHeight:0,borderRight:at&&!Pe?"1px solid var(--border)":"none",borderBottom:at&&Pe?"1px solid var(--border)":"none"},children:[e.jsxs("div",{ref:Qe,onScroll:Yt,className:"chat-area",style:{flex:1,overflowY:"scroll",padding:"20px 24px"},children:[a.map(t=>{const r=X===t.id,l=Ae.get(t.id)??[],h=t.persistStatus!=="stored"&&t.persistStatus!=="enshrined"&&t.persistStatus!=="skipped"&&t.persistAttempts!=null&&t.persistMaxAttempts!=null;return e.jsxs("div",{ref:x=>{x?Ze.current.set(t.id,x):Ze.current.delete(t.id)},className:`chat-msg ${t.role}`,onClick:()=>{if(Le(t.id),!S)return;const x=l[0]??null;je(x),x&&It(x)},style:{cursor:S?"pointer":"default"},children:[e.jsx("div",{className:`chat-bubble ${t.role}`,style:r?{boxShadow:"0 0 0 1px rgba(34,211,238,.55)"}:void 0,children:t.content}),t.role==="assistant"&&(t.persistStatus||t.llmDiagnostics||t.graphDiff)&&e.jsxs("div",{style:{marginTop:5,display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[t.persistStatus&&e.jsxs("span",{className:"mono",title:t.persistStatus==="enshrined"?"Published to the paranet and anchored on-chain":t.persistStatus==="stored"?"Saved to your local knowledge graph":t.persistStatus==="failed"?"Failed to persist this memory":t.persistStatus==="skipped"?"Memory persistence was skipped for this message":t.persistStatus==="in_progress"?"Currently being saved to the knowledge graph":"Waiting to be persisted",style:{fontSize:10,cursor:"help",color:t.persistStatus==="enshrined"?"#22d3ee":t.persistStatus==="stored"?"var(--green)":t.persistStatus==="failed"?"var(--red)":t.persistStatus==="skipped"?"var(--text-dim)":"#f59e0b",background:t.persistStatus==="enshrined"?"rgba(34,211,238,.1)":t.persistStatus==="stored"?"rgba(74,222,128,.1)":t.persistStatus==="failed"?"rgba(248,113,113,.08)":t.persistStatus==="skipped"?"var(--surface)":"rgba(245,158,11,.1)",border:t.persistStatus==="enshrined"?"1px solid rgba(34,211,238,.3)":t.persistStatus==="stored"?"1px solid rgba(74,222,128,.3)":t.persistStatus==="failed"?"1px solid rgba(248,113,113,.3)":t.persistStatus==="skipped"?"1px solid var(--border)":"1px solid rgba(245,158,11,.35)",borderRadius:5,padding:"2px 6px"},children:["Memory: ",t.persistStatus==="in_progress"?"pending":t.persistStatus,h?` (${t.persistAttempts}/${t.persistMaxAttempts})`:""]}),t.graphDiff&&e.jsxs("span",{style:{fontSize:10,color:"#22d3ee",background:"rgba(34,211,238,.1)",border:"1px solid rgba(34,211,238,.28)",borderRadius:5,padding:"2px 6px"},children:["Added to graph: +",t.graphDiff.addedNodeCount," nodes, +",t.graphDiff.addedEdgeCount," edges"]}),t.persistStatus==="failed"&&e.jsxs("span",{style:{fontSize:10,color:"var(--red)",background:"rgba(248,113,113,.08)",border:"1px solid rgba(248,113,113,.3)",borderRadius:5,padding:"2px 6px"},children:["Memory save failed: ",t.persistError??"Unknown error"]}),t.llmDiagnostics&&e.jsxs("span",{style:{fontSize:10,color:"#f59e0b",background:"rgba(245,158,11,.1)",border:"1px solid rgba(245,158,11,.35)",borderRadius:5,padding:"2px 6px"},title:t.llmDiagnostics.message,children:["LLM compatibility issue",t.llmDiagnostics.compatibilityHint?`: ${t.llmDiagnostics.compatibilityHint}`:""]})]}),t.sparql&&e.jsxs("details",{style:{marginTop:4},children:[e.jsx("summary",{style:{fontSize:10,color:"var(--text-dim)",cursor:"pointer"},children:"SPARQL used"}),e.jsx("pre",{className:"mono",style:{fontSize:10,color:"var(--text-muted)",padding:"6px 8px",background:"var(--surface)",borderRadius:4,marginTop:4,whiteSpace:"pre-wrap",wordBreak:"break-all"},children:t.sparql})]}),e.jsx("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:4,fontFamily:"JetBrains Mono, monospace"},children:t.ts})]},t.id)}),d&&e.jsx("div",{className:"chat-msg assistant",children:e.jsx("div",{className:"chat-bubble assistant",style:{display:"flex",gap:4,alignItems:"center",padding:"12px 16px"},children:[0,.2,.4].map((t,r)=>e.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:"var(--text-muted)",display:"inline-block",animation:`pulse 1.2s ease ${t}s infinite`}},r))})})]}),e.jsxs("div",{className:"chat-input-row",children:[e.jsx("input",{className:"chat-input",value:v,onChange:t=>C(t.target.value),onKeyDown:t=>t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),St()),placeholder:"Query the graph, recall memories, publish knowledge..."}),e.jsx("button",{className:"chat-send",onClick:St,disabled:d,children:"Send"})]})]}),S&&!Pe&&e.jsx("div",{style:{display:"flex",minWidth:0,overflow:"hidden"},children:Rt})]}),S&&Pe&&e.jsx("div",{style:{borderTop:"1px solid var(--border)",height:"43%",minHeight:260,maxHeight:"70%",display:"flex",overflow:"hidden"},children:Rt})]})]})]})}export{Gs as AgentHubPage};
@@ -0,0 +1 @@
1
+ import{a1 as p,r as n,j as c}from"./index-DH-l6lM0.js";function m({apps:h}){const{appId:l}=p(),o=n.useRef(null),[d,s]=n.useState(null),i=n.useRef(!1),t=h.find(e=>e.id===l);n.useEffect(()=>{if(!t)return;let e=!1;return i.current=!1,s(null),t.staticUrl?fetch(t.staticUrl,{method:"HEAD"}).then(r=>{e||s(r.ok?t.staticUrl:`${t.path}/`)}).catch(()=>{e||s(`${t.path}/`)}):s(`${t.path}/`),()=>{e=!0}},[t==null?void 0:t.id,t==null?void 0:t.staticUrl,t==null?void 0:t.path]);const a=n.useCallback(()=>{var r;const e=window.__DKG_TOKEN__;e&&((r=o.current)!=null&&r.contentWindow)&&o.current.contentWindow.postMessage({type:"dkg-token",token:e,apiOrigin:window.location.origin},"*")},[]),w=n.useCallback(()=>{t&&t.staticUrl&&!i.current&&(i.current=!0,s(`${t.path}/`))},[t]);return n.useEffect(()=>{const e=r=>{var u,f;((u=r.data)==null?void 0:u.type)==="dkg-token-request"&&((f=o.current)==null?void 0:f.contentWindow)===r.source&&a()};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)},[a]),t?d?c.jsx("iframe",{ref:o,src:d,onLoad:a,onError:w,sandbox:"allow-scripts allow-forms allow-popups",style:{width:"100%",height:"100%",border:"none",borderRadius:8,background:"var(--surface)"},title:t.label}):null:c.jsxs("div",{style:{padding:32,color:"var(--text-muted)"},children:["App ",c.jsx("strong",{children:l})," is not installed."]})}export{m as AppHostPage};
@@ -0,0 +1 @@
1
+ import{r as n,j as k}from"./index-DH-l6lM0.js";const E="origin-trail-game",a="/apps/origin-trail-game/";function R(o,t){return typeof t=="string"&&o!==null&&t===o}function b({apps:o}){const t=n.useRef(null),i=n.useRef(null),e=o==null?void 0:o.find(r=>r.id===E),[g,l]=n.useState((e==null?void 0:e.staticUrl)||a),c=n.useRef(!1);n.useEffect(()=>{c.current=!1,l((e==null?void 0:e.staticUrl)||a)},[e==null?void 0:e.staticUrl]);const w=n.useCallback(()=>{e!=null&&e.staticUrl&&!c.current&&(c.current=!0,l(a))},[e==null?void 0:e.staticUrl]),m=n.useCallback(()=>{var s;if(!((s=t.current)!=null&&s.contentWindow))return;const r=crypto.randomUUID();i.current=r,t.current.contentWindow.postMessage({type:"dkg-nonce",nonce:r},"*")},[]);return n.useEffect(()=>{const r=s=>{var u,d;if(((u=s.data)==null?void 0:u.type)==="dkg-token-request"&&((d=t.current)==null?void 0:d.contentWindow)===s.source&&R(i.current,s.data.nonce)){i.current=null;const f=window.__DKG_TOKEN__;f&&t.current.contentWindow.postMessage({type:"dkg-token",token:f,apiOrigin:window.location.origin},"*")}};return window.addEventListener("message",r),()=>window.removeEventListener("message",r)},[]),k.jsx("iframe",{ref:t,src:g,onLoad:m,onError:w,sandbox:"allow-scripts allow-forms allow-popups",allow:"clipboard-write",style:{width:"100%",height:"100%",border:"none",borderRadius:8,background:"#111"},title:"OriginTrail Game"})}export{b as AppsPage,R as validateTokenRequest};
@@ -0,0 +1,2 @@
1
+ import{r as u,j as e,u as J,f as Z,a as ee,b as te,c as ne,i as re,d as se,e as oe,R as ie,g as ae,h as le,I as de,k as ce,l as he}from"./index-DH-l6lM0.js";import{u as T,f as $}from"./hooks-BLTFNmyP.js";import{R as pe}from"./index-8_35CUX2.js";import"./ordinal-DIohFSkg.js";function E({text:t,children:l,maxWidth:r=280}){const[s,n]=u.useState(!1),[o,i]=u.useState(null),a=u.useRef(null),h=u.useRef(null),S=u.useCallback(()=>{if(!a.current)return;const m=a.current.getBoundingClientRect();i({x:m.left+m.width/2,y:m.top}),n(!0)},[]),f=u.useCallback(()=>n(!1),[]);return u.useEffect(()=>{if(!s||!h.current||!o)return;const m=h.current,k=m.getBoundingClientRect();let v=o.x,N=o.y;k.right>window.innerWidth-12&&(v-=k.right-window.innerWidth+12),k.left<12&&(v+=12-k.left),k.top<12?(N=a.current.getBoundingClientRect().bottom,m.classList.add("tt-below")):m.classList.remove("tt-below"),(v!==o.x||N!==o.y)&&i({x:v,y:N})},[s,o]),e.jsxs("span",{ref:a,onMouseEnter:S,onMouseLeave:f,style:{display:"inline-flex",alignItems:"center"},children:[l,s&&o&&e.jsx("div",{ref:h,className:"tt",style:{left:o.x,top:o.y,maxWidth:r},children:t})]})}function H({text:t,maxWidth:l}){return e.jsx(E,{text:t,maxWidth:l,children:e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:4,verticalAlign:"middle",opacity:.7},children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),e.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})})}const ue={claude:{label:"Claude",icon:"🟣"},chatgpt:{label:"ChatGPT",icon:"🟢"},gemini:{label:"Gemini",icon:"🔵"},other:{label:"Other",icon:"⚪"}},ge=de.map(t=>({value:t,...ue[t]})),fe={name:"ImportPreview",palette:"dark",paletteOverrides:{edgeColor:"#5f8598"},animation:{fadeIn:!0,linkParticles:!1,drift:!1,hoverTrace:!1}};function U(t){const l=t.replace(/^"|".*$/g,""),r=l.lastIndexOf("#"),s=l.lastIndexOf("/"),n=l.lastIndexOf(":"),o=Math.max(r,s,n);return o>=0?l.slice(o+1):l}function me(t){return t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t.startsWith('"')&&t.includes('"^^<')?t.slice(1,t.indexOf('"^^<')):t}function xe({result:t,onReset:l,onClose:r}){const[s,n]=u.useState("graph"),o=u.useMemo(()=>{var i;return(i=t.quads)!=null&&i.length?t.quads.filter(a=>!a.object.startsWith('"')).map(a=>({subject:a.subject,predicate:a.predicate,object:a.object})):[]},[t.quads]);return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsxs("div",{style:{textAlign:"center"},children:[e.jsxs("div",{style:{fontSize:16,fontWeight:700,color:"var(--green)",marginBottom:4},children:[t.memoryCount," memories imported"]}),e.jsxs("p",{children:[t.tripleCount," triples created",t.entityCount>0&&e.jsxs(e.Fragment,{children:[" · ",t.entityCount," entities extracted"]})]}),e.jsxs("div",{className:"mono",style:{fontSize:10,color:"var(--text-dim)",marginTop:6},children:["Batch: ",t.batchId," · Source: ",t.source]})]}),t.warnings&&t.warnings.length>0&&e.jsx("div",{style:{padding:"8px 12px",borderRadius:8,background:"rgba(250,204,21,.08)",border:"1px solid rgba(250,204,21,.25)"},children:t.warnings.map((i,a)=>e.jsxs("div",{style:{fontSize:11,color:"rgb(250,204,21)",lineHeight:1.5},children:["⚠ ",i]},a))}),e.jsxs("div",{style:{display:"flex",gap:6,justifyContent:"center"},children:[e.jsx("button",{className:`dkg-btn ${s==="graph"?"":"dkg-btn-secondary"}`,onClick:()=>n("graph"),style:{padding:"6px 16px",fontSize:11},children:"Graph"}),e.jsx("button",{className:`dkg-btn ${s==="triples"?"":"dkg-btn-secondary"}`,onClick:()=>n("triples"),style:{padding:"6px 16px",fontSize:11},children:"Triples"})]}),s==="graph"&&e.jsx("div",{style:{height:320,borderRadius:10,overflow:"hidden",border:"1px solid var(--border)",background:"var(--bg)"},children:o.length>0?e.jsx(pe,{data:o,format:"triples",options:{labelMode:"humanized",renderer:"2d",style:{classColors:{"http://dkg.io/ontology/MemoryImport":"#f59e0b","http://dkg.io/ontology/ImportedMemory":"#4ade80"},defaultNodeColor:"#22d3ee",defaultEdgeColor:"#5f8598",edgeWidth:.9},hexagon:{baseSize:4,minSize:3,maxSize:6,scaleWithDegree:!0},focus:{maxNodes:500,hops:999}},viewConfig:fe,style:{width:"100%",height:"100%"}}):e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"var(--text-dim)",fontSize:12},children:"No graph edges to display"})}),s==="triples"&&e.jsx("div",{style:{maxHeight:320,overflowY:"auto",borderRadius:10,border:"1px solid var(--border)",background:"var(--bg)",padding:0},children:e.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11,fontFamily:"'JetBrains Mono', monospace"},children:[e.jsx("thead",{children:e.jsxs("tr",{style:{position:"sticky",top:0,background:"var(--surface)",borderBottom:"1px solid var(--border)"},children:[e.jsx("th",{style:{textAlign:"left",padding:"8px 10px",color:"var(--text-dim)",fontWeight:600,fontSize:10,textTransform:"uppercase",letterSpacing:".05em"},children:"Subject"}),e.jsx("th",{style:{textAlign:"left",padding:"8px 10px",color:"var(--text-dim)",fontWeight:600,fontSize:10,textTransform:"uppercase",letterSpacing:".05em"},children:"Predicate"}),e.jsx("th",{style:{textAlign:"left",padding:"8px 10px",color:"var(--text-dim)",fontWeight:600,fontSize:10,textTransform:"uppercase",letterSpacing:".05em"},children:"Object"})]})}),e.jsx("tbody",{children:(t.quads??[]).map((i,a)=>e.jsxs("tr",{style:{borderBottom:"1px solid var(--border)"},children:[e.jsx("td",{style:{padding:"6px 10px",color:"var(--cyan)",wordBreak:"break-all"},children:U(i.subject)}),e.jsx("td",{style:{padding:"6px 10px",color:"var(--text-muted)",wordBreak:"break-all"},children:U(i.predicate)}),e.jsx("td",{style:{padding:"6px 10px",color:i.object.startsWith('"')?"var(--text)":"var(--green)",wordBreak:"break-all"},children:me(i.object)})]},a))})]})}),e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.6,textAlign:"center"},children:["Stored as private Knowledge Assets in ",e.jsx("code",{className:"mono",style:{fontSize:10,background:"var(--surface)",padding:"1px 4px",borderRadius:3},children:"agent-memory"}),". Never shared with other nodes."]}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"center"},children:[e.jsx("button",{className:"dkg-btn dkg-btn-secondary",onClick:l,children:"Import More"}),e.jsx("button",{className:"dkg-btn dkg-btn-solid",onClick:r,children:"Done"})]})]})}function be({open:t,onClose:l}){const[r,s]=u.useState(""),[n,o]=u.useState("claude"),[i,a]=u.useState(!1),[h,S]=u.useState(!1),[f,m]=u.useState(null),[k,v]=u.useState(null),N=u.useCallback(()=>{s(""),o("claude"),a(!1),S(!1),m(null),v(null)},[]),c=u.useCallback(()=>{h||(N(),l())},[l,N,h]),w=u.useCallback(async()=>{if(!(!r.trim()||h)){S(!0),v(null),m(null);try{const d=await re(r.trim(),n,i);m(d)}catch(d){v(d.message??"Import failed")}finally{S(!1)}}},[r,n,i,h]);return t?e.jsx("div",{className:"import-modal-overlay open",onClick:c,children:e.jsxs("div",{className:"import-modal",style:f?{maxWidth:680}:void 0,onClick:d=>d.stopPropagation(),children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:20},children:[e.jsx("h3",{style:{fontSize:18,fontWeight:700},children:f?"Import Complete":"Import Memories"}),e.jsx("button",{onClick:c,disabled:h,style:{background:"none",border:"none",color:"var(--text-muted)",fontSize:18,opacity:h?.3:1},children:"×"})]}),f?e.jsx(xe,{result:f,onReset:N,onClose:c}):e.jsxs(e.Fragment,{children:[e.jsx("p",{style:{marginBottom:12},children:"Paste exported memories from Claude, ChatGPT, Gemini, or any other AI assistant. They'll be stored as private Knowledge Assets on your DKG node — owned by you, queryable by your agent."}),e.jsx("div",{style:{display:"flex",gap:6,marginBottom:14},children:ge.map(d=>e.jsxs("button",{className:`dkg-btn ${n===d.value?"":"dkg-btn-secondary"}`,onClick:()=>o(d.value),style:{padding:"6px 12px",fontSize:11},children:[e.jsx("span",{style:{fontSize:12},children:d.icon}),d.label]},d.value))}),e.jsxs("div",{style:{padding:"10px 14px",borderRadius:8,background:"var(--blue-dim)",border:"1px solid rgba(96,165,250,.2)",marginBottom:16},children:[e.jsx("div",{style:{fontSize:10,fontWeight:700,color:"var(--blue)",marginBottom:4},children:"HOW TO EXPORT"}),e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.6},children:["Paste this into ",n==="claude"?"Claude":n==="chatgpt"?"ChatGPT":n==="gemini"?"Gemini":"your AI assistant"," to export your memories:",e.jsx("br",{}),e.jsx("code",{className:"mono",style:{fontSize:10,color:"var(--text)",background:"rgba(255,255,255,.05)",padding:"2px 6px",borderRadius:4,display:"inline-block",marginTop:4},children:'"List every memory you have stored about me in a single code block."'})]})]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"var(--text-muted)",marginBottom:10,cursor:"pointer"},children:[e.jsx("input",{type:"checkbox",checked:i,onChange:d=>a(d.target.checked),disabled:h}),e.jsxs("span",{children:["Use LLM-assisted parsing ",e.jsx("span",{style:{fontSize:10,opacity:.7},children:"(sends memories to configured LLM for better categorisation & entity extraction)"})]})]}),e.jsx("textarea",{value:r,onChange:d=>s(d.target.value),placeholder:"Paste your exported memories here...",disabled:h}),r.trim()&&e.jsxs("div",{className:"mono",style:{fontSize:10,color:"var(--text-dim)",marginTop:6},children:[r.trim().split(`
2
+ `).filter(d=>d.trim().length>3).length," lines detected"]}),k&&e.jsx("div",{style:{marginTop:10,padding:"8px 12px",borderRadius:6,background:"var(--red-dim)",border:"1px solid rgba(248,113,113,.2)",color:"var(--red)",fontSize:12},children:k}),e.jsxs("div",{style:{display:"flex",gap:8,marginTop:16,justifyContent:"flex-end"},children:[e.jsx("button",{className:"dkg-btn dkg-btn-secondary",onClick:c,disabled:h,children:"Cancel"}),e.jsx("button",{className:"dkg-btn dkg-btn-solid",onClick:w,disabled:h||!r.trim(),children:h?e.jsxs(e.Fragment,{children:[e.jsx("span",{style:{width:12,height:12,border:"2px solid rgba(10,15,26,.3)",borderTopColor:"var(--bg)",borderRadius:"50%",animation:"spin .6s linear infinite",display:"inline-block"}}),"Importing…"]}):e.jsxs(e.Fragment,{children:[e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),e.jsx("polyline",{points:"7 10 12 15 17 10"}),e.jsx("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),"Import as Private Knowledge"]})})]})]})]})}):null}const Q={publish:"#10b981",query:"#3b82f6",update:"#f97316",chat:"#06b6d4",access:"#f59e0b",stake:"#8b5cf6"},Y=["#4f46e5","#6366f1","#818cf8","#3b82f6","#60a5fa","#22d3ee","#a78bfa","#8b5cf6","#f472b6","#94a3b8","#fbbf24","#f97316"],F=4,V=8,ye=2,X=6;function ve(t,l,r,s){const n=[];for(let o=0;o<t;o++){const i=o/t*Math.PI*2-Math.PI/2;n.push({x:l+Math.cos(i)*s,y:r+Math.sin(i)*s})}return n}function je(t,l,r){t.save(),t.strokeStyle="rgba(74, 222, 128, 0.03)",t.lineWidth=1;const s=40;for(let n=0;n<l;n+=s)t.beginPath(),t.moveTo(n,0),t.lineTo(n,r),t.stroke();for(let n=0;n<r;n+=s)t.beginPath(),t.moveTo(0,n),t.lineTo(l,n),t.stroke();t.restore()}function Se(t,l,r,s,n,o){t.save(),t.strokeStyle=o?"rgba(74, 222, 128, 0.18)":"rgba(74, 222, 128, 0.05)",t.lineWidth=o?1.5:1,t.setLineDash(o?[]:[4,4]),t.beginPath(),t.moveTo(l,r),t.lineTo(s,n),t.stroke(),t.restore()}function ke(t,l,r,s,n){if(t.save(),n){const a=t.createRadialGradient(l,r,F,l,r,V);a.addColorStop(0,"rgba(74, 222, 128, 0.30)"),a.addColorStop(1,"transparent"),t.fillStyle=a,t.beginPath(),t.arc(l,r,V,0,Math.PI*2),t.fill()}const o=s.status==="offline"&&!n;t.globalAlpha=o?.3:s.status==="recent"&&!n?.6:1,t.beginPath(),t.arc(l,r,F,0,Math.PI*2),t.fillStyle=n?"#0a1a0a":"#0f0f23",t.fill(),t.strokeStyle=n?"#4ade80":s.color,t.lineWidth=n?1.5:1,s.status==="recent"&&!n&&t.setLineDash([2,2]),t.stroke(),t.setLineDash([]);const i=s.status==="online"?"#10b981":s.status==="recent"?"#f59e0b":"#ef4444";if(t.beginPath(),t.arc(l+4,r-4,1.5,0,Math.PI*2),t.fillStyle=i,t.fill(),t.strokeStyle="#0a0f1a",t.lineWidth=.8,t.stroke(),s.status==="online"){const a=t.createRadialGradient(l+4,r-4,1.5,l+4,r-4,4);a.addColorStop(0,"rgba(16,185,129,0.3)"),a.addColorStop(1,"transparent"),t.fillStyle=a,t.beginPath(),t.arc(l+4,r-4,4,0,Math.PI*2),t.fill()}t.font="500 7px Inter, system-ui, sans-serif",t.textAlign="center",t.textBaseline="middle",t.fillStyle="#94a3b8",t.fillText(s.sublabel,l,r+F+7),n&&(t.font="600 6px JetBrains Mono, monospace",t.fillStyle="#4ade80",t.fillText("YOUR NODE",l,r+F+15)),t.globalAlpha=1,t.restore()}function we(t,l,r,s){const n=Q[s];t.save();const o=t.createRadialGradient(l,r,0,l,r,X);o.addColorStop(0,n+"aa"),o.addColorStop(.4,n+"44"),o.addColorStop(1,"transparent"),t.fillStyle=o,t.beginPath(),t.arc(l,r,X,0,Math.PI*2),t.fill(),t.fillStyle=n,t.beginPath(),t.arc(l,r,ye,0,Math.PI*2),t.fill(),t.fillStyle="#ffffff",t.beginPath(),t.arc(l,r,1.5,0,Math.PI*2),t.fill(),t.restore()}function Ce(t,l,r){const s=Object.entries(Q).map(([f,m])=>[f.charAt(0).toUpperCase()+f.slice(1),m]),n=10,o=16,i=90,a=n*2+s.length*o,h=l-i-12,S=r-a-12;t.save(),t.fillStyle="rgba(10, 15, 26, 0.85)",t.strokeStyle="rgba(74, 222, 128, 0.15)",t.lineWidth=1,t.beginPath(),t.roundRect(h,S,i,a,6),t.fill(),t.stroke(),t.font="500 9px Inter, system-ui, sans-serif",t.textAlign="left",t.textBaseline="middle",s.forEach(([f,m],k)=>{const v=S+n+k*o+o/2;t.fillStyle=m,t.beginPath(),t.arc(h+n+3,v,3.5,0,Math.PI*2),t.fill(),t.fillStyle="#94a3b8",t.fillText(f,h+n+12,v)}),t.restore()}const Re={publish:"publish",query:"query",workspace:"update",chat:"chat",connect:"access",enshrine:"publish",sync:"stake",access:"access"};function Pe({agents:t,nodeName:l}){const r=u.useRef(null),s=u.useRef(null),n=u.useRef([]),o=u.useRef(0),i=u.useRef(new Set),a=u.useRef(0),h=u.useRef(1),S=u.useRef({x:0,y:0}),f=u.useRef(!1),m=u.useRef({x:0,y:0,panX:0,panY:0}),k=300*1e3,v=1440*60*1e3;function N(d){if(d.connectionStatus==="self"||d.connectionStatus==="connected")return"online";if(d.lastSeen==null)return"offline";const p=Date.now()-d.lastSeen;return p<k?"online":p<v?"recent":"offline"}const c=t.length>0?t.map((d,p)=>{var j,x;const y=d.connectionStatus==="self",b=N(d);return{id:p,isYou:y,online:b!=="offline",status:b,label:y?"YOU":((j=d.name)==null?void 0:j.replace(/^devnet-/,""))||`P${p}`,sublabel:y?l||d.name||"my-node":d.name||((x=d.peerId)==null?void 0:x.slice(0,10))||`peer-${p}`,color:y?"#4ade80":Y[p%Y.length]}}):[{id:0,isYou:!0,online:!0,status:"online",label:"YOU",sublabel:l||"my-node",color:"#4ade80"}],w=u.useCallback(()=>{var q,K;const d=r.current;if(!d)return;const p=d.getContext("2d"),y=window.devicePixelRatio||1,b=d.width/y,j=d.height/y,x=b/2,C=j/2,z=c.length<=6?.52:c.length<=10?.58:.64,W=Math.min(x,C)*z;p.save(),p.scale(y,y),p.clearRect(0,0,b,j),p.fillStyle="#0a0f1a",p.fillRect(0,0,b,j),je(p,b,j),p.save();const B=h.current,M=S.current;p.translate(b/2+M.x,j/2+M.y),p.scale(B,B),p.translate(-b/2,-j/2);const R=ve(c.length,x,C,W),D=new Set;for(const g of n.current){const P=[Math.min(g.from,g.to),Math.max(g.from,g.to)].join("-");D.add(P)}const L=c.findIndex(g=>g.isYou),G=new Set;for(let g=0;g<c.length;g++){if(g===L)continue;const P=[Math.min(g,L),Math.max(g,L)].join("-");G.add(P);const I=(g+1)%c.length;if(I!==L){const O=[Math.min(g,I),Math.max(g,I)].join("-");G.add(O)}}for(const g of G){const[P,I]=g.split("-").map(Number);if(R[P]&&R[I]){const O=((q=c[P])==null?void 0:q.online)!==!1&&((K=c[I])==null?void 0:K.online)!==!1;p.globalAlpha=O?1:.15,Se(p,R[P].x,R[P].y,R[I].x,R[I].y,D.has(g))}}p.globalAlpha=1;for(const g of n.current){const P=R[g.from],I=R[g.to];if(!P||!I)continue;const O=g.progress<.5?2*g.progress*g.progress:1-Math.pow(-2*g.progress+2,2)/2;we(p,P.x+(I.x-P.x)*O,P.y+(I.y-P.y)*O,g.type)}for(let g=0;g<c.length;g++)ke(p,R[g].x,R[g].y,c[g],c[g].isYou);p.restore(),Ce(p,b,j),p.restore()},[t,l]);return u.useEffect(()=>{let d,p=!1;const y=c.findIndex(C=>C.isYou),b=c.map((C,z)=>z).filter(C=>C!==y),j=async()=>{if(p||c.length<2)return;const C=Date.now();if(!(C-a.current<3e3)){a.current=C;try{const z=C-1e4,W=await he({from:String(z),limit:"20"}),B=(W==null?void 0:W.operations)??[];for(const M of B){const R=M.operation_id??M.id;if(!R||i.current.has(R))continue;i.current.add(R);const D=Re[M.operation_name]??"query",L=b.length>0?b[Math.floor(Math.random()*b.length)]:0;n.current.push({id:o.current++,from:y>=0?y:0,to:L,progress:0,speed:.006+Math.random()*.004,type:D})}if(i.current.size>200){const M=Array.from(i.current);i.current=new Set(M.slice(-100))}}catch{}}},x=C=>{j(),n.current=n.current.map(z=>({...z,progress:z.progress+z.speed})).filter(z=>z.progress<=1),w(),d=requestAnimationFrame(x)};return d=requestAnimationFrame(x),()=>{p=!0,cancelAnimationFrame(d)}},[w]),u.useEffect(()=>{const d=r.current,p=s.current;if(!d||!p)return;const y=()=>{const j=window.devicePixelRatio||1,x=p.getBoundingClientRect();d.width=x.width*j,d.height=x.height*j,d.style.width=`${x.width}px`,d.style.height=`${x.height}px`};y();const b=new ResizeObserver(y);return b.observe(p),()=>b.disconnect()},[]),u.useEffect(()=>{const d=s.current;if(!d)return;const p=x=>{x.preventDefault();const C=x.deltaY>0?.9:1.1;h.current=Math.max(.3,Math.min(5,h.current*C))},y=x=>{f.current=!0,m.current={x:x.clientX,y:x.clientY,panX:S.current.x,panY:S.current.y},d.style.cursor="grabbing"},b=x=>{f.current&&(S.current={x:m.current.panX+(x.clientX-m.current.x),y:m.current.panY+(x.clientY-m.current.y)})},j=()=>{f.current=!1,d.style.cursor="grab"};return d.style.cursor="grab",d.addEventListener("wheel",p,{passive:!1}),d.addEventListener("mousedown",y),window.addEventListener("mousemove",b),window.addEventListener("mouseup",j),()=>{d.removeEventListener("wheel",p),d.removeEventListener("mousedown",y),window.removeEventListener("mousemove",b),window.removeEventListener("mouseup",j)}},[]),e.jsx("div",{ref:s,style:{width:"100%",height:"100%"},children:e.jsx("canvas",{ref:r,style:{display:"block"}})})}const Ne=[{name:"OriginTrail Game",assets:847,agents:12,color:"var(--green)"},{name:"DeSci Research",assets:1203,agents:8,color:"var(--blue)"},{name:"Supply Chain EU",assets:797,agents:4,color:"var(--amber)"}],Ie={prepare:"Partitioning triples, computing Merkle hashes, validating & signing.",store:"Inserting triples into the local triple store and data graph.",chain:"Submitting on-chain tx and waiting for confirmation.",broadcast:"Broadcasting to network peers via GossipSub.",parse:"Validating and parsing the SPARQL query syntax.",execute:"Running the SPARQL query against the local triple store.",transfer:"Fetching triple pages from the remote peer.",verify:"Verifying Merkle proofs and inserting synced triples."},A={prepare:"#3b82f6","prepare:ensureParanet":"#60a5fa","prepare:partition":"#2563eb","prepare:manifest":"#93c5fd","prepare:validate":"#1d4ed8","prepare:merkle":"#7dd3fc",store:"#8b5cf6",chain:"#f59e0b","chain:sign":"#fbbf24","chain:submit":"#d97706","chain:metadata":"#f97316",broadcast:"#22c55e",decode:"#14b8a6",validate:"#2dd4bf","read-workspace":"#06b6d4",parse:"#3b82f6",execute:"#8b5cf6",transfer:"#60a5fa",verify:"#22c55e"},_="#a78bfa";function ze({phases:t,totalMs:l}){const[r,s]=u.useState(null);if(!(t!=null&&t.length)||l<=0)return e.jsx("div",{style:{flex:1,height:8,borderRadius:2,background:"rgba(255,255,255,.04)"}});const n=t.reduce((o,i)=>o+(i.duration_ms??0),0)||l;return e.jsxs("div",{style:{flex:1,position:"relative"},children:[e.jsx("div",{style:{display:"flex",height:8,borderRadius:2,overflow:"hidden",background:"rgba(255,255,255,.04)"},children:t.map((o,i)=>{const a=Math.max((o.duration_ms??0)/n*100,2),h=o.status==="error"?"#ef4444":A[o.phase]??_;return e.jsx("div",{onMouseEnter:()=>s(i),onMouseLeave:()=>s(null),style:{width:`${a}%`,background:h,minWidth:2,opacity:r===i?1:.7,transition:"opacity .15s",cursor:"default"}},`${o.phase}-${i}`)})}),r!==null&&t[r]&&(()=>{const o=t[r].phase,i=o.includes(":")?o.split(":")[0]:o,a=Ie[i];return e.jsxs("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:6,padding:"4px 8px",borderRadius:6,background:"var(--surface)",border:"1px solid var(--border)",boxShadow:"0 4px 12px rgba(0,0,0,.4)",fontSize:10,zIndex:10,pointerEvents:"none",maxWidth:240},children:[e.jsxs("div",{style:{whiteSpace:"nowrap"},children:[e.jsx("span",{style:{fontWeight:700,color:A[o]??_},children:o}),e.jsx("span",{style:{color:"var(--text-muted)",margin:"0 4px"},children:"·"}),e.jsx("span",{style:{fontFamily:"'JetBrains Mono', monospace",color:"var(--text)"},children:$(t[r].duration_ms)}),t[r].status==="error"&&e.jsx("span",{style:{color:"var(--red)",marginLeft:4,fontWeight:600},children:"FAIL"})]}),a&&e.jsx("div",{style:{fontSize:9,color:"var(--text-muted)",marginTop:2,whiteSpace:"normal",lineHeight:1.3},children:a})]})})()]})}function Me({operationId:t}){const{data:l,loading:r}=T(()=>ce(t),[t]);if(r)return e.jsx("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:"Loading..."});if(!l)return null;const{operation:s,phases:n,logs:o}=l;if(!s)return null;const i=(o??[]).slice(-5);return e.jsxs("div",{style:{padding:"10px 12px",background:"rgba(255,255,255,.02)",borderTop:"1px solid var(--border)"},children:[e.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap",marginBottom:8,fontSize:11},children:[e.jsxs("span",{style:{color:"var(--text-muted)"},children:["Status: ",e.jsx("strong",{style:{color:s.status==="error"?"var(--red)":"var(--green-mid)"},children:s.status})]}),e.jsxs("span",{style:{color:"var(--text-muted)"},children:["Duration: ",e.jsx("strong",{style:{fontFamily:"'JetBrains Mono', monospace"},children:$(s.duration_ms)})]}),s.error_message&&e.jsx("span",{style:{color:"var(--red)",fontSize:10},children:s.error_message})]}),(n==null?void 0:n.length)>0&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:3,marginBottom:i.length?8:0},children:n.map((a,h)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10},children:[e.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:a.status==="error"?"var(--red)":A[a.phase]??_,flexShrink:0}}),e.jsx("span",{style:{color:A[a.phase]??_,fontWeight:600,minWidth:100},children:a.phase}),e.jsx("span",{className:"mono",style:{color:"var(--text-dim)"},children:$(a.duration_ms)}),a.status==="error"&&e.jsx("span",{style:{color:"var(--red)",fontWeight:600},children:"FAILED"})]},`${a.phase}-${h}`))}),i.length>0&&e.jsxs("div",{style:{borderTop:"1px solid var(--border)",paddingTop:6},children:[e.jsx("div",{style:{fontSize:9,color:"var(--text-dim)",marginBottom:4,fontWeight:600},children:"Recent logs"}),i.map((a,h)=>e.jsxs("div",{style:{fontSize:10,color:a.level==="error"?"var(--red)":a.level==="warn"?"var(--amber)":"var(--text-muted)",lineHeight:1.5,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["[",a.module,"] ",a.message]},h))]})]})}function Te(){const{data:t}=T(()=>se({limit:"8"}),[],1e4),l=J(),[r,s]=u.useState(null),n=(t==null?void 0:t.operations)??[],o=oe();return n.length===0?null:e.jsxs("div",{style:{marginBottom:16},children:[e.jsxs("div",{className:"section-title",style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsx("span",{children:"Recent Operations"}),o&&e.jsx("button",{className:"dkg-btn dkg-btn-secondary",style:{fontSize:10,padding:"4px 10px"},onClick:()=>l("/settings?tab=observability"),children:"View All"})]}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:n.map(i=>{const a=i.duration_ms??0,h=i.status==="error",S=i.phases??[],f=r===i.operation_id;return e.jsxs(ie.Fragment,{children:[e.jsxs("div",{onClick:()=>s(f?null:i.operation_id),style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderRadius:f?"8px 8px 0 0":8,background:f?"rgba(59,130,246,.06)":"var(--surface)",border:"1px solid var(--border)",borderBottom:f?"1px solid var(--border)":void 0,cursor:"pointer",transition:"border-color .15s, background .15s"},onMouseEnter:m=>{f||(m.currentTarget.style.borderColor="rgba(74,222,128,.3)")},onMouseLeave:m=>{f||(m.currentTarget.style.borderColor="var(--border)")},children:[e.jsx("span",{className:"mono",style:{fontSize:10,color:"var(--text-dim)",width:50,flexShrink:0},children:new Date(i.started_at).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}),e.jsx("span",{style:{fontSize:10,fontWeight:700,width:60,flexShrink:0,color:h?"var(--red)":"var(--green-mid)"},children:i.operation_name}),e.jsx(ze,{phases:S,totalMs:a}),e.jsx("span",{className:"mono",style:{fontSize:10,color:"var(--text-muted)",width:50,textAlign:"right",flexShrink:0},children:$(a)}),e.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:h?"var(--red)":i.status==="in_progress"?"var(--amber)":"var(--green-mid)",flexShrink:0}})]}),f&&e.jsx("div",{style:{border:"1px solid var(--border)",borderTop:"none",borderRadius:"0 0 8px 8px",overflow:"hidden",marginTop:-4},children:e.jsx(Me,{operationId:i.operation_id})})]},i.operation_id)})})]})}function Ee(){const{data:t}=T(()=>ae(6048e5),[],3e4),l=((t==null?void 0:t.hotspots)??[]).slice(0,5);return l.length===0?e.jsx("div",{className:"paranet-card",style:{display:"flex",alignItems:"center",justifyContent:"center",minHeight:60},children:e.jsx("span",{style:{fontSize:11,color:"var(--green)",fontWeight:600},children:"No errors in 7 days"})}):e.jsxs("div",{className:"paranet-card",style:{padding:12},children:[e.jsx("div",{style:{fontSize:11,fontWeight:700,color:"var(--red)",marginBottom:6},children:"Error Hotspots (7d)"}),l.map((r,s)=>e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",fontSize:11,padding:"3px 0",color:"var(--text-muted)"},children:[e.jsxs("span",{children:[e.jsx("span",{style:{color:"var(--text-dim)",fontSize:10},children:r.operation_name}),e.jsx("span",{style:{color:"var(--text-dim)",margin:"0 4px"},children:"›"}),e.jsx("span",{style:{color:A[r.phase]??_,fontWeight:500},children:r.phase})]}),e.jsx("span",{style:{color:"var(--red)",fontWeight:700},children:r.error_count})]},`${r.operation_name}-${r.phase}-${s}`))]})}function Le(){var s,n;const{data:t}=T(le,[],6e4),r=((t==null?void 0:t.periods)??[])[0];return r?e.jsxs("div",{className:"paranet-card",style:{padding:12},children:[e.jsxs("div",{style:{fontSize:11,fontWeight:700,color:"var(--amber)",marginBottom:6},children:["Spending (",r.label,")"]}),e.jsxs("div",{style:{display:"flex",gap:16,fontSize:11,color:"var(--text-muted)"},children:[e.jsxs("div",{children:[e.jsx("div",{className:"mono",style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:((s=r.totalGasEth)==null?void 0:s.toFixed(6))??"0"}),e.jsx(E,{text:"Ethereum gas fees for on-chain transactions",children:e.jsx("div",{children:"ETH gas"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mono",style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:((n=r.totalTrac)==null?void 0:n.toFixed(2))??"0"}),e.jsx(E,{text:"TRAC — the OriginTrail network token used for publishing and storing knowledge",children:e.jsx("div",{children:"TRAC"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mono",style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:r.publishCount??0}),e.jsx(E,{text:"Number of Knowledge Assets published on-chain",children:e.jsx("div",{children:"publishes"})})]})]})]}):null}function Be(){const t=J(),[l,r]=u.useState(!1),{data:s}=T(ee,[],1e4),{data:n}=T(te,[],1e4),{data:o}=T(Z,[],3e4),{data:i}=T(ne,[],15e3),a=u.useMemo(()=>{const c=["var(--green)","var(--blue)","var(--amber)","var(--purple)","#f472b6","#22d3ee"];return((o==null?void 0:o.paranets)??[]).map((w,d)=>({id:w.id??`paranet-${d}`,name:w.name??w.id??`Paranet ${d+1}`,assets:w.assetCount??w.assets??"—",agents:w.agentCount??w.agents??"—",color:c[d%c.length]}))},[o]),h=a.length>0?a:Ne,S=a.length>0,f=(s==null?void 0:s.connectedPeers)??(s==null?void 0:s.peerCount)??null,m=(n==null?void 0:n.total_kcs)??null,k=(n==null?void 0:n.confirmed_kcs)??null,v=(n==null?void 0:n.tentative_kcs)??null,N=(i==null?void 0:i.agents)!=null?i.agents.length:null;return e.jsxs("div",{className:"page-section",children:[e.jsx(be,{open:l,onClose:()=>r(!1)}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:24},children:[e.jsxs("div",{children:[e.jsx("h1",{className:"page-title",style:{marginBottom:0},children:"Dashboard"}),e.jsx("p",{style:{marginTop:4},children:s?`Your node is live${a.length?` and participating in ${a.length} paranet${a.length!==1?"s":""}`:""}`:"Loading node status…"})]}),e.jsxs("button",{className:"dkg-btn",onClick:()=>r(!0),children:[e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),e.jsx("polyline",{points:"7 10 12 15 17 10"}),e.jsx("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),"Import Memories"]})]}),e.jsx("div",{style:{display:"flex",gap:12,marginBottom:24,flexWrap:"wrap"},children:[{label:e.jsxs(e.Fragment,{children:["Knowledge Collections ",e.jsx(H,{text:"Groups of knowledge triples stored on your node. Confirmed = finalized on-chain. Tentative = stored locally, pending blockchain finalization."})]}),value:k!=null&&v!=null?String(Number(k)+Number(v)):m!=null?Number(m).toLocaleString():"—",sub:k!=null&&v!=null?e.jsxs(e.Fragment,{children:[e.jsx(E,{text:"Finalized on-chain with a confirmed transaction",children:e.jsxs("span",{style:{color:"var(--green)"},children:[Number(k).toLocaleString()," confirmed"]})})," · ",e.jsx(E,{text:"Stored locally, pending blockchain finalization",children:e.jsxs("span",{style:{color:"var(--amber)"},children:[Number(v).toLocaleString()," tentative"]})})]}):m!=null?"from node metrics":"loading…",color:"var(--green)"},{label:e.jsxs(e.Fragment,{children:["Connected Peers ",e.jsx(H,{text:"Other DKG nodes your node has an active network connection with"})]}),value:f!=null?String(f):"—",sub:f!=null?"live":"loading…",color:"var(--blue)"},{label:e.jsxs(e.Fragment,{children:["Agents Discovered ",e.jsx(H,{text:"AI agents discovered across the paranets your node participates in"})]}),value:N!=null?String(N):"—",sub:`Across ${h.length} paranet${h.length!==1?"s":""}`,color:"var(--amber)"}].map((c,w)=>e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"accent",style:{background:`linear-gradient(90deg,${c.color}44,transparent)`}}),e.jsx("div",{className:"stat-label",children:c.label}),e.jsx("div",{className:"stat-value mono",children:c.value}),e.jsx("div",{className:"stat-sub",children:c.sub})]},w))}),e.jsxs("div",{style:{position:"relative",height:340,borderRadius:12,overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",marginBottom:16},children:[e.jsxs("div",{style:{position:"absolute",top:14,left:18,zIndex:2,display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{className:"pulse-dot",style:{width:6,height:6,borderRadius:"50%",background:"var(--green)",boxShadow:"0 0 6px rgba(74,222,128,.53)",display:"inline-block"}}),e.jsx("span",{className:"mono",style:{fontSize:12,fontWeight:700},children:(s==null?void 0:s.networkName)??"DKG Network"}),e.jsx("span",{className:"mono",style:{fontSize:10,color:"var(--text-muted)"},children:f!=null?`${f} PEERS`:"… PEERS"}),e.jsx("span",{className:"mono",style:{fontSize:9,color:"var(--text-dim)",marginLeft:4},children:"scroll to zoom · drag to pan"})]}),e.jsx(Pe,{agents:(i==null?void 0:i.agents)??[],nodeName:(s==null?void 0:s.name)??""})]}),e.jsxs("div",{style:{marginBottom:16},children:[e.jsxs("div",{className:"section-title",children:["Paranets",!S&&e.jsx("span",{className:"mono",style:{fontSize:9,color:"var(--text-dim)",fontWeight:400},children:"DEMO"})]}),e.jsx("div",{className:"paranet-list",children:h.map((c,w)=>e.jsxs("div",{className:"paranet-card",onClick:()=>c.id&&t(`/explorer?paranet=${encodeURIComponent(c.id)}`),children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:6},children:[e.jsx("span",{style:{width:7,height:7,borderRadius:3,background:c.color,display:"inline-block"}}),e.jsx("h3",{style:{fontSize:13,fontWeight:600,margin:0},children:c.name}),e.jsx("span",{className:"pulse-dot",style:{width:5,height:5,borderRadius:"50%",background:"var(--green)",display:"inline-block",marginLeft:"auto"}})]}),e.jsxs("div",{className:"mono",style:{display:"flex",gap:14,fontSize:10,color:"var(--text-muted)"},children:[e.jsx(E,{text:"Knowledge Assets published to this paranet",children:e.jsxs("span",{children:[c.assets.toLocaleString()," assets"]})}),e.jsxs("span",{children:[c.agents," agents"]})]})]},c.id??`fallback-${w}`))})]}),e.jsx(Te,{}),e.jsxs("div",{className:"dashboard-grid-2",children:[e.jsx(Ee,{}),e.jsx(Le,{})]}),e.jsx("div",{className:"quick-actions",style:{marginBottom:16},children:[{label:"Query the Graph",desc:"SPARQL queries",icon:"⌘",onClick:()=>t("/explorer/sparql")},{label:"Import Memories",desc:"From Claude / ChatGPT",icon:"📥",onClick:()=>r(!0)},{label:"Play OriginTrail",desc:"Test your node",icon:"🎮",onClick:()=>t("/apps")}].map(c=>e.jsxs("button",{className:"quick-action",onClick:c.onClick,children:[e.jsx("span",{style:{fontSize:16},children:c.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"qa-label",children:c.label}),e.jsx("div",{className:"qa-desc",children:c.desc})]})]},c.label))})]})}export{Be as DashboardPage};